@agentprojectcontext/apx 1.53.4 → 1.53.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -619,7 +619,7 @@ Hechos estables que cualquier agente debería saber…`,agents_title:"Memorias d
619
619
 
620
620
  Stable facts that any agent should know…`,agents_title:"Agent memories",agents_desc:"Individual memory per agent. ~/.apx/projects/<id>/agents/<slug>/memory.md",no_agents:"No agents in this project.",saved:"Memory saved.",empty:"(empty memory)",chars:"chars · Markdown",save_btn:"Save"}},base:{title:"Base",subtitle:"General workspace · super-agent",nav_general:"General",nav_activity:"Activity",nav_system:"System",workspaces_title:"Workspaces",workspaces_desc:"All projects registered in APX.",workspaces_new:"New project",workspaces_empty:"No projects. Add one with the button above.",sessions_title:"Sessions",sessions_desc:"Sessions from all engines (apx · claude · codex), newest first.",sessions_all:"All engines",sessions_empty:"No sessions.",sessions_error:"Could not read sessions: {msg}",sessions_search_ph:"Search sessions…",sessions_deep:"Deep",sessions_deep_tip:"Also search inside transcripts (slower)",sessions_clear:"Clear filters",sessions_refresh:"Refresh list",sessions_no_match:"No sessions match “{q}”.",sessions_act_cmd:"Copy apx command",sessions_act_ask:"Ask {name} to continue",sessions_act_folder:"Open folder",sessions_act_path:"Copy path",sessions_cmd_copied:"Command copied — paste it in your terminal",sessions_path_copied:"Path copied",sessions_copy_failed:"Could not copy",sessions_no_folder:"This session has no folder",sessions_no_path:"This session has no path",sessions_folder_failed:"Could not open folder: {msg}",defaults_title:"Agent defaults",defaults_desc:"Global vault templates. Bundled ones come with APX and are always present; ones you create or edit go in ~/.apx/agents and override. Import them into a project from Agents › Import.",defaults_show_removed:"Show removed",defaults_new:"New",defaults_empty:"No templates in the vault.",defaults_hide:"Hide",defaults_restore:"Restore",defaults_edit:"Edit",defaults_remove:"Hide",defaults_delete:"Delete",defaults_tombstone_msg:`Hide the default "{slug}"? It's bundled — tombstoned and recoverable with Restore.`,defaults_delete_msg:'Delete the template "{slug}"?',defaults_hidden:"Hidden.",defaults_deleted:"Deleted.",defaults_restored:"Restored.",defaults_new_title:"New template",defaults_new_desc:"POST /agents/vault — saved to ~/.apx/agents/<slug>.md",defaults_edit_title:'Edit "{slug}"',defaults_bundled_desc:"This is a bundled default. Saving does a copy-on-write to ~/.apx/agents/<slug>.md (becomes an override).",defaults_user_desc:"PATCH /agents/vault/:slug — edits the file in ~/.apx/agents.",defaults_master_label:"Master agent",defaults_slug_invalid:"invalid slug (must match /^[a-z][a-z0-9_-]*$/)",defaults_created:'Template "{slug}" created.',defaults_saved:'Template "{slug}" saved.'},logs:{title:"Logs",desc_global:"Daemon activity (global channels: telegram, direct…). ~/.apx/messages/<channel>/.",desc_project:"Project activity. ~/.apx/projects/<id>/messages/.",filter_channel:"filter channel (e.g. telegram)",filter_dir:"direction",all_directions:"All directions",in:"Incoming (in)",out:"Outgoing (out)",filter_type:"type",all_types:"All types",search_text:"search text…",count_of:"of",no_activity:"No activity.",no_activity_ch:'No activity in channel "{ch}".',error:"Could not read messages: {msg}",show_more:"show more",show_less:"show less",daemon_errors:"Daemon errors (~/.apx/logs/errors.jsonl)",no_errors:"No errors recorded. 🎉"},telegram_contacts:{title:"Telegram contacts",desc:"Who writes to the bots. The role defines which tools they can use; a guest has no permissions until you assign a role.",empty:"No contacts yet — they register automatically when someone writes to a bot.",owner_badge:"owner",assign_role:"Assign role",owner_hint:"Channel owner — change it from the channel",removed:"Contact deleted.",delete_confirm:"Delete contact {name}?",last_seen:"seen:",tools_all:"tools: all",tools_none:"tools: none",tools_label:"tools:"},telegram_channels:{title:"Channels",desc:"Each channel is a bot the daemon polls. Here you can add/remove channels, change the answering agent, the project it belongs to and its owner.",new_btn:"New channel",empty:"No channels yet — add the first one.",removed:"Channel deleted.",delete_confirm:"Delete channel {name}?",no_owner:"no owner (claimed on first DM)",owner_label:"owner:"},telegram_channel_dialog:{new_title:"New Telegram channel",edit_title:"Edit channel: {name}",name_label:"name (internal slug)",token_label:"bot_token",chat_id:"chat_id",project_label:"project",project_hint:"Slug or id of the project to pin this channel to (optional).",route_label:"route_to_agent",route_hint:"Answering agent; empty = APX super-agent.",owner_label:"owner_user_id",owner_hint:"Telegram user_id of the channel owner. Overrides global role to 'owner' here. Leave empty — first private message claims it.",owner_ph:"889721252",respond_label:"Respond with engine (not echo)",name_required:"name required",saved:"Channel saved."},telegram_send_dialog:{title:"Send to {name}",default_msg:"Test message from APX panel ✅"},telegram_roles:{title:"Roles",desc:"Each role defines which super-agent tools the assigned user can invoke. 'owner' always = all; 'guest' always = none (chat only).",empty:"No roles defined.",tools_all:"all tools",tools_none:"no tools",builtin:"built-in",delete_confirm:'Delete role "{name}"?',removed:"Role deleted.",saved:'Role "{name}" saved.',name_required:"Name required.",builtin_error:'"{name}" is a built-in role.',new_title:"New role or replace a custom one",name_label:"Name",name_ph:"editor",tools_label:"Tools (comma-separated)",tools_hint:"Empty = none. Examples: call_agent, list_tasks, create_task.",tools_ph:"call_agent, list_tasks",full_access:"Full access (all tools)",save_btn:"Save role",delete_btn:"Delete"},superagent:{title:"{persona}",badge:"super-agent · APX",desc:"Quick chat with your super-agent. Has access to tools (projects, tasks, mcps, agents); for a longer persistent thread, open Chats.",empty:"Send {persona} a message to get started.",thinking:"{persona} is thinking…",talk:"Talk to {persona}",new_chat:"New chat",placeholder:"Type and press enter to send (shift+enter = new line)…"},not_found:{title:"404",message:"Roby got lost: this page doesn't exist or has moved.",home:"Back to home"},ask_panel:{answers_header:"Answers",other:"Other",other_placeholder:"Write your own answer here",text_placeholder:"Type your answer…",back:"Back",skip:"Skip",next:"Next",submit:"Send",status_waiting:"Waiting for your answer…",status_received:"Answers received"},code_module:{title:"Code",badge:"super-agent",desc:"OpenCode-style coding sessions. Pick a project, open a session, and ask it to read, plan, edit or run.",no_projects:"No registered projects. Register one with `apx project add` to use Code.",sessions:"Sessions",new_session:"New session",untitled:"New session",no_sessions:"No sessions yet — create one to start coding.",pick_project:"Pick a project to see its sessions.",rename:"Rename",delete:"Delete",delete_confirm:"Delete this session? The transcript is removed; your files are untouched.",empty_chat:"Send a coding instruction to get started.",placeholder:"Ask for a change… (enter sends, shift+enter = new line)",mode_build:"Build",mode_plan:"Plan",mode_build_hint:"Build — edits files and runs commands",mode_plan_hint:"Plan — read-only, proposes changes without touching files",tab_context:"Context",tab_changes:"Changes",tab_artifacts:"Artifacts",artifacts_none:"No artifacts yet. Ask the agent to create a script under `artifacts/<name>`.",artifacts_count:"{n} artifact(s)",artifacts_copy_path:"Copy path",artifacts_run:"Run",artifacts_run_hint:"Run it from your terminal:",artifacts_delete:"Delete",artifacts_delete_confirm:"Delete this artifact? The file will be removed from disk.",ctx_model:"Model",ctx_tokens:"Tokens",ctx_input:"Input",ctx_output:"Output",ctx_messages:"Messages",ctx_breakdown:"Context breakdown",ctx_none:"No usage yet — send a turn to see tokens.",seg_system:"System",seg_user:"User",seg_assistant:"Assistant",seg_tool:"Tools",seg_other:"Other",changes_none:"No changes in this session yet.",changes_no_git:"Changes need a git repository. This project isn't one.",changes_files:"{n} file(s) changed",stopped:"[stopped]",close:"Close",reload:"Reload",discard_changes:"Discard changes",save_shortcut_hint:"Save (Cmd/Ctrl+S)",artifacts_rename:"Rename",artifacts_view:"View contents",artifacts_edit:"Edit contents",tree_collapse_all:"Collapse all",terminal_clear:"Clear",terminal_close:"Close terminal"},desktop_screen:{status_title:"Status",autostart_title:"Auto-start",shortcut_title:"Keyboard shortcut",appearance_title:"Appearance",activation_title:"Activation + transcription",last_conv_title:"Last conversation",open_config:"Configuration"},voice_screen:{providers_title:"Voice providers (TTS)",test_title:"Test voice",stt_title:"Transcription (STT)",configure_provider:"Configure {name}"},deck_screen:{widgets_title:"Widgets",context_title:"APX context",reload_manifest:"Reload manifest",widget_native:"Native APX widget",widget_external:"External widget",preview_badge:"Preview",preview_title:"Deck — Coming soon",preview_body:"The Deck module is still in development and not released yet. We'll re-enable it once Deck ships in a stable release. For now everything here is read-only and no changes will be saved."},memory_panel:{embeddings_title:"Embeddings (RAG)",embeddings_desc:"Model that vectorizes the history of all channels for relevant memory. Just like TTS/STT: pick a provider and model. 'Automatic' tries local first and falls back to offline if nothing is available.",provider_label:"Provider",provider_hint:"Ollama is local and free. Gemini/OpenAI use the API key from their section in Models (or the one below).",mode_label:"Selection mode",mode_hint:"Chain falls back to the next if one fails; Single uses exactly the chosen provider.",available:"available",unavailable:"unavail.",test_btn:"Test embedding",reindex_btn:"Reindex memory",test_ok:"Embedding OK with {embedder}",test_failed:"Test failed: {msg}",reindexed:"Reindexed: {indexed} chunks (cleared {cleared}).",reindex_failed:"Reindex failed: {msg}",save_failed:"Could not save: {msg}",provider_auto:"Automatic (chain: Ollama → Gemini → OpenAI → offline)",provider_ollama:"Ollama — local, no API key (nomic-embed-text)",provider_gemini:"Gemini — free tier with key (text-embedding-004)",provider_openai:"OpenAI — text-embedding-3-small (cloud)",provider_tf:"Offline (term-frequency, no model — degraded)",mode_chain:"Chain (automatic fallback)",mode_single:"Single (uses only the chosen one)",ollama_title:"Ollama (local)",ollama_desc:"No API key. Runs nomic-embed-text on your local or cloud Ollama.",model_label:"Model",base_url_label:"Base URL",ollama_base_url_hint:"Empty uses engines.ollama.base_url (default http://localhost:11434).",openai_title:"OpenAI",openai_desc:"text-embedding-3-small (1536 dims) or another compatible model.",api_key_label:"API key",openai_key_hint:"Empty reuses engines.openai.api_key. Leave it blank to keep the saved one.",gemini_title:"Gemini",gemini_desc:"text-embedding-004 (768 dims). Free tier with a Google API key.",gemini_key_hint:"Empty reuses engines.gemini.api_key.",compaction_title:"History compaction",compaction_desc:"When a chat exceeds the turn threshold, the oldest turns are summarized with a lightweight (local) LLM and saved as [COMPACTED SUMMARY], keeping context bounded. Runs off the hot-path: the current turn uses whatever summary already exists.",threshold_label:"Compaction threshold",threshold_hint:"Compact once the chat exceeds these turns (default 60).",keep_recent_label:"Recent turns to preserve",keep_recent_hint:"Verbatim turns that are NEVER compacted (default 40). Must be lower than the threshold.",compact_model_label:"Compaction model",compact_model_hint:"Lightweight LLM for summarizing. Ideally a local one (Ollama) to avoid cost. Format provider:model.",compact_fallback_label:"Fallback model",compact_fallback_hint:"Used if the compaction one fails. Empty falls back to the super-agent model.",compact_fallback_ph:"(empty → super-agent model)"},router_panel:{title:"Model router",description:"A single general router (no per-task cases). Pick a provider and model; if the active one fails, it tries the fallback chain in order.",badge_default:"default",no_providers:"Add a provider below to be able to pick models.",active_model_label:"Active model (default)",active_model_hint:"Provider + model. Saved as provider:model.",fallback_title:"Fallback chain",fallback_desc:"If the active model fails, it tries these in order. Click one to edit it.",fallback_empty:"No fallback configured.",add_to_chain:"Add to the chain",done:"done",save:"Save router",saved:"Saved",saved_toast:"Router saved.",provider_ph:"— provider —",provider_not_found:"⚠ {name} (not found)",provider_not_configured:'The provider "{name}" is not configured.'},engines_panel:{title:"Providers",new_btn:"New provider",description:"LLM providers (API). Each provider uses an engine/adapter (openai, ollama, …) with its key and URL.",empty:"No providers. Add one with the button above.",add_card:"Add provider",saved:"Provider saved.",saved_json:"Provider saved (JSON).",deleted:"Provider deleted.",delete_confirm:"Delete provider {name}?"},providers_modal:{new_title:"New provider",edit_title:"Edit {name}",description:"LLM provider. The engine defines which adapter it uses (openai, ollama, …).",list_models_hint:"List the provider's actual models",toggle_active:"Active · click to deactivate",toggle_inactive:"Inactive · click to activate",delete:"Delete",custom:"Custom",json_mode:"JSON",form_mode:"Back to form",json_label:"Provider config (JSON)",json_hint:"Saved as engines.{slug} in config.json",json_help:"Must be a valid JSON object with at least engine. The slug is taken from the form.",name_label:"Name",name_ph:"My provider",engine_label:"Engine",base_url_label:"Base URL (base_url)",base_url_hint:"Auto-filled when you pick a provider.",base_url_ph:"https://api.openai.com/v1",api_key_label:"API key",api_key_hint_existing:"Leave blank to keep the current one.",api_key_hint_env:"Stored as a secret. Suggested env: {env}",api_key_hint:"Stored as a secret.",api_key_set:"…{suffix} (already set)",model_label:"Default model",load_models:"Load models",max_tokens_label:"Max tokens (max_tokens)",temperature_label:"Temperature: {value}",pricing_summary:"Token analysis / pricing (optional)",context_limit_label:"Context limit (tokens)",price_input:"$ input / 1M",price_output:"$ output / 1M",price_cache_read:"$ cache read / 1M",price_cache_write:"$ cache write / 1M",model_limits_label:"Per-model context limits (JSON)",active_label:"Active (agents can use it)",err_slug_required:"Slug required.",err_slug_required_form:"Slug required (in the form).",err_slug_exists:'A provider "{slug}" already exists.',err_model_limits_json:"Per-model context limits: invalid JSON.",err_json_invalid:"Invalid JSON: check the syntax.",err_json_object:"The JSON must be an object with the provider config.",err_engine_missing:'Missing "engine" (e.g. "anthropic", "ollama").',err_save:"Error saving.",err_no_models:"No models. Correct key/URL?",err_list_models:"Could not list models."},providers_card:{active:"Active",off:"Off",model:"Model",base_url:"Base URL",api_key:"API key",key_set:"✓ set",temp:"Temp",price_io:"$ in/out (1M)"},chat_ui:{copy:"Copy",stop:"Stop",send:"Send",pick_model:"Pick model (or Auto)",insert_variable:"Insert variable"},sidebar_ui:{toggle:"Toggle sidebar"},models_ui:{invalid_hint:"Model/provider unavailable"},global_config:{title:"APX config"},agent_detail_extra:{skills_title:"Skills & tools"},voice_ui:{api_key_label:"API key",api_key_set:"…{suffix} (already set)",api_key_keep_hint:"Leave blank to keep the current one.",api_key_secret_hint:"Stored as a secret. Env: {env}",api_key_reuse_hint:"Reuses {engine} if left blank. Env: {env}",err_save:"Error while saving.",model_label:"Model",voice_label:"Voice",format_label:"Format",output_format_label:"Output format",voice_id_label:"Voice ID",voice_id_hint:"ElevenLabs voice id (empty = default).",gemini_model_hint:"Gemini TTS is still in preview.",base_url_label:"Base URL (optional)",base_url_hint:"OpenAI-compatible endpoint. Empty = OpenAI. Point it at a local server (e.g. a QVox / Qwen3-TTS daemon) to use that instead.",openai_model_hint:"tts-1 / tts-1-hd for OpenAI. Leave blank to let a custom server pick.",openai_voice_hint:"OpenAI preset (alloy…) or a custom server's preset (e.g. custom). Empty = server default.",openai_style_hint:"Base voice / instruct, used by custom endpoints (the persona kept across the audio). Ignored by stock OpenAI tts-1.",style_label:"Style (how it should speak)",style_hint:"Natural-language instruction. Empty = no style. E.g.: 'speak in a cheerful, unhurried tone'.",style_ph:"speak in a cheerful, energetic tone",temperature_label:"Temperature (optional)",temperature_hint:"Sampling temperature for custom endpoints. Empty = server default.",emotions_short:"Emotions",emotions_label:"Inline emotion tags",emotions_hint:"When this engine speaks, let the agent drop [happy]/[whisper]-style tags into voice replies to color the delivery. Only enable it if this engine understands the tags (e.g. a QVox/Qwen3-TTS endpoint) — otherwise they're stripped before synthesis.",emotions_tags_label:"Allowed tags",emotions_tags_hint:"Comma-separated. Empty = the default set.",piper_bin_label:"Binary (bin)",piper_bin_hint:"Path or name of the piper CLI (PATH).",piper_model_label:"Model (.onnx)",piper_model_hint:"Absolute path to the piper voice model.",piper_speaker_label:"Speaker (optional)",piper_speaker_hint:"Speaker id for multi-voice models.",mock_desc:"The mock engine generates a silent test WAV. It has no parameters: it serves as a guaranteed fallback when no other engine is configured.",selection_mode:"Selection mode",mode_chain_desc:"Chain with fallback: uses the first available engine following the order below.",mode_single_desc:"Default engine only: always uses the chosen one; the rest stay configured for other purposes.",mode_chain_btn:"Chain (router)",mode_single_btn:"Default engine only",move_up:"Move up",move_down:"Move down",badge_local:"local",badge_available:"available",badge_unavailable:"configured, unavailable",badge_not_configured:"not configured",badge_default:"default",badge_custom:"custom",set_as_default:"Set as default",configure:"Configure",remove:"Remove",remove_confirm:"Remove this custom provider?",add_provider:"Add provider",new_provider:"New provider",custom_note:"Custom OpenAI-compatible endpoint.",custom_desc:"Any OpenAI-compatible speech endpoint (e.g. a local QVox / Qwen3-TTS server).",label_label:"Name",label_hint:"Display name for this provider.",base_url_req_label:"Base URL",base_url_req_hint:"Required. The OpenAI-compatible endpoint, e.g. http://127.0.0.1:5111/v1",api_key_optional_hint:"Optional — only if your server requires a key.",advanced:"Advanced",custom_model_hint:"Optional. Most local servers ignore it (e.g. QVox).",custom_voice_hint:"Optional. A preset your server understands (e.g. custom). Empty = server default.",custom_optional_ph:"(optional)",stt_engine_label:"Transcription engine",stt_engine_hint:"Local uses faster-whisper (requires python3 + faster-whisper). OpenAI uses the engines.openai key.",stt_model_label:"Local model (whisper)",stt_model_hint:"Bigger = more accurate and slower.",stt_language_label:"Language",stt_language_hint:'For Spanish, setting "Spanish" improves accuracy.',stt_provider_auto:"Automatic (local, then remote)",stt_provider_local:"Local — faster-whisper (offline)",stt_provider_openai:"OpenAI — Whisper-1 (cloud)",stt_provider_custom:"Custom — OpenAI-compatible server",stt_openai_model_label:"OpenAI model",stt_openai_model_hint:"Defaults to whisper-1.",stt_custom_baseurl_label:"Base URL (OpenAI-compatible)",stt_custom_baseurl_hint:"e.g. http://localhost:8000/v1 (mlx-audio on Metal) or http://192.168.1.50:9000/v1 (Radeon/NVIDIA on the LAN).",stt_custom_model_label:"Model",stt_custom_model_hint:"e.g. mlx-community/whisper-large-v3-turbo or large-v3.",stt_custom_key_hint:"Optional — most local servers need no key.",stt_hw_label:"Detected hardware",stt_hw_recommended:"Recommended",stt_hw_limited:"limited GPU acceleration, using CPU",stt_backend_label:"Acceleration / Engine",stt_backend_hint:"Auto adapts to your hardware. Metal runs on the GPU (mlx); CPU uses faster-whisper.",stt_backend_auto:"Automatic (recommended)",stt_model_needs_download:"Not downloaded (~{size}). The model must be downloaded to use this engine.",lang_auto:"Auto-detect",lang_es:"Spanish",lang_en:"English",lang_pt:"Portuguese",lang_fr:"French",lang_it:"Italian",lang_de:"German",test_default_text:"Hi, I'm APX. This is a voice test.",test_default_engine:"Default ({name})",test_default_chain:"Default (chain)",test_unavailable_suffix:" · unavailable",test_empty_error:"Type something to say.",test_synth_error:"Could not synthesize.",test_engine_label:"Engine",test_engine_hint:"Override the default for testing.",test_style_label:"Style (Gemini only)",test_style_hint:"How it should speak. Empty = no style.",test_text_label:"Text to say",test_text_ph:"Type what you want it to say…",say_this:"Say this",stop:"Stop",replay:"Replay",engine_result:"Engine",providers_desc:"Synthesis engines, in fallback order. Status is reported live by the daemon. Add your own OpenAI-compatible endpoints.",providers_load_error:"Could not load providers: {msg}",test_desc:"Pick which engine to synthesize with and, if applicable, how it should speak.",stt_desc:"Speech-to-text engine used by the deck, Telegram, and the CLI when listening.",toast_default_engine:"Default engine: {id}.",toast_mode_chain:"Mode: chain with fallback.",toast_mode_single:"Mode: default engine only.",toast_config_saved:"Voice configuration saved.",toast_provider_removed:"Provider removed.",err_label_required:"A name is required.",err_base_url_required:"A base URL is required.",toast_transcription_updated:"Transcription updated."},telegram_ui:{channel_dialog_desc:"POST /telegram/channels (upsert) — PATCH /telegram/channels/:name (partial).",bot_token_hint:"BotFather token. Stored in ~/.apx/config.json.",bot_token_hint_short:"BotFather token.",secret_set_replace:"(set — type to replace)",secret_already_set:"(already set)",empty_keep:"— empty = keep",message_sent:"Message sent.",message_label:"Text",send_chat_id:"chat_id: {id}",default_apx:"default APX",yes:"yes",no:"no",user_id_fallback:"user_id {id}",role_assigned:"{name} → {role}"},agents_ui:{model_router_default:"model: router default",slug_kebab_hint:"kebab-case, e.g. reviewer, my-agent, content-writer",comma_separated:"comma-separated",body_hint:"markdown — extends the agent's system prompt",source_user:"user",source_override:"override",source_bundled:"bundled",tab_explorer:"Explorer",type_none:"— no type —",type_orchestrator:"Orchestrator",type_orchestrator_desc:"Coordinates the team and delegates.",type_specialist:"Specialist",type_specialist_desc:"Domain expert; runs tasks.",type_assistant:"Assistant",type_assistant_desc:"Conversational helper.",type_worker:"Worker",type_worker_desc:"Runs autonomous tasks.",type_monitor:"Monitor",type_monitor_desc:"Watches state and reports.",stat_threads:"Threads",stat_records:"Records",stat_tasks:"Tasks",stat_heartbeats:"Heartbeats",config_def_desc:"definition (frontmatter + system prompt).",memory_durable_desc:"durable facts the agent remembers.",running:"running",paused:"paused",last_error:"last: error",field_tick:"Tick",field_next_tick:"Next tick",field_last_tick:"Last tick",field_last_run:"Last run",tools_label:"Tools",kind_agent:"agent",kind_memory:"memory",kind_thread:"thread",kind_task:"task",kind_routine:"routine",kind_hierarchy:"hierarchy",nodes_drag_hint:"{n} nodes · drag to rearrange",kind_exec_agent:"Project agent",kind_exec_agent_desc:"Runs a project agent with a prompt. You pick which one.",kind_super_agent:"Super-agent",kind_super_agent_desc:"Calls the APX super-agent with a prompt.",kind_telegram:"Telegram",kind_telegram_desc:"Sends a fixed message to a Telegram channel. No model or agent.",kind_shell:"Shell",kind_shell_desc:"Runs a shell command. No prompt or pre/post — the command is the action.",kind_heartbeat:"Heartbeat",kind_heartbeat_desc:"Does nothing except write a line to the logs each time it runs. Useful to confirm the scheduler is alive. If you don't know whether you need it, don't use it.",unit_seconds:"seconds",unit_minutes:"minutes",unit_hours:"hours",unit_days:"days",every_n_unit:"every {n} {unit}",every_v:"every {v}",preset_every_10m:"every 10 min",preset_hourly:"hourly",preset_daily_9am:"daily 9am",preset_weekdays_9am:"weekdays 9am",preset_manual:"Manual",var_pre_output_prompt:"Text output of the pre-commands. Replaced inside the prompt/text before it is sent. Use it to inject fresh data (weather, an API) into the instruction.",var_llm_output:"Final answer from the agent or super-agent. Available in the post-commands as an env var — e.g. forward it via Telegram.",var_status:"Action result: ok or error. Available in the post-commands to branch on what happened.",var_skipped:"1 if the action was skipped (via skip_prompt_on), 0 if it ran. Available in the post-commands.",var_pre_output:"Full pre-commands output, as an env var in the post-commands (up to 32k).",var_pre_output_file:"Path to a temp file with the pre-commands output. For large outputs not suited to an env var.",var_pre_exit:"Exit code of the last pre-command (0 = ok). Available in the post-commands.",var_routine:"Name of this routine. Available as an env var in the commands.",summary_runs_agent:'Runs the agent "{agent}"',summary_runs_agent_none:"Runs an agent (none chosen yet)",summary_super_agent:"Calls the super-agent",summary_telegram:'Sends Telegram to "{channel}"',summary_runs_cmd:"Runs: {cmd}",summary_shell:"Runs a shell command",summary_heartbeat:"Leaves a heartbeat in the logs",action_agent_answers:'Agent "{agent}" answers the prompt',action_agent_pick_answers:"Agent (pick one) answers the prompt",action_super_answers:"The super-agent answers the prompt",action_telegram_channel:'Sends Telegram to channel "{channel}"',action_runs_shell:"Runs the shell command",step_pre:"Pre",step_post:"Post",last_label:"last:",tg_chat_id_ph:"(uses the channel's)",tg_text_ph:"message to send",hb_message_ph:"still alive",arg_placeholder:"--flag or value",remove_arg:"remove arg",super_agent_label:"{persona} (super-agent)",super_agent_badge:"super-agent"},modules_ui:{desktop_pos_left:"Left",desktop_pos_center:"Center",desktop_pos_right:"Right",desktop_theme_system:"System",desktop_theme_light:"Light",desktop_theme_dark:"Dark",desktop_status_desc:"The window launches from the terminal or via autostart.",desktop_running:"Running",desktop_stopped:"Stopped",desktop_refresh:"refresh",desktop_start:"Start",desktop_stop:"Stop",desktop_restart:"Restart",desktop_restart_hint:"Reload the open window so config changes (theme, position) apply now.",desktop_restart_done:"Restarting the window — applying the latest config.",desktop_restart_none:"No desktop window is connected.",desktop_start_done:"Desktop window launched.",desktop_start_already:"Desktop window is already running.",desktop_stop_done:"Desktop window stopped.",desktop_stop_none:"No desktop window was running.",desktop_from_terminal:"From terminal:",desktop_autostart_desc:"Launches the window at user login. Equivalent to `apx desktop install` (no sudo required).",desktop_platform:"platform: {platform}",desktop_shortcut_desc:"Global hotkey that shows/hides the window and starts listening.",desktop_accelerator:"Accelerator",desktop_accelerator_hint:"Click the field and press your key combo. Restart the window to apply.",desktop_shortcut_record:"Click to set a shortcut",desktop_shortcut_recording:"Press your combo…",desktop_shortcut_change:"click to change",desktop_shortcut_esc:"Esc to cancel",desktop_shortcut_saved:"Shortcut saved. Restart the window (apx desktop stop && start) to apply it.",desktop_autostart_on:"Autostart enabled for the next login.",desktop_autostart_off:"Autostart disabled.",desktop_appearance_desc:"Window theme and position on the screen.",desktop_theme:"Theme",desktop_restart_apply:"Restart the window to apply.",desktop_theme_set:"Theme: {value}.",desktop_position:"Position",desktop_position_hint:'"left" / "center" / "right" of the top edge.',desktop_position_set:"Position: {value}.",desktop_activation_desc:"The daemon plugin processes the messages. STT is configured in Voices.",desktop_enabled_toast:"Desktop enabled.",desktop_disabled_toast:"Desktop disabled.",desktop_plugin_on:"Plugin enabled (replies to messages)",desktop_plugin_off:"Plugin disabled",desktop_stt_engine:"Speech-to-text engine:",desktop_stt_engine_suffix:"(local whisper, language, model).",desktop_last_conv_desc:"The latest exchange with the agent from the floating window.",desktop_no_messages:"No messages yet. Send something to the desktop window for it to appear here.",desktop_you:"You",desktop_roby:"Roby",desktop_empty_msg:"(empty)",deck_widget_enabled:"Widget {id} enabled.",deck_widget_disabled:"Widget {id} disabled.",deck_save_error:"Error while saving",deck_loading_manifest:"Loading manifest…",deck_manifest_error:"Error loading the manifest.",deck_widgets_summary:"{count} widgets · {enabled} external enabled",deck_loading_manifest_full:"Loading the Deck manifest…",deck_manifest_load_failed:"Could not load the Deck manifest.",deck_retry:"Retry",deck_no_widgets:"No widgets in the manifest.",deck_context_desc:"Information the Deck sees from the daemon.",deck_active_project:"Active project:",deck_none:"none",deck_registered_projects:"Registered projects:",deck_active_plugins:"Active plugins:",deck_daemon_active:"active · {uptime}",deck_daemon_started:"started",deck_safety_no_shell:"no direct shell",deck_safety_no_arbitrary:"arbitrary commands blocked",deck_safety_confirm:"dangerous actions require confirmation",code_copied:"Copied.",code_saved:"Saved.",code_file_empty:"(empty)",code_file_error:"Error: {msg}",code_stream_error:"error",code_super_agent:"super-agent",code_super_agent_desc:"Main agent with all tools",code_chat_tab:"Chat",code_panel_sessions:"Session list",code_panel_tree:"File tree",code_panel_terminal:"Terminal",code_panel_context:"Context panel",code_ctx_auto:"auto",code_ctx_mode:"Mode",code_ctx_agent:"Agent",code_ctx_msgs_value:"{user} user · {assistant} assistant",code_ctx_tokens_total:"Total Tokens",code_ctx_created:"Created",code_ctx_activity:"Activity",code_project_fallback:"project {id}",code_pick_project_ph:"Pick a project…",code_artifact_exit_ok:"exit 0 — {ms}ms",code_artifact_exit_fail:"exit {code}{timeout}",code_artifact_timeout_suffix:" (timeout)",code_artifact_view_short:"View",code_artifact_edit_short:"Edit",code_artifact_exit_badge:"exit {code}",code_artifact_timeout:"timeout",code_artifact_truncated:"truncated"},settings_ui:{bearer_label:"Bearer",global_config_desc:"General config in ~/.apx/config.json. Editable by tabs; JSON stays separate.",global_json_desc:"Redacted secrets are not overwritten.",save_json:"Save JSON",expand_menu:"Expand menu",collapse_menu:"Collapse menu",documentation:"Documentation",kind_personal:"Personal",kind_company:"Company",kind_app:"App",kind_software:"Software",kind_default:"Default",kind_other:"Other",base_menu_view:"Base menu view (general workspace).",coming_soon:"Coming soon",inspector_title:"Skill Inspector (per-turn RAG)",inspector_desc:"Experimental feature. When active, the agent does NOT receive the full skill list in its prompt; on each message a local RAG decides which skill(s) to load — the full body on a strong match, a suggestion on a medium match, nothing if it doesn't apply. It is re-evaluated every turn: a skill that stopped being relevant disappears from the context.",enable_inspector:"Enable inspector",enable_inspector_hint:"Off = classic behavior (slug list + passive suggestion). On = the RAG decides per turn.",on:"On",off:"Off",index_count:"Index: {n} skills",not_indexed:"not indexed",dim:"dim {dim}",updated_at:"updated {date}",reindex:"Reindex",reindex_forced:"Reindex (forced)",embedder_source:"The embedder comes from Memory (RAG). Local with Ollama, or offline if no provider is set.",thresholds_title:"Thresholds and limits",thresholds_desc:"Tune how aggressive the inspector is. Raising the thresholds = fewer false positives but more risk of missing a skill; lowering them = the opposite.",test_title:"Test (dry-run)",test_desc:"Type a message the way a user would and see which skills the inspector would load/suggest — without calling the model. Forces the inspector on even if it's off above.",test_placeholder:"e.g.: I need to create a promo video with voiceover",test_btn:"Test",jit_empty_index:"JIT (empty index)",loaded_label:"Loaded:",suggested_label:"Suggested:",could_not_save:"Could not save: {msg}",indexed_with:"Indexed with {embedder} (dim {dim}): +{added} ~{refreshed} -{removed}.",index_failed:"Index failed: {msg}",dry_run_failed:"Dry-run failed: {msg}",knob_load_threshold:"Load threshold",knob_load_threshold_hint:"Minimum similarity to inject the skill's BODY (high = stricter).",knob_hint_threshold:"Hint threshold",knob_hint_threshold_hint:"Minimum similarity to only SUGGEST the skill (so the agent loads it if it wants).",knob_margin:"Margin over the 2nd",knob_margin_hint:"The top must beat the second by this margin to load its body (avoids weak ties).",knob_max_loaded:"Max. loaded bodies",knob_max_loaded_hint:"How many skills are injected in full per turn.",knob_max_hints:"Max. hints",knob_max_hints_hint:"How many extra skills are named as a suggestion.",knob_prompt_floor:"Minimum prompt length",knob_prompt_floor_hint:"Messages shorter than this are ignored (avoids 'ok', 'hi').",knob_body_char_cap:"Body char cap",knob_body_char_cap_hint:"Trims long skill bodies so they don't bloat the context.",cfg_overrides_label:"Overrides",cfg_overrides_desc:".apc/config.json. Only project-specific values; empty inherits global/effective.",cfg_route_to_agent:"Route to agent",cfg_super_agent_model:"Super-agent model",cfg_permission_mode:"Permission mode",cfg_extra_prompt:"Extra prompt",cfg_telegram_label:"Telegram",cfg_chat_id:"Chat ID",cfg_bot_token:"Bot token",cfg_respond_with_engine:"Respond with engine",cfg_engines_label:"Engines",cfg_ollama_url:"Ollama URL",cfg_anthropic_key:"Anthropic API key",cfg_openai_key:"OpenAI API key",cfg_groq_key:"Groq API key",cfg_openrouter_key:"OpenRouter API key",cfg_gemini_key:"Gemini API key",cfg_project_label:"Project",cfg_project_desc:".apc/project.json. Portable APC metadata; no secrets, no runtime.",cfg_name:"Name",cfg_version:"Version",cfg_apc_spec:"APC spec",cfg_apx_install:"APX install state",cfg_apx_storage_id:"APX storage id"},shared_ui:{skill_inspector_title:"Skill Inspector ({embedder}) chose these skills for this turn",tools_count:"{n} tools",tool_read_file:"Read file",tool_write_file:"Write file",tool_edit_file:"Edit file",tool_list_files:"List files",tool_search_files:"Search in files",tool_search_messages:"Search messages",tool_tail_messages:"Latest messages",tool_run_shell:"Run shell",tool_send_telegram:"Send Telegram",tool_call_agent:"Call agent",tool_call_mcp:"Call MCP",tool_call_runtime:"Call runtime",tool_create_task:"Create task",dedup:"dedup",args:"args",result:"result",auto:"Auto",auto_router:"Auto (router decides)",model_filter_ph:"filter or type a model…",loading_models:"loading models…",use_value:"use “{value}”",model_combobox_ph:"pick or type a model…",search_variable_ph:"search variable…",no_matches:"no matches",create_variable:"Create new variable…",kv_key_ph:"KEY",kv_value_ph:"value",remove_row:"remove row",add_row:"Add row",err_chat_failed:"Chat failed.",err_stream_failed:"Stream failed.",err_load_conversation:"Could not load conversation.",err_stream:"Stream error."}},Vb={es:aD,en:rD};function oD(){try{const e=localStorage.getItem(Tn.language);if(e&&e in Vb)return e}catch{}return"en"}let rp=oD();function cC(e){rp=e;try{localStorage.setItem(Tn.language,e)}catch{}}const uC=[{value:"es",label:"Español"},{value:"en",label:"English"}];function qb(){return rp}function lD(e){const t=Vb[rp],s=e.split(".");let o=t;for(const l of s)if(o&&typeof o=="object"&&l in o)o=o[l];else return;return typeof o=="string"?o:void 0}function iD(e,t){return t?e.replace(/\{(\w+)\}/g,(s,o)=>o in t?String(t[o]):`{${o}}`):e}function cD(e){const t=lD(e);if(t!==void 0)return t;if(rp!=="es"){const s=Vb.es,o=e.split(".");let l=s;for(const c of o)if(l&&typeof l=="object"&&c in l)l=l[c];else return;return typeof l=="string"?l:void 0}}function f(e,t){const s=cD(e);return s===void 0?e:iD(s,t)}function $b(e){const[t,s]=x.useState(!1);x.useEffect(()=>{try{s(localStorage.getItem(e)==="true")}catch{}},[e]);const o=x.useCallback(()=>s(l=>{const c=!l;try{localStorage.setItem(e,String(c))}catch{}return c}),[e]);return{collapsed:t,toggle:o}}function uD({collapsed:e,onToggle:t}){return r.jsx(Ye,{content:f(e?"settings_ui.expand_menu":"settings_ui.collapse_menu"),side:"bottom",children:r.jsx("button",{type:"button",onClick:t,"aria-label":f(e?"settings_ui.expand_menu":"settings_ui.collapse_menu"),className:"flex size-7 shrink-0 items-center justify-center rounded-md text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:r.jsx(eS,{className:Te("size-4 transition-transform",e&&"rotate-180")})})})}function dD({sections:e,active:t,onChange:s,collapsed:o=!1}){return r.jsx("nav",{className:Te("hidden md:flex shrink-0 flex-col gap-1 py-3 transition-all",o?"w-12 items-center px-1":"w-52 px-2"),children:e.map((l,c)=>r.jsxs("div",{className:Te("w-full",c>0&&"mt-2"),children:[!o&&l.title&&r.jsx("p",{className:"mb-1 px-2 text-[9px] font-semibold uppercase tracking-wider text-muted-fg/70",children:l.title}),r.jsx("div",{className:"space-y-0.5",children:l.items.map(({key:u,label:p,icon:m,badge:g})=>{const h=t===u,b=r.jsxs("button",{type:"button",onClick:()=>s(u),"data-testid":`tabnav-${u||"index"}`,className:Te("flex cursor-pointer items-center rounded-lg transition-colors",o?"size-9 justify-center":"w-full gap-2 px-2.5 py-1.5",h?"bg-accent text-accent-fg":"text-muted-fg hover:bg-accent/60 hover:text-foreground"),children:[r.jsx(m,{className:"size-4 shrink-0"}),!o&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"flex-1 truncate text-left text-xs",children:p}),g!==void 0&&r.jsx("span",{className:"rounded-full bg-muted px-1.5 text-[9px] text-muted-fg",children:g})]})]});return o?r.jsx(Ye,{content:p,side:"right",children:b},u):r.jsx(x.Fragment,{children:b},u)})})]},c))})}const dC=0,fC=1,pC=2,Mj=3;var Oj=Object.prototype.hasOwnProperty;function ox(e,t){var s,o;if(e===t)return!0;if(e&&t&&(s=e.constructor)===t.constructor){if(s===Date)return e.getTime()===t.getTime();if(s===RegExp)return e.toString()===t.toString();if(s===Array){if((o=e.length)===t.length)for(;o--&&ox(e[o],t[o]););return o===-1}if(!s||typeof e=="object"){o=0;for(s in e)if(Oj.call(e,s)&&++o&&!Oj.call(t,s)||!(s in t)||!ox(e[s],t[s]))return!1;return Object.keys(t).length===o}}return e!==e&&t!==t}const Va=new WeakMap,$a=()=>{},Bn=$a(),lx=Object,kt=e=>e===Bn,aa=e=>typeof e=="function",zr=(e,t)=>({...e,...t}),mC=e=>aa(e.then),Kg={},jd={},Fb="undefined",Yc=typeof window!=Fb,ix=typeof document!=Fb,fD=Yc&&"Deno"in window,pD=()=>Yc&&typeof window.requestAnimationFrame!=Fb,gC=(e,t)=>{const s=Va.get(e);return[()=>!kt(t)&&e.get(t)||Kg,o=>{if(!kt(t)){const l=e.get(t);t in jd||(jd[t]=l),s[5](t,zr(l,o),l||Kg)}},s[6],()=>!kt(t)&&t in jd?jd[t]:!kt(t)&&e.get(t)||Kg]};let cx=!0;const mD=()=>cx,[ux,dx]=Yc&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[$a,$a],gD=()=>{const e=ix&&document.visibilityState;return kt(e)||e!=="hidden"},hD=e=>(ix&&document.addEventListener("visibilitychange",e),ux("focus",e),()=>{ix&&document.removeEventListener("visibilitychange",e),dx("focus",e)}),xD=e=>{const t=()=>{cx=!0,e()},s=()=>{cx=!1};return ux("online",t),ux("offline",s),()=>{dx("online",t),dx("offline",s)}},bD={isOnline:mD,isVisible:gD},_D={initFocus:hD,initReconnect:xD},zj=!Uc.useId,Al=!Yc||fD,vD=e=>pD()?window.requestAnimationFrame(e):setTimeout(e,1),Xg=Al?x.useEffect:x.useLayoutEffect,Qg=typeof navigator<"u"&&navigator.connection,Dj=!Al&&Qg&&(["slow-2g","2g"].includes(Qg.effectiveType)||Qg.saveData),wd=new WeakMap,yD=e=>lx.prototype.toString.call(e),Wg=(e,t)=>e===`[object ${t}]`;let jD=0;const fx=e=>{const t=typeof e,s=yD(e),o=Wg(s,"Date"),l=Wg(s,"RegExp"),c=Wg(s,"Object");let u,p;if(lx(e)===e&&!o&&!l){if(u=wd.get(e),u)return u;if(u=++jD+"~",wd.set(e,u),Array.isArray(e)){for(u="@",p=0;p<e.length;p++)u+=fx(e[p])+",";wd.set(e,u)}if(c){u="#";const m=lx.keys(e).sort();for(;!kt(p=m.pop());)kt(e[p])||(u+=p+":"+fx(e[p])+",");wd.set(e,u)}}else u=o?e.toJSON():t=="symbol"?e.toString():t=="string"?JSON.stringify(e):""+e;return u},Gb=e=>{if(aa(e))try{e=e()}catch{e=""}const t=e;return e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?fx(e):"",[e,t]};let wD=0;const px=()=>++wD;async function hC(...e){const[t,s,o,l]=e,c=zr({populateCache:!0,throwOnError:!0},typeof l=="boolean"?{revalidate:l}:l||{});let u=c.populateCache;const p=c.rollbackOnError;let m=c.optimisticData;const g=v=>typeof p=="function"?p(v):p!==!1,h=c.throwOnError;if(aa(s)){const v=s,k=[],N=t.keys();for(const j of N)!/^\$(inf|sub)\$/.test(j)&&v(t.get(j)._k)&&k.push(j);return Promise.all(k.map(b))}return b(s);async function b(v){const[k]=Gb(v);if(!k)return;const[N,j]=gC(t,k),[y,C,S,E]=Va.get(t),R=()=>{const V=y[k];return(aa(c.revalidate)?c.revalidate(N().data,v):c.revalidate!==!1)&&(delete S[k],delete E[k],V&&V[0])?V[0](pC).then(()=>N().data):N().data};if(e.length<3)return R();let A=o,T,M=!1;const z=px();C[k]=[z,0];const B=!kt(m),L=N(),U=L.data,D=L._c,I=kt(D)?U:D;if(B&&(m=aa(m)?m(I,U):m,j({data:m,_c:I})),aa(A))try{A=A(I)}catch(V){T=V,M=!0}if(A&&mC(A))if(A=await A.catch(V=>{T=V,M=!0}),z!==C[k][0]){if(M)throw T;return A}else M&&B&&g(T)&&(u=!0,j({data:I,_c:Bn}));if(u&&!M)if(aa(u)){const V=u(A,I);j({data:V,error:Bn,_c:Bn})}else j({data:A,error:Bn,_c:Bn});if(C[k][1]=px(),Promise.resolve(R()).then(()=>{j({_c:Bn})}),M){if(h)throw T;return}return A}}const Lj=(e,t)=>{for(const s in e)e[s][0]&&e[s][0](t)},kD=(e,t)=>{if(!Va.has(e)){const s=zr(_D,t),o=Object.create(null),l=hC.bind(Bn,e);let c=$a;const u=Object.create(null),p=(h,b)=>{const v=u[h]||[];return u[h]=v,v.push(b),()=>{const k=v.indexOf(b);k>=0&&(v[k]=v[v.length-1],v.pop())}},m=(h,b,v)=>{e.set(h,b);const k=u[h];if(k)for(const N of k)N(b,v)},g=()=>{if(!Va.has(e)&&(Va.set(e,[o,Object.create(null),Object.create(null),Object.create(null),l,m,p]),!Al)){const h=s.initFocus(setTimeout.bind(Bn,Lj.bind(Bn,o,dC))),b=s.initReconnect(setTimeout.bind(Bn,Lj.bind(Bn,o,fC)));c=()=>{h&&h(),b&&b(),Va.delete(e)}}};return g(),[e,l,g,c]}return[e,Va.get(e)[4]]},SD=(e,t,s,o,l)=>{const c=s.errorRetryCount,u=l.retryCount,p=~~((Math.random()+.5)*(1<<(u<8?u:8)))*s.errorRetryInterval;!kt(c)&&u>c||setTimeout(o,p,l)},CD=ox,[xC,bC]=kD(new Map),ND=zr({onLoadingSlow:$a,onSuccess:$a,onError:$a,onErrorRetry:SD,onDiscarded:$a,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Dj?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Dj?5e3:3e3,compare:CD,isPaused:()=>!1,cache:xC,mutate:bC,fallback:{}},bD),ED=(e,t)=>{const s=zr(e,t);if(t){const{use:o,fallback:l}=e,{use:c,fallback:u}=t;o&&c&&(s.use=o.concat(c)),l&&u&&(s.fallback=zr(l,u))}return s},RD=x.createContext({}),TD="$inf$",_C=Yc&&window.__SWR_DEVTOOLS_USE__,AD=_C?window.__SWR_DEVTOOLS_USE__:[],MD=()=>{_C&&(window.__SWR_DEVTOOLS_REACT__=Uc)},OD=e=>aa(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}],vC=()=>{const e=x.useContext(RD);return x.useMemo(()=>zr(ND,e),[e])},zD=e=>(t,s,o)=>e(t,s&&((...c)=>{const[u]=Gb(t),[,,,p]=Va.get(xC);if(u.startsWith(TD))return s(...c);const m=p[u];return kt(m)?s(...c):(delete p[u],m)}),o),DD=AD.concat(zD),LD=e=>function(...s){const o=vC(),[l,c,u]=OD(s),p=ED(o,u);let m=e;const{use:g}=p,h=(g||[]).concat(DD);for(let b=h.length;b--;)m=h[b](m);return m(l,c||p.fetcher||null,p)},PD=(e,t,s)=>{const o=t[e]||(t[e]=[]);return o.push(s),()=>{const l=o.indexOf(s);l>=0&&(o[l]=o[o.length-1],o.pop())}};MD();const Zg=Uc.use||(e=>{switch(e.status){case"pending":throw e;case"fulfilled":return e.value;case"rejected":throw e.reason;default:throw e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e}}),Jg={dedupe:!0},ff=Promise.resolve(Bn);ff.status="fulfilled";ff.value=Bn;const ID=()=>$a,BD=(e,t,s)=>{const{cache:o,compare:l,suspense:c,fallbackData:u,revalidateOnMount:p,revalidateIfStale:m,refreshInterval:g,refreshWhenHidden:h,refreshWhenOffline:b,keepPreviousData:v,strictServerPrefetchWarning:k}=s,[N,j,y,C]=Va.get(o),[S,E]=Gb(e),R=x.useRef(!1),A=x.useRef(!1),T=x.useRef(S),M=x.useRef(t),z=x.useRef(s),B=()=>z.current,L=()=>B().isVisible()&&B().isOnline(),[U,D,I,V]=gC(o,S),$=x.useRef({}).current,q=kt(u)?kt(s.fallback)?Bn:s.fallback[S]:u,Y=(we,Ee)=>{for(const ve in $){const Ce=ve;if(Ce==="data"){if(!l(we[Ce],Ee[Ce])&&(!kt(we[Ce])||!l(fe,Ee[Ce])))return!1}else if(Ee[Ce]!==we[Ce])return!1}return!0},K=!R.current,F=x.useMemo(()=>{const we=U(),Ee=V(),ve=Ie=>{const se=zr(Ie);return delete se._k,(()=>{if(!S||!t||B().isPaused())return!1;if(K&&!kt(p))return p;const $e=kt(q)?se.data:q;return kt($e)||m})()?{isValidating:!0,isLoading:!0,...se}:se},Ce=ve(we),Le=we===Ee?Ce:ve(Ee);let Pe=Ce;return[()=>{const Ie=ve(U());return Y(Ie,Pe)?(Pe.data=Ie.data,Pe.isLoading=Ie.isLoading,Pe.isValidating=Ie.isValidating,Pe.error=Ie.error,Pe):(Pe=Ie,Ie)},()=>Le]},[o,S]),X=rf.useSyncExternalStore(x.useCallback(we=>I(S,(Ee,ve)=>{Y(ve,Ee)||we()}),[o,S]),F[0],F[1]),P=N[S]&&N[S].length>0,G=X.data,Z=kt(G)?q&&mC(q)?Zg(q):q:G,ee=X.error,de=x.useRef(Z),fe=v?kt(G)?kt(de.current)?Z:de.current:G:Z,ae=S&&kt(Z),oe=x.useRef(null);!Al&&rf.useSyncExternalStore(ID,()=>(oe.current=!1,oe),()=>(oe.current=!0,oe));const me=oe.current;k&&me&&!c&&ae&&console.warn(`Missing pre-initiated data for serialized key "${S}" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);const Ae=!S||!t||B().isPaused()||P&&!kt(ee)?!1:K&&!kt(p)?p:c?kt(Z)?!1:m:kt(Z)||m,ie=K&&Ae,pe=kt(X.isValidating)?ie:X.isValidating,Se=kt(X.isLoading)?ie:X.isLoading,je=x.useCallback(async we=>{const Ee=M.current;if(!S||!Ee||A.current||B().isPaused())return!1;let ve,Ce,Le=!0;const Pe=we||{},Ie=!y[S]||!Pe.dedupe,se=()=>zj?!A.current&&S===T.current&&R.current:S===T.current,be={isValidating:!1,isLoading:!1},$e=()=>{D(be)},Re=()=>{const We=y[S];We&&We[1]===Ce&&delete y[S]},ze={isValidating:!0};kt(U().data)&&(ze.isLoading=!0);try{if(Ie&&(D(ze),s.loadingTimeout&&kt(U().data)&&setTimeout(()=>{Le&&se()&&B().onLoadingSlow(S,s)},s.loadingTimeout),y[S]=[Ee(E),px()]),[ve,Ce]=y[S],ve=await ve,Ie&&setTimeout(Re,s.dedupingInterval),!y[S]||y[S][1]!==Ce)return Ie&&se()&&B().onDiscarded(S),!1;be.error=Bn;const We=j[S];if(!kt(We)&&(Ce<=We[0]||Ce<=We[1]||We[1]===0))return $e(),Ie&&se()&&B().onDiscarded(S),!1;const at=U().data;be.data=l(at,ve)?at:ve,Ie&&se()&&B().onSuccess(ve,S,s)}catch(We){Re();const at=B(),{shouldRetryOnError:yt}=at;at.isPaused()||(be.error=We,Ie&&se()&&(at.onError(We,S,at),(yt===!0||aa(yt)&&yt(We))&&(!B().revalidateOnFocus||!B().revalidateOnReconnect||L())&&at.onErrorRetry(We,S,at,_e=>{const Oe=N[S];Oe&&Oe[0]&&Oe[0](Mj,_e)},{retryCount:(Pe.retryCount||0)+1,dedupe:!0})))}return Le=!1,$e(),!0},[S,o]),Be=x.useCallback((...we)=>hC(o,T.current,...we),[]);if(Xg(()=>{M.current=t,z.current=s,kt(G)||(de.current=G)}),Xg(()=>{if(!S)return;const we=je.bind(Bn,Jg);let Ee=0;B().revalidateOnFocus&&(Ee=Date.now()+B().focusThrottleInterval);const Ce=PD(S,N,(Le,Pe={})=>{if(Le==dC){const Ie=Date.now();B().revalidateOnFocus&&Ie>Ee&&L()&&(Ee=Ie+B().focusThrottleInterval,we())}else if(Le==fC)B().revalidateOnReconnect&&L()&&we();else{if(Le==pC)return je();if(Le==Mj)return je(Pe)}});return A.current=!1,T.current=S,R.current=!0,D({_k:E}),Ae&&(y[S]||(kt(Z)||Al?we():vD(we))),()=>{A.current=!0,Ce()}},[S]),Xg(()=>{let we;function Ee(){const Ce=aa(g)?g(U().data):g;Ce&&we!==-1&&(we=setTimeout(ve,Ce))}function ve(){!U().error&&(h||B().isVisible())&&(b||B().isOnline())?je(Jg).then(Ee):Ee()}return Ee(),()=>{we&&(clearTimeout(we),we=-1)}},[g,h,b,S]),x.useDebugValue(fe),c){if(!zj&&Al&&ae)throw new Error("Fallback data is required when using Suspense in SSR.");ae&&(M.current=t,z.current=s,A.current=!1);const we=C[S],Ee=!kt(we)&&ae?Be(we):ff;if(Zg(Ee),!kt(ee)&&ae)throw ee;const ve=ae?je(Jg):ff;!kt(fe)&&ae&&(ve.status="fulfilled",ve.value=!0),Zg(ve)}return{mutate:Be,get data(){return $.data=!0,fe},get error(){return $.error=!0,ee},get isValidating(){return $.isValidating=!0,pe},get isLoading(){return $.isLoading=!0,Se}}},et=LD(BD);let ql=null;function fo(e){ql=e}function Yb(){return ql}class Kc extends Error{status;body;constructor(t,s,o){super(s),this.status=t,this.body=o}}async function Ji(e,t,s,o={}){const l={"content-type":"application/json",...ql?{authorization:`Bearer ${ql}`}:{},...o.headers||{}},c=await fetch(t,{...o,method:e,headers:l,body:s!==void 0?JSON.stringify(s):void 0});if(!c.ok){let u="",p=null;try{p=await c.json(),u=p?.error||JSON.stringify(p)}catch{u=await c.text()}throw new Kc(c.status,`${e} ${t} → ${c.status}: ${u}`,p)}if(c.status!==204)return await c.json()}function wl(e){const t=e;if(Array.isArray(e))return{items:e,total:e.length};if(t&&Array.isArray(t.data)){const s=t.data;return{items:s,total:typeof t.meta?.total=="number"?t.meta.total:s.length}}if(t&&Array.isArray(t.sessions)){const s=t.sessions;return{items:s,total:s.length}}return{items:[],total:0}}const ge={get:e=>Ji("GET",e),post:(e,t)=>Ji("POST",e,t),put:(e,t)=>Ji("PUT",e,t),patch:(e,t)=>Ji("PATCH",e,t),del:e=>Ji("DELETE",e)};async function yC(e,t,s,o){const l=await fetch(e,{method:"POST",signal:o,headers:{"content-type":"application/json",...ql?{authorization:`Bearer ${ql}`}:{}},body:JSON.stringify(t)});if(!l.ok||!l.body){const m=await l.text().catch(()=>"");throw new Kc(l.status,`POST ${e} → ${l.status}: ${m||"stream failed"}`)}const c=l.body.getReader(),u=new TextDecoder("utf-8");let p="";for(;;){const{value:m,done:g}=await c.read();if(g)break;p+=u.decode(m,{stream:!0});let h=p.indexOf(`
621
621
  `);for(;h>=0;){const b=p.slice(0,h).trim();if(p=p.slice(h+1),b)try{s(JSON.parse(b))}catch{}h=p.indexOf(`
622
- `)}}if(p.trim())try{s(JSON.parse(p.trim()))}catch{}}const UD={get:()=>ge.get("/health")},ls={list:()=>ge.get("/projects"),register:e=>ge.post("/projects",{path:e}),remove:e=>ge.del(`/projects/${encodeURIComponent(e)}`),rebuild:e=>ge.post(`/projects/${encodeURIComponent(e)}/rebuild`),config:{show:e=>ge.get(`/projects/${e}/config`),set:(e,t)=>ge.patch(`/projects/${e}/config`,{set:t}),unset:(e,t)=>ge.patch(`/projects/${e}/config`,{unset:t}),put:(e,t)=>ge.put(`/projects/${e}/config`,t)},apcProject:{set:(e,t,s)=>ge.patch(`/projects/${e}/apc-project`,{set:t,unset:s}),put:(e,t)=>ge.put(`/projects/${e}/apc-project`,t)},memory:{get:e=>ge.get(`/projects/${e}/memory`),put:(e,t)=>ge.put(`/projects/${e}/memory`,{body:t})}},rn={list:e=>ge.get(`/projects/${e}/agents`),get:(e,t)=>ge.get(`/projects/${e}/agents/${t}`),create:(e,t)=>ge.post(`/projects/${e}/agents`,t),update:(e,t,s)=>ge.patch(`/projects/${e}/agents/${encodeURIComponent(t)}`,s),remove:(e,t)=>ge.del(`/projects/${e}/agents/${encodeURIComponent(t)}`),chat:(e,t,s)=>ge.post(`/projects/${e}/agents/${encodeURIComponent(t)}/chat`,s),memory:{get:(e,t)=>ge.get(`/projects/${e}/agents/${t}/memory`),put:(e,t,s)=>ge.put(`/projects/${e}/agents/${t}/memory`,{body:s})},vault:e=>ge.get(e?.includeRemoved?"/agents/vault?include_removed=1":"/agents/vault"),vaultCreate:(e,t={},s="")=>ge.post("/agents/vault",{slug:e,fields:t,body:s}),vaultPatch:(e,t)=>ge.patch(`/agents/vault/${encodeURIComponent(e)}`,t),vaultRemove:e=>ge.del(`/agents/vault/${encodeURIComponent(e)}`),vaultRestore:e=>ge.post(`/agents/vault/${encodeURIComponent(e)}/restore`),import:(e,t)=>ge.post(`/projects/${e}/agents/import`,{slug:t})},Kb={list:(e,t)=>ge.get(`/projects/${e}/agents/${t}/conversations`),get:(e,t,s)=>ge.get(`/projects/${e}/agents/${t}/conversations/${s}`),compact:(e,t,s)=>ge.post(s?`/projects/${e}/agents/${t}/conversations/${s}/compact`:`/projects/${e}/agents/${t}/compact`,{})},Cr={list:e=>ge.get(`/projects/${e}/routines`),get:(e,t)=>ge.get(`/projects/${e}/routines/${t}`),run:(e,t)=>ge.post(`/projects/${e}/routines/${t}/run`),enable:(e,t)=>ge.post(`/projects/${e}/routines/${t}/enable`),disable:(e,t)=>ge.post(`/projects/${e}/routines/${t}/disable`),upsert:(e,t)=>ge.post(`/projects/${e}/routines`,t),remove:(e,t)=>ge.del(`/projects/${e}/routines/${encodeURIComponent(t)}`)},Nr={list:(e,t="open")=>ge.get(`/projects/${e}/tasks?state=${t}`).then(s=>wl(s).items),global:(e="open")=>ge.get(`/tasks?state=${e}`).then(t=>wl(t).items),listPage:(e,{state:t,limit:s,offset:o})=>ge.get(`/projects/${e}/tasks?state=${t}&limit=${s}&offset=${o}`).then(l=>wl(l)),globalPage:({state:e,limit:t,offset:s})=>ge.get(`/tasks?state=${e}&limit=${t}&offset=${s}`).then(o=>wl(o)),add:(e,t)=>ge.post(`/projects/${e}/tasks`,t),done:(e,t)=>ge.post(`/projects/${e}/tasks/${t}/done`),drop:(e,t)=>ge.post(`/projects/${e}/tasks/${t}/drop`),reopen:(e,t)=>ge.post(`/projects/${e}/tasks/${t}/reopen`)},Er={list:e=>ge.get(`/projects/${e}/mcps`),check:e=>ge.get(`/projects/${e}/mcps/check`),add:(e,t,s)=>ge.post(`/projects/${e}/mcps?scope=${t}`,s),remove:(e,t,s="shared")=>ge.del(`/projects/${e}/mcps/${encodeURIComponent(t)}?scope=${s}`),test:(e,t)=>ge.post(`/projects/${e}/mcps/${encodeURIComponent(t)}/test`,{}),logs:(e,t)=>ge.get(`/projects/${e}/mcps/${encodeURIComponent(t)}/logs`)},Dc={list:(e,t={})=>ge.get(`/projects/${e}/vars${t.reveal?"?reveal=1":""}`),get:(e,t,s={})=>ge.get(`/projects/${e}/vars/${encodeURIComponent(t)}${s.reveal?"?reveal=1":""}`),upsert:(e,t)=>ge.post(`/projects/${e}/vars`,t),remove:(e,t,s="project")=>ge.del(`/projects/${e}/vars/${encodeURIComponent(t)}?scope=${s}`)},eh=e=>{const t=new URLSearchParams;for(const[o,l]of Object.entries(e))l!==void 0&&l!==""&&t.set(o,String(l));const s=t.toString();return s?`?${s}`:""},pf={global:(e={})=>ge.get(`/messages/global${eh(e)}`),project:(e,t={})=>ge.get(`/projects/${e}/messages${eh(t)}`),search:(e,t,s=50)=>ge.get(`/projects/${e}/messages/search${eh({q:t,limit:s})}`)},HD={global:e=>ge.get(`/sessions${e?`?engine=${encodeURIComponent(e)}`:""}`).then(t=>({sessions:wl(t).items})),page:({engine:e,q:t,deep:s,limit:o,offset:l})=>{const c=new URLSearchParams({limit:String(o),offset:String(l)});return e&&c.set("engine",e),t?.trim()&&c.set("q",t.trim()),s&&c.set("deep","1"),ge.get(`/sessions?${c.toString()}`).then(u=>wl(u))}},VD={list:()=>ge.get("/tools")},An={channels:{list:()=>ge.get("/telegram/channels"),upsert:e=>ge.post("/telegram/channels",e),patch:(e,t)=>ge.patch(`/telegram/channels/${e}`,t),remove:e=>ge.del(`/telegram/channels/${encodeURIComponent(e)}`)},contacts:{list:()=>ge.get("/telegram/contacts"),patch:(e,t)=>ge.patch(`/telegram/contacts/${encodeURIComponent(String(e))}`,t),remove:e=>ge.del(`/telegram/contacts/${encodeURIComponent(String(e))}`)},roles:{list:()=>ge.get("/telegram/roles"),set:(e,t)=>ge.put(`/telegram/roles/${encodeURIComponent(e)}`,{tools:t}),remove:e=>ge.del(`/telegram/roles/${encodeURIComponent(e)}`)},status:()=>ge.get("/telegram/status"),start:()=>ge.post("/telegram/start"),stop:()=>ge.post("/telegram/stop"),send:e=>ge.post("/telegram/send",e)},mf={list:()=>ge.get("/engines"),models:e=>ge.post("/engines/models",e)},$l={reload:()=>ge.post("/admin/reload"),shutdown:()=>ge.post("/admin/shutdown"),config:{get:()=>ge.get("/admin/config"),patch:e=>ge.patch("/admin/config",e)},superAgent:()=>ge.get("/admin/super-agent"),logs:(e="errors",t=200)=>ge.get(`/admin/logs?file=${e}&limit=${t}`)},Fl={list:()=>ge.get("/pair/list"),revoke:e=>ge.del(`/pair/revoke/${encodeURIComponent(e)}`),init:()=>ge.post("/pair/init",{}),status:e=>ge.get(`/pair/status/${encodeURIComponent(e)}`),confirm:e=>ge.post("/pair/confirm",e)},Pj={get:()=>ge.get("/identity"),patch:e=>ge.patch("/identity",e)},jC={send:(e,t)=>ge.post(`/projects/${e}/super-agent/chat`,t),stream:(e,t,s,o)=>yC(`/projects/${e}/super-agent/chat/stream`,t,s,o),summarize:e=>ge.post("/super-agent/summarize",e)},Ij={dirs:e=>ge.get(`/admin/fs/dirs?path=${encodeURIComponent(e)}`),pickDir:e=>ge.get(`/admin/fs/pick-dir${e?`?prompt=${encodeURIComponent(e)}`:""}`)},qD=["alloy","echo","fable","onyx","nova","shimmer"],$D=["Kore","Puck","Charon","Fenrir","Aoede"],FD=["eleven_multilingual_v2","eleven_turbo_v2_5","eleven_flash_v2_5"],GD=["tts-1","tts-1-hd"],YD=["happy","sad","excited","angry","calm","whisper","shout","laugh","cry","narrator","neutral"],KD=["tiny","base","small","medium","large-v2","large-v3","large-v3-turbo"],gf={piper:{name:"Piper",note:"Local, offline (CLI + .onnx model). No API key.",local:!0},elevenlabs:{name:"ElevenLabs",note:"Cloud, multilingual. Requires an API key."},openai:{name:"OpenAI",note:"Cloud (tts-1 / tts-1-hd) or any OpenAI-compatible endpoint (set a base URL for a local server, e.g. QVox)."},gemini:{name:"Gemini",note:"Cloud (preview). Uses your Gemini key."},mock:{name:"Mock",note:"Silent test engine. Always available as a fallback.",local:!0}};async function XD(e){const t=Yb(),s=await fetch(`/voice/tts?path=${encodeURIComponent(e)}`,{headers:t?{authorization:`Bearer ${t}`}:{}});if(!s.ok){const l=await s.text().catch(()=>"");throw new Error(`No se pudo leer el audio (${s.status}): ${l.slice(0,160)}`)}const o=await s.blob();return URL.createObjectURL(o)}const hf={providers:()=>ge.get("/tts/providers"),sttHardware:()=>ge.get("/transcribe/hardware"),sttModels:e=>ge.get(`/transcribe/models?backend=${e}`),say:e=>ge.post("/tts/say",e),turn:e=>ge.post("/voice/turn",e)},wC={manifest:()=>ge.get("/deck/manifest"),setWidget:(e,t)=>ge.patch(`/deck/widgets/${encodeURIComponent(e)}`,t),exec:e=>ge.post("/deck/exec",e)},lo=e=>`/projects/${e}/code/sessions`,Ba={sessions:{list:e=>ge.get(lo(e)).then(t=>t.sessions),get:(e,t)=>ge.get(`${lo(e)}/${t}`),create:(e,t={})=>ge.post(lo(e),t),update:(e,t,s)=>ge.patch(`${lo(e)}/${t}`,s),remove:(e,t)=>ge.del(`${lo(e)}/${t}`)},changes:(e,t)=>ge.get(`${lo(e)}/${t}/changes`),stream:(e,t,s,o,l)=>yC(`${lo(e)}/${t}/chat/stream`,s,o,l)},Ml={list:e=>ge.get(`/projects/${encodeURIComponent(e)}/artifacts`),read:(e,t)=>ge.get(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),run:(e,t,s=[])=>ge.post(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}/run`,{args:s}),remove:(e,t)=>ge.del(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),write:(e,t,s)=>ge.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{content:s}),rename:(e,t,s)=>ge.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{newName:s})},fc={list:e=>ge.get(e?`/skills?project_path=${encodeURIComponent(e)}`:"/skills"),inspector:()=>ge.get("/skills/inspector"),updateInspector:e=>ge.put("/skills/inspector",e),index:(e={})=>ge.post("/skills/index",e),inspect:(e,t)=>ge.post("/skills/inspect",{prompt:e,project_path:t})};function Xc(){const{data:e,error:t,isLoading:s,mutate:o}=et("/projects",()=>ls.list(),{refreshInterval:Of.projects});return{projects:(e||[]).slice().sort((c,u)=>{const p=Number(c.id),m=Number(u.id);return p===0&&m!==0?-1:m===0&&p!==0?1:p-m}),error:t,isLoading:s,mutate:o}}function Xb(e){const{projects:t,isLoading:s,mutate:o}=Xc();return{project:t.find(c=>String(c.id)===e)??null,isLoading:s,mutate:o}}function Qb(){const{data:e,error:t,isLoading:s,mutate:o}=et("/identity",()=>Pj.get());return{identity:e||{},error:t,isLoading:s,mutate:o,save:async c=>{const u=await Pj.patch(c);return await o(u,{revalidate:!1}),u}}}function op(){const{identity:e}=Qb();return e?.agent_name?.trim()||"APX"}function QD(){return[{id:"desktop",label:f("nav.modules.desktop"),href:"/m/desktop",icon:qx},{id:"code",label:f("nav.modules.code"),href:"/m/code",icon:Ya}]}function WD(e,t,s){const[o,l]=x.useState(t);return x.useLayoutEffect(()=>{const c=e.current;if(!c||!s)return;const u=()=>{const m=c.clientHeight;if(!m)return;const g=parseFloat(getComputedStyle(c).rowGap)||12,b=(c.querySelector("[data-rail-probe]")?.offsetHeight??56)+g,k=Math.max(0,Math.floor((m+g)/b))-1;l(k>=t?t:Math.max(0,k-1))};u();const p=new ResizeObserver(u);return p.observe(c),()=>p.disconnect()},[e,t,s]),s?Math.min(o,t):t}function Bj({projects:e,label:t,sublabel:s,icon:o,tooltip:l,header:c,active:u,testId:p,onSelect:m,isActive:g}){return r.jsxs(oC,{children:[r.jsxs(lC,{"data-testid":p,title:l,"aria-label":l,className:"group flex w-full cursor-pointer flex-col items-center gap-1",children:[r.jsx("span",{className:Te("flex size-10 items-center justify-center rounded-xl text-xs font-bold transition-all","bg-muted/40 text-muted-fg hover:bg-accent hover:text-foreground",u&&"ring-2 ring-foreground ring-offset-2 ring-offset-card"),children:o??t}),s&&r.jsx("span",{className:"block max-w-[3.6rem] truncate text-[9px] leading-tight text-muted-fg group-hover:text-foreground",children:s})]}),r.jsxs(iC,{side:"right",align:"start",sideOffset:8,className:"max-h-[70vh] w-64",children:[r.jsx("div",{className:"px-1.5 py-1 text-xs font-medium text-muted-foreground",children:c}),e.map(h=>{const b=h.name||h.path.split("/").pop()||String(h.id),v=`/p/${h.id}`,{initials:k,idleClass:N}=az(b);return r.jsxs(tD,{"data-testid":`project-menu-item-${h.id}`,onClick:()=>m(v),className:Te(g(v)&&"bg-accent/60 text-foreground"),children:[r.jsx("span",{className:Te("flex size-6 shrink-0 items-center justify-center rounded-md text-[10px] font-bold",N),children:k}),r.jsx("span",{className:"truncate",children:b})]},h.id)})]})]})}function ZD({onSelect:e,onOpenRoby:t,onOpenAddProject:s}){const{projects:o,isLoading:l}=Xc(),c=Qn(),u=QD(),p=op(),m=x.useRef(null),{collapsed:g,toggle:h}=$b(Tn.sidebarCollapsed+".projects"),b=S=>c.pathname===S||c.pathname.startsWith(`${S}/`),v=o.find(S=>String(S.id)==="0"),k=o.filter(S=>String(S.id)!=="0").sort((S,E)=>Number(E.id)-Number(S.id)),N=WD(m,k.length,!g&&k.length>0),j=k.slice(0,N),y=k.slice(N),C=y.some(S=>b(`/p/${S.id}`));return r.jsxs("aside",{className:"flex h-full w-20 flex-col items-center gap-3 overflow-hidden bg-transparent py-3",children:[r.jsx(Ye,{content:f("nav.apx_admin"),side:"right",children:r.jsx("button",{type:"button",onClick:()=>e("/"),"data-testid":"nav-home",className:"mb-2 cursor-pointer",children:r.jsx(o3,{size:36})})}),l&&r.jsx("div",{className:"size-10 animate-pulse rounded-xl bg-muted"}),v&&r.jsx(bl,{label:f("base.title"),testId:"project-avatar-0",title:f("base.subtitle"),active:b("/p/0"),isDefault:!0,icon:r.jsx("img",{src:"/modules/superagent.png",alt:f("base.title"),className:"size-7 object-contain",draggable:!1}),onClick:()=>e("/p/0")}),u.map(S=>r.jsx(bl,{label:S.label,testId:`module-avatar-${S.id}`,title:S.label,active:b(S.href),icon:r.jsx(S.icon,{size:18}),onClick:()=>e(S.href)},S.id)),r.jsxs("div",{className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3",children:[k.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"my-0.5 h-px w-8 rounded-full bg-border"}),r.jsx(Ye,{content:f(g?"nav.expand_projects":"nav.collapse_projects"),side:"right",children:r.jsx("button",{type:"button",onClick:h,"data-testid":"nav-toggle-projects","aria-label":f(g?"nav.expand_projects":"nav.collapse_projects"),"aria-expanded":!g,className:"flex h-5 w-8 cursor-pointer items-center justify-center rounded-md text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:r.jsx(pa,{className:Te("size-3.5 transition-transform",g&&"-rotate-90")})})})]}),r.jsxs("div",{ref:m,className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3 overflow-hidden",children:[k.length>0&&g&&r.jsx(Bj,{projects:k,icon:r.jsx(RM,{size:18}),sublabel:String(k.length),tooltip:f("nav.all_projects"),header:f("nav.all_projects"),active:k.some(S=>b(`/p/${S.id}`)),testId:"nav-projects-folder",onSelect:e,isActive:b}),k.length>0&&!g&&r.jsxs(r.Fragment,{children:[r.jsx("div",{"data-rail-probe":!0,"aria-hidden":!0,className:"invisible absolute w-full",children:r.jsx(bl,{label:"Ag",active:!1,onClick:()=>{}})}),j.map(S=>{const E=S.name||S.path.split("/").pop()||String(S.id),R=`/p/${S.id}`;return r.jsx("div",{"data-rail-item":!0,className:"w-full",children:r.jsx(bl,{label:E,testId:`project-avatar-${S.id}`,title:`${E} — ${S.path}`,active:b(R),onClick:()=>e(R)})},S.id)}),y.length>0&&r.jsx(Bj,{projects:y,label:`+${y.length}`,tooltip:f("nav.more_projects",{count:y.length}),header:f("nav.more_projects",{count:y.length}),active:C,testId:"nav-projects-overflow",onSelect:e,isActive:b})]}),r.jsx(bl,{label:f("nav.add_project"),isAdd:!0,testId:"nav-add-project",icon:r.jsx(tn,{size:18}),active:!1,onClick:()=>s?s():e("/?action=add-project"),title:f("nav.add_project")})]})]}),r.jsx(bl,{label:f("nav.settings"),isSettings:!0,testId:"nav-settings",icon:r.jsx(Rc,{size:16}),active:c.pathname==="/settings"||c.pathname.startsWith("/settings/"),onClick:()=>e("/settings"),title:f("nav.settings")}),r.jsx(Ye,{content:f("settings_ui.documentation"),side:"right",children:r.jsx("a",{href:"https://agentprojectcontext.github.io/apx/docs/",target:"_blank",rel:"noopener noreferrer","data-testid":"nav-docs","aria-label":f("settings_ui.documentation"),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:r.jsx(lM,{size:18})})}),r.jsx(Ye,{content:f("superagent.talk",{persona:p}),side:"right",children:r.jsx("button",{type:"button",onClick:t,"data-testid":"nav-roby","aria-label":f("superagent.talk",{persona:p}),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:r.jsx(un,{size:18})})})]})}function kC(e){switch(e){case"personal":return f("settings_ui.kind_personal");case"company":return f("settings_ui.kind_company");case"app":return f("settings_ui.kind_app");case"software":return f("settings_ui.kind_software");case"default":return f("settings_ui.kind_default");case"other":return f("settings_ui.kind_other");default:return f("nav.project")}}function Ke({title:e,description:t,action:s,className:o,children:l,fullHeight:c}){return r.jsxs("section",{className:Te("rounded-xl border border-border bg-card p-5",c&&"flex h-full min-h-0 flex-col",o),children:[r.jsxs("header",{className:Te("mb-4 flex items-start justify-between gap-4",c&&"shrink-0"),children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:e}),t&&r.jsx("p",{className:"mt-0.5 text-sm text-muted-fg",children:t})]}),s]}),r.jsx("div",{className:Te(c&&"flex min-h-0 flex-1 flex-col"),children:l})]})}function Uj({children:e}){return r.jsx("kbd",{className:"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-muted-fg",children:e})}function Qc({ok:e}){return r.jsx("span",{className:Te("inline-block size-2 rounded-full",e===null?"bg-muted-fg":e?"bg-emerald-500":"bg-red-500")})}const JD=x.forwardRef(function(t,s){const{render:o,className:l,disabled:c=!1,focusableWhenDisabled:u=!1,nativeButton:p=!0,style:m,...g}=t,{getButtonProps:h,buttonRef:b}=Hr({disabled:c,focusableWhenDisabled:u,native:p});return Nt("button",t,{state:{disabled:c},ref:[s,b],props:[g,h]})}),Hj=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Vj=Tc,Wb=(e,t)=>s=>{var o;if(t?.variants==null)return Vj(e,s?.class,s?.className);const{variants:l,defaultVariants:c}=t,u=Object.keys(l).map(g=>{const h=s?.[g],b=c?.[g];if(h===null)return null;const v=Hj(h)||Hj(b);return l[g][v]}),p=s&&Object.entries(s).reduce((g,h)=>{let[b,v]=h;return v===void 0||(g[b]=v),g},{}),m=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((g,h)=>{let{class:b,className:v,...k}=h;return Object.entries(k).every(N=>{let[j,y]=N;return Array.isArray(y)?y.includes({...c,...p}[j]):{...c,...p}[j]===y})?[...g,b,v]:g},[]);return Vj(e,u,m,s?.class,s?.className)},eL=Wb("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",outline:"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",ghost:"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",xs:"h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",lg:"h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",icon:"size-8","icon-xs":"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg","icon-lg":"size-9"}},defaultVariants:{variant:"default",size:"default"}});function Wa({className:e,variant:t="default",size:s="default",...o}){return r.jsx(JD,{"data-slot":"button",className:St(eL({variant:t,size:s,className:e})),...o})}let qj=(function(e){return e.disabled="data-disabled",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.filled="data-filled",e.focused="data-focused",e})({});const tL={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},pc={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},nL={disabled:!1,...pc},Zb={valid(e){return e===null?null:e?{[qj.valid]:""}:{[qj.invalid]:""}}},sL={invalid:void 0,name:void 0,validityData:{state:tL,errors:[],error:"",value:"",initialValue:null},setValidityData:En,disabled:void 0,touched:pc.touched,setTouched:En,dirty:pc.dirty,setDirty:En,filled:pc.filled,setFilled:En,focused:pc.focused,setFocused:En,validate:()=>null,validationMode:"onSubmit",validationDebounceTime:0,shouldValidateOnChange:()=>!1,state:nL,markedDirtyRef:{current:!1},registerFieldControl:En,validation:{getValidationProps:(e,t=qt)=>t,inputRef:{current:null},registerInput:En,commit:async()=>{},change:En}},aL=x.createContext(sL);function Wc(e=!0){const t=x.useContext(aL);if(t.setValidityData===En&&!e)throw new Error(nn(28));return t}const rL=x.createContext({formRef:{current:{fields:new Map}},errors:{},clearErrors:En,validationMode:"onSubmit",submitAttemptedRef:{current:!1}});function Jb(){return x.useContext(rL)}const oL=x.createContext({controlId:void 0,registerControlId:En,labelId:void 0,setLabelId:En,messageIds:[],setMessageIds:En,getDescriptionProps:e=>e});function lp(){return x.useContext(oL)}function lL(e,t,s,o=!0,l){const[c,u]=x.useState(),p=Ks(l?`${l}-label`:void 0),m=e??t??c;return De(()=>{const g=e||t||!o?void 0:iL(s.current,p);c!==g&&u(g)}),m}function iL(e,t){const s=cL(e);if(s)return!s.id&&t&&(s.id=t),s.id||void 0}function cL(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const s=e.id;if(s){const l=e.nextElementSibling;if(l&&l.htmlFor===s)return l}const o=e.labels;return o&&o[0]}function ip(e={}){const{id:t,implicit:s=!1,controlRef:o}=e,{controlId:l,registerControlId:c}=lp(),u=Ks(t),p=s?l:void 0,m=Xn(()=>Symbol("labelable-control")),g=x.useRef(!1),h=x.useRef(t!=null),b=Ue(()=>{!g.current||c===En||(g.current=!1,c(m.current,void 0))});return De(()=>{if(c===En)return;let v;if(s){const k=o?.current;gt(k)&&k.closest("label")!=null?v=t??null:v=p??u}else if(t!=null)h.current=!0,v=t;else if(h.current)v=u;else{b();return}if(v===void 0){b();return}g.current=!0,c(m.current,v)},[t,o,p,c,s,u,m,b]),x.useEffect(()=>b,[b]),l??u}function e_(e,t,s,o,l=!0,c){const{registerFieldControl:u}=Wc(),p=x.useRef(null);p.current||(p.current=Symbol()),De(()=>{const m=p.current;return!m||!l?void 0:(u(m,{controlRef:e,getValue:o,id:t,name:c,value:s}),()=>{u(m,void 0)})},[e,l,o,t,c,u,s])}const uL=x.forwardRef(function(t,s){const{render:o,className:l,id:c,name:u,value:p,disabled:m=!1,onValueChange:g,defaultValue:h,autoFocus:b=!1,style:v,...k}=t,{state:N,name:j,disabled:y,setTouched:C,setDirty:S,validityData:E,setFocused:R,setFilled:A,validationMode:T,validation:M}=Wc(),{clearErrors:z}=Jb(),B=y||m,L=j??u,U={...N,disabled:B},{labelId:D}=lp(),I=ip({id:c});De(()=>{const X=p!=null;M.inputRef.current?.value||X&&p!==""?A(!0):X&&p===""&&A(!1)},[M.inputRef,A,p]);const V=x.useRef(null);De(()=>{b&&V.current===qn(mt(V.current))&&R(!0)},[b,R]);const[$]=Vl({controlled:p,default:h,name:"FieldControl",state:"value"}),q=p!==void 0,Y=q?$:void 0,K=Ue(()=>M.inputRef.current?.value);return e_(M.inputRef,I,Y,K,!B,u),Nt("input",t,{ref:[s,V],state:U,props:[{id:I,disabled:B,name:L,ref:M.inputRef,"aria-labelledby":D,autoFocus:b,...q?{value:Y}:{defaultValue:h},onChange(X){const P=X.currentTarget.value;g?.(P,nt(fa,X.nativeEvent)),S(P!==E.initialValue),A(P!==""),X.nativeEvent.defaultPrevented||(z(L),M.change(P))},onFocus(){R(!0)},onBlur(X){C(!0),R(!1),T==="onBlur"&&M.commit(X.currentTarget.value)},onKeyDown(X){X.currentTarget.tagName==="INPUT"&&X.key==="Enter"&&(C(!0),M.commit(X.currentTarget.value))}},k,X=>M.getValidationProps(B,X)],stateAttributesMapping:Zb})}),dL=x.forwardRef(function(t,s){return r.jsx(uL,{ref:s,...t})});function fL({className:e,type:t,...s}){return r.jsx(dL,{type:t,"data-slot":"input",className:St("h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...s})}function pL({className:e,...t}){return r.jsx("textarea",{"data-slot":"textarea",className:St("flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...t})}function mL(e){return Nt(e.defaultTagName??"div",e,e)}const gL=Wb("group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",secondary:"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",destructive:"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",outline:"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",ghost:"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",link:"text-primary underline-offset-4 hover:underline"}},defaultVariants:{variant:"default"}});function hL({className:e,variant:t="default",render:s,...o}){return mL({defaultTagName:"span",props:Fn({className:St(gL({variant:t}),e)},o),render:s,state:{slot:"badge",variant:t}})}const SC=x.createContext(void 0);function xL(){const e=x.useContext(SC);if(e===void 0)throw new Error(nn(63));return e}let $j=(function(e){return e.checked="data-checked",e.unchecked="data-unchecked",e.disabled="data-disabled",e.readonly="data-readonly",e.required="data-required",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.filled="data-filled",e.focused="data-focused",e})({});const CC={...Zb,checked(e){return e?{[$j.checked]:""}:{[$j.unchecked]:""}}},bL=x.forwardRef(function(t,s){const{checked:o,className:l,defaultChecked:c,"aria-labelledby":u,form:p,id:m,inputRef:g,name:h,nativeButton:b=!1,onCheckedChange:v,readOnly:k=!1,required:N=!1,disabled:j=!1,render:y,uncheckedValue:C,value:S,style:E,...R}=t,{clearErrors:A}=Jb(),{state:T,setTouched:M,setDirty:z,validityData:B,setFilled:L,setFocused:U,validationMode:D,disabled:I,name:V,validation:$}=Wc(),{labelId:q}=lp(),Y=I||j,K=V??h,F=x.useRef(null),X=Xa(F,g,$.inputRef),P=x.useRef(null),G=Ks(),Z=ip({id:m,implicit:!1,controlRef:P}),ee=b?void 0:Z,[de,fe]=Vl({controlled:o,default:!!c,name:"Switch",state:"checked"});e_(P,G,de,void 0,!Y,h),De(()=>{F.current&&L(F.current.checked)},[F,L]),Ub(de,()=>{A(K),z(de!==B.initialValue),L(de),$.change(de)});const{getButtonProps:ae,buttonRef:oe}=Hr({disabled:Y,native:b}),me=lL(u,q,F,!b,ee),Ae={id:b?Z:G,role:"switch","aria-checked":de,"aria-readonly":k||void 0,"aria-required":N||void 0,"aria-labelledby":me,onFocus(){Y||U(!0)},onBlur(){const je=F.current;!je||Y||(M(!0),U(!1),D==="onBlur"&&$.commit(je.checked))},onClick(je){if(k||Y)return;je.preventDefault();const Be=F.current;Be&&Be.dispatchEvent(new($t(Be)).PointerEvent("click",{bubbles:!0,shiftKey:je.shiftKey,ctrlKey:je.ctrlKey,altKey:je.altKey,metaKey:je.metaKey}))}},ie=Fn({checked:de,disabled:Y,form:p,id:ee,name:K,required:N,style:K?SS:lb,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:X,onChange(je){if(je.nativeEvent.defaultPrevented)return;if(k){je.preventDefault();return}const Be=je.currentTarget.checked,Ve=nt(fa,je.nativeEvent);v?.(Be,Ve),!Ve.isCanceled&&fe(Be)},onFocus(){P.current?.focus()}},je=>$.getValidationProps(Y,je),S!==void 0?{value:S}:qt),pe=x.useMemo(()=>({...T,checked:de,disabled:Y,readOnly:k,required:N}),[T,de,Y,k,N]),Se=Nt("span",t,{state:pe,ref:[s,P,oe],props:[Ae,R,ae,je=>$.getValidationProps(Y,je)],stateAttributesMapping:CC});return r.jsxs(SC.Provider,{value:pe,children:[Se,!de&&K&&C!==void 0&&r.jsx("input",{type:"hidden",form:p,name:K,value:C,disabled:Y}),r.jsx("input",{...ie,suppressHydrationWarning:!0})]})}),_L=x.forwardRef(function(t,s){const{render:o,className:l,style:c,...u}=t,p=xL();return Nt("span",t,{state:p,ref:s,stateAttributesMapping:CC,props:u})});function vL({className:e,size:t="default",...s}){return r.jsx(bL,{"data-slot":"switch","data-size":t,className:St("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...s,children:r.jsx(_L,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function yL({className:e,...t}){return r.jsx(Af,{role:"status","aria-label":"Loading",className:St("size-4 animate-spin",e),...t})}const NC=x.createContext(!1),EC=x.createContext(void 0);function To(e){const t=x.useContext(EC);if(e===!1&&t===void 0)throw new Error(nn(27));return t}const jL={...Ro,...Ja},RC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,forceRender:u=!1,...p}=t,{store:m}=To(),g=m.useState("open"),h=m.useState("nested"),b=m.useState("mounted"),v=m.useState("transitionStatus");return Nt("div",t,{state:{open:g,transitionStatus:v},ref:[m.context.backdropRef,s],stateAttributesMapping:jL,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},p],enabled:u||!h})}),cp=x.forwardRef(function(t,s){const{render:o,className:l,style:c,disabled:u=!1,nativeButton:p=!0,...m}=t,{store:g}=To(),h=g.useState("open"),{getButtonProps:b,buttonRef:v}=Hr({disabled:u,native:p}),k={disabled:u};function N(j){h&&g.setOpen(!1,nt(l5,j.nativeEvent))}return Nt("button",t,{state:k,ref:[s,v],props:[{onClick:N},m,b]})}),TC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,id:u,...p}=t,{store:m}=To(),g=Ks(u);return m.useSyncedValueWithCleanup("descriptionElementId",g),Nt("p",t,{ref:s,props:[{id:g},p]})});let wL=(function(e){return e.nestedDialogs="--nested-dialogs",e})({}),kL=(function(e){return e[e.open=po.open]="open",e[e.closed=po.closed]="closed",e[e.startingStyle=po.startingStyle]="startingStyle",e[e.endingStyle=po.endingStyle]="endingStyle",e.nested="data-nested",e.nestedDialogOpen="data-nested-dialog-open",e})({});const AC=x.createContext(void 0);function SL(){const e=x.useContext(AC);if(e===void 0)throw new Error(nn(26));return e}const CL={...Ro,...Ja,nestedDialogOpen(e){return e?{[kL.nestedDialogOpen]:""}:null}},MC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,finalFocus:u,initialFocus:p,...m}=t,{store:g}=To(),h=g.useState("descriptionElementId"),b=g.useState("disablePointerDismissal"),v=g.useState("floatingRootContext"),k=g.useState("popupProps"),N=g.useState("modal"),j=g.useState("mounted"),y=g.useState("nested"),C=g.useState("nestedOpenDialogCount"),S=g.useState("open"),E=g.useState("openMethod"),R=g.useState("titleElementId"),A=g.useState("transitionStatus"),T=g.useState("role"),M=v.useState("floatingId"),z=m.id??M;SL(),ha({open:S,ref:g.context.popupRef,onComplete(){S&&g.context.onOpenChangeComplete?.(!0)}});const B=p===void 0?f4(g.context.popupRef):p,L=C>0,U=g.useStateSetter("popupElement"),I=Nt("div",t,{state:{open:S,nested:y,transitionStatus:A,nestedDialogOpen:L},props:[k,{id:z,"aria-labelledby":R??void 0,"aria-describedby":h??void 0,role:T,...Xf,hidden:!j,onKeyDown(V){sp.has(V.key)&&V.stopPropagation()},style:{[wL.nestedDialogs]:C}},m],ref:[s,g.context.popupRef,U],stateAttributesMapping:CL});return r.jsx(_b,{context:v,openInteractionType:E,disabled:!j,closeOnFocusOut:!b,initialFocus:B,returnFocus:u,modal:N!==!1,restoreFocus:"popup",children:I})}),OC=x.forwardRef(function(t,s){const{keepMounted:o=!1,...l}=t,{store:c}=To(),u=c.useState("mounted"),p=c.useState("modal"),m=c.useState("open");return u||o?r.jsx(AC.Provider,{value:o,children:r.jsxs(hb,{ref:s,...l,children:[u&&p===!0&&r.jsx(Bb,{ref:c.context.internalBackdropRef,inert:Jf(!m)}),t.children]})}):null});function NL(e){const{store:t,actionsRef:s}=e,o=t.useState("open");g4(t,o),wb(t);const{forceUnmount:l}=kb(o,t),c=x.useCallback(()=>{t.setOpen(!1,nt(rb))},[t]);x.useImperativeHandle(s,()=>({unmount:l,close:c}),[l,c])}function EL({store:e,parentContext:t,isDrawer:s}){const o=e.useState("open"),l=e.useState("disablePointerDismissal"),c=e.useState("modal"),u=e.useState("popupElement"),p=e.useState("floatingRootContext"),[m,g]=x.useState(0),[h,b]=x.useState(0),v=m===0,k=Ff(p,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:c==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(C){if(!e.context.outsidePressEnabledRef.current||"button"in C&&C.button!==0||"touches"in C&&C.touches.length!==1)return!1;const S=Un(C);return v&&!l?c&&(e.context.internalBackdropRef.current||e.context.backdropRef.current)?e.context.internalBackdropRef.current===S||e.context.backdropRef.current===S||Qe(S,u)&&!S?.hasAttribute("data-base-ui-portal"):!0:!1},escapeKey:v});Q2(o&&c===!0,u),e.useContextCallback("onNestedDialogOpen",(C,S)=>{g(C),b(S)}),e.useContextCallback("onNestedDialogClose",()=>{g(0),b(0)}),x.useEffect(()=>(t?.onNestedDialogOpen&&o&&t.onNestedDialogOpen(m+1,h+(s?1:0)),t?.onNestedDialogClose&&!o&&t.onNestedDialogClose(),()=>{t?.onNestedDialogClose&&o&&t.onNestedDialogClose()}),[s,o,m,h,t]);const N=k.reference??qt,j=k.trigger??qt,y=k.floating??qt;return Sb(e,{activeTriggerProps:N,inactiveTriggerProps:j,popupProps:y,nestedOpenDialogCount:m,nestedOpenDrawerCount:h}),null}const RL={...Eb,modal:Me(e=>e.modal),nested:Me(e=>e.nested),nestedOpenDialogCount:Me(e=>e.nestedOpenDialogCount),nestedOpenDrawerCount:Me(e=>e.nestedOpenDrawerCount),disablePointerDismissal:Me(e=>e.disablePointerDismissal),openMethod:Me(e=>e.openMethod),descriptionElementId:Me(e=>e.descriptionElementId),titleElementId:Me(e=>e.titleElementId),viewportElement:Me(e=>e.viewportElement),role:Me(e=>e.role)};class t_ extends Yf{constructor(t,s,o=!1){const l=new Fc,c=TL(t);c.floatingRootContext=h2(l,s,o),super(c,{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:l,onOpenChange:void 0,onOpenChangeComplete:void 0},RL)}setOpen=(t,s)=>{if(s.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!t&&s.trigger==null&&this.state.activeTriggerId!=null&&(s.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(t,s),s.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,s);const o={open:t};jb(o,t,s.trigger),this.update(o)};static useStore(t,s){return f2(t,(l,c)=>new t_(s,l,c),!0).store}}function TL(e={}){return{...Cb(),modal:!0,disablePointerDismissal:!1,popupElement:null,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}function AL(e,t="dialog"){const{children:s,open:o,defaultOpen:l=!1,onOpenChange:c,onOpenChangeComplete:u,disablePointerDismissal:p=!1,modal:m=!0,actionsRef:g,handle:h,triggerId:b,defaultTriggerId:v=null}=e,k=t==="drawer",N=t==="alert-dialog",j=N?!0:m,y=N||p,C=N?"alertdialog":"dialog",S=To(!0),R={modal:j,disablePointerDismissal:y,nested:!!S,role:C},A=t_.useStore(h?.store,{open:l,openProp:o,activeTriggerId:v,triggerIdProp:b,...R});yb(()=>{const U=o===void 0&&A.state.open===!1&&l===!0?{open:!0,activeTriggerId:v}:null;N?A.update(U?{...R,...U}:R):U&&A.update(U)}),A.useControlledProp("openProp",o),A.useControlledProp("triggerIdProp",b),A.useSyncedValues(R),A.useContextCallback("onOpenChange",c),A.useContextCallback("onOpenChangeComplete",u);const T=A.useState("open"),M=A.useState("mounted"),z=A.useState("payload");NL({store:A,actionsRef:g});const B=T||M,L=x.useMemo(()=>({store:A}),[A]);return r.jsx(NC.Provider,{value:!1,children:r.jsxs(EC.Provider,{value:L,children:[B&&r.jsx(EL,{store:A,parentContext:S?.store.context,isDrawer:k}),typeof s=="function"?s({payload:z}):s]})})}function zC(e){const t=x.useContext(NC)?"drawer":"dialog";return AL(e,t)}const DC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,id:u,...p}=t,{store:m}=To(),g=Ks(u);return m.useSyncedValueWithCleanup("titleElementId",g),Nt("h2",t,{ref:s,props:[{id:g},p]})});function mx({...e}){return r.jsx(zC,{"data-slot":"dialog",...e})}function ML({...e}){return r.jsx(OC,{"data-slot":"dialog-portal",...e})}function OL({...e}){return r.jsx(cp,{"data-slot":"dialog-close",...e})}function zL({className:e,...t}){return r.jsx(RC,{"data-slot":"dialog-overlay",className:St("fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",e),...t})}function gx({className:e,children:t,showCloseButton:s=!0,...o}){return r.jsxs(ML,{children:[r.jsx(zL,{}),r.jsxs(MC,{"data-slot":"dialog-content",className:St("fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...o,children:[t,s&&r.jsxs(cp,{"data-slot":"dialog-close",render:r.jsx(Wa,{variant:"ghost",className:"absolute top-2 right-2",size:"icon-sm"}),children:[r.jsx(Ys,{}),r.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function hx({className:e,...t}){return r.jsx("div",{"data-slot":"dialog-header",className:St("flex flex-col gap-2",e),...t})}function Fj({className:e,showCloseButton:t=!1,children:s,...o}){return r.jsxs("div",{"data-slot":"dialog-footer",className:St("-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",e),...o,children:[s,t&&r.jsx(cp,{render:r.jsx(Wa,{variant:"outline"}),children:"Close"})]})}function xx({className:e,...t}){return r.jsx(DC,{"data-slot":"dialog-title",className:St("font-heading text-base leading-none font-medium",e),...t})}function DL({className:e,...t}){return r.jsx(TC,{"data-slot":"dialog-description",className:St("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",e),...t})}const LL={primary:"default",secondary:"outline",ghost:"ghost",destructive:"destructive"},PL={sm:"sm",md:"default"};function ce({variant:e="secondary",size:t="md",loading:s,className:o,children:l,disabled:c,type:u="button",...p}){return r.jsxs(Wa,{type:u,variant:LL[e],size:PL[t],disabled:c||s,className:o,...p,children:[s?r.jsx(vs,{size:14}):null,l]})}function Ne(e){return r.jsx(fL,{...e})}function Mn(e){return r.jsx(pL,{...e})}function IL(e){return r.jsx("select",{...e,className:Te("h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",e.className)})}function le({label:e,hint:t,badge:s,children:o}){return r.jsxs("label",{className:"block space-y-1",children:[r.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[e,s&&r.jsx("span",{className:"rounded bg-muted px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-muted-foreground",children:s})]}),o,t&&r.jsx("span",{className:"block text-[11px] text-muted-foreground/70",children:t})]})}function Ft({checked:e,onChange:t,label:s,disabled:o}){return r.jsxs("label",{className:Te("inline-flex items-center gap-2",o&&"opacity-50"),children:[r.jsx(vL,{checked:e,onCheckedChange:t,disabled:o}),s&&r.jsx("span",{className:"text-sm",children:s})]})}function Fe({children:e,tone:t="muted",className:s}){const o=t==="danger"?"destructive":t==="muted"?"secondary":"outline",l={muted:"",danger:"",success:"text-emerald-400 border-emerald-500/30",warning:"text-amber-400 border-amber-500/30",info:"text-sky-400 border-sky-500/30"};return r.jsx(hL,{variant:o,className:Te("rounded-md",l[t],s),children:e})}function On({open:e,onClose:t,title:s,description:o,children:l,footer:c,size:u="md"}){const p={sm:"sm:max-w-md",md:"sm:max-w-lg",lg:"sm:max-w-2xl",xl:"sm:max-w-4xl"};return r.jsx(mx,{open:e,onOpenChange:m=>{m||t()},children:r.jsxs(gx,{className:Te("flex max-h-[88vh] w-full flex-col gap-0 p-0",p[u]),children:[(s||o)&&r.jsxs(hx,{className:"shrink-0 border-b border-border px-5 py-4 pr-12",children:[s&&r.jsx(xx,{children:s}),o&&r.jsx(DL,{children:o})]}),r.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:l}),c&&r.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-5 py-4",children:c})]})})}function vs({size:e=14}){return r.jsx(yL,{style:{width:e,height:e}})}function xt({children:e}){return r.jsx("div",{className:"rounded-lg border border-dashed border-border bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground",children:e})}function ot({label:e="Cargando…"}){return r.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[r.jsx(vs,{})," ",e]})}const LC=x.createContext(null);let BL=1;function UL({children:e}){const[t,s]=x.useState([]),o=x.useCallback((c,u)=>{const p=BL++;s(m=>[...m,{id:p,kind:c,message:u}]),setTimeout(()=>{s(m=>m.filter(g=>g.id!==p))},4500)},[]),l=x.useMemo(()=>({show:o,success:c=>o("success",c),error:c=>o("error",c),info:c=>o("info",c)}),[o]);return x.useEffect(()=>(window.__apxToast=l,()=>{delete window.__apxToast}),[l]),r.jsxs(LC.Provider,{value:l,children:[e,r.jsx("div",{className:"pointer-events-none fixed bottom-4 right-4 z-[100] flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",children:t.map(c=>r.jsx("div",{className:Te("pointer-events-auto overflow-hidden rounded-lg border bg-card px-3 py-2 text-sm shadow-lg",c.kind==="success"&&"border-emerald-500/40",c.kind==="error"&&"border-destructive/60",c.kind==="info"&&"border-border"),children:r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("span",{className:Te("mt-1 size-2 shrink-0 rounded-full",c.kind==="success"&&"bg-emerald-500",c.kind==="error"&&"bg-destructive",c.kind==="info"&&"bg-sky-500")}),r.jsx("span",{className:"flex-1 break-words",children:c.message})]})},c.id))})]})}function lt(){const e=x.useContext(LC);if(!e)throw new Error("useToast must be used inside <ToastProvider>");return e}function PC(){const{data:e,error:t,isLoading:s}=et("/health",()=>UD.get(),{refreshInterval:Of.health});return{health:e,error:t,isLoading:s,isUp:!t&&!!e}}function HL(){const{data:e,error:t,isLoading:s,mutate:o}=et("/engines",()=>mf.list());return{engines:e?.engines||[],error:t,isLoading:s,mutate:o}}function VL(){const{data:e,error:t,isLoading:s,mutate:o}=et("/telegram/status",()=>An.status(),{refreshInterval:Of.telegramStatus});return{status:e,error:t,isLoading:s,mutate:o}}function n_(){const{data:e,error:t,isLoading:s,mutate:o}=et("/telegram/channels",()=>An.channels.list());return{channels:e?.channels||[],error:t,isLoading:s,mutate:o}}function s_(){const{data:e,error:t,isLoading:s,mutate:o}=et("/telegram/contacts",()=>An.contacts.list());return{contacts:e?.contacts||[],roles:e?.roles||{},channelOwners:e?.channel_owners||[],error:t,isLoading:s,mutate:o}}function is(e){return typeof e=="string"&&e.startsWith("*** set ***")}function Ar(e,t="(no seteada)"){return is(e)?e:t}function jo(e){if(typeof e!="string")return null;const t=e.match(/\(\.\.\.([^)]+)\)/);return t?t[1]:null}function IC({channel:e,onClose:t,onSaved:s}){const o=lt(),[l,c]=x.useState(!1),[u,p]=x.useState({name:""});x.useEffect(()=>{p(e?{...e,bot_token:""}:{name:""})},[e?.name]);const m=async()=>{if(!u.name?.trim()){o.error(f("telegram_channel_dialog.name_required"));return}c(!0);try{e&&e.name!==""&&e?.name===u.name?await An.channels.patch(e.name,u):await An.channels.upsert(u),o.success(f("telegram_channel_dialog.saved")),s()}catch(g){o.error(g.message)}finally{c(!1)}};return r.jsx(On,{open:!!e,onClose:t,title:e?.name?f("telegram_channel_dialog.edit_title",{name:e.name}):f("telegram_channel_dialog.new_title"),description:f("telegram_ui.channel_dialog_desc"),footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:l,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:m,loading:l,children:f("common.save")})]}),children:r.jsxs("div",{className:"space-y-3",children:[r.jsx(le,{label:f("telegram_channel_dialog.name_label"),children:r.jsx(Ne,{value:u.name,onChange:g=>p({...u,name:g.target.value}),disabled:!!e?.name})}),r.jsx(le,{label:f("telegram_channel_dialog.token_label"),hint:e?.bot_token?Ar(e.bot_token):f("telegram_ui.bot_token_hint"),children:r.jsx(Ne,{type:"password",value:u.bot_token||"",onChange:g=>p({...u,bot_token:g.target.value}),placeholder:e?.bot_token?Ar(e.bot_token):""})}),r.jsx(le,{label:f("telegram_channel_dialog.chat_id"),children:r.jsx(Ne,{value:u.chat_id||"",onChange:g=>p({...u,chat_id:g.target.value})})}),r.jsx(le,{label:f("telegram_channel_dialog.project_label"),hint:f("telegram_channel_dialog.project_hint"),children:r.jsx(Ne,{value:u.project||"",onChange:g=>p({...u,project:g.target.value})})}),r.jsx(le,{label:f("telegram_channel_dialog.route_label"),hint:f("telegram_channel_dialog.route_hint"),children:r.jsx(Ne,{value:u.route_to_agent||"",onChange:g=>p({...u,route_to_agent:g.target.value})})}),r.jsx(le,{label:f("telegram_channel_dialog.owner_label"),hint:f("telegram_channel_dialog.owner_hint"),children:r.jsx(Ne,{value:u.owner_user_id!=null?String(u.owner_user_id):"",onChange:g=>{const h=g.target.value.trim();p({...u,owner_user_id:h===""?void 0:/^\d+$/.test(h)?Number(h):h})},placeholder:"889721252"})}),r.jsx(Ft,{checked:!!u.respond_with_engine,onChange:g=>p({...u,respond_with_engine:g}),label:f("telegram_channel_dialog.respond_label")})]})})}function BC({channel:e,onClose:t}){const s=lt(),[o,l]=x.useState(f("admin.telegram_default_message")),[c,u]=x.useState(!1),p=async()=>{if(!(!o.trim()||!e)){u(!0);try{await An.send({text:o,channel:e.name}),s.success(f("telegram_ui.message_sent")),t()}catch(m){s.error(m.message)}finally{u(!1)}}};return r.jsx(On,{open:!!e,onClose:t,title:e?f("telegram_send_dialog.title",{name:e.name}):"",description:e?f("telegram_ui.send_chat_id",{id:e.chat_id||"—"}):"",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:c,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:p,loading:c,children:f("chat_ui.send")})]}),children:r.jsx(le,{label:f("telegram_ui.message_label"),children:r.jsx(Mn,{rows:4,value:o,onChange:m=>l(m.target.value)})})})}function UC({bare:e=!1}){const t=lt(),{contacts:s,roles:o,channelOwners:l,isLoading:c,mutate:u}=s_(),p=new Set(l.filter(v=>v.owner_user_id!=null).map(v=>String(v.owner_user_id))),m=Array.from(new Set(["owner","guest",...Object.keys(o)])),g=async(v,k)=>{try{await An.contacts.patch(v.user_id,{role:k}),t.success(f("telegram_ui.role_assigned",{name:v.name||v.user_id,role:k})),u()}catch(N){t.error(N.message)}},h=async v=>{if(confirm(f("telegram_contacts.delete_confirm",{name:v.name||String(v.user_id)})))try{await An.contacts.remove(v.user_id),t.success(f("telegram_contacts.removed")),u()}catch(k){t.error(k.message)}},b=r.jsxs(r.Fragment,{children:[c&&r.jsx(ot,{}),!c&&s.length===0&&r.jsx(xt,{children:f("telegram_contacts.empty")}),s.length>0&&r.jsx("ul",{className:"space-y-2 text-sm",children:s.map(v=>{const k=p.has(String(v.user_id)),N=k?"owner":v.role||"guest";return r.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("span",{className:"font-medium",children:v.name||"—"}),v.username&&r.jsxs("span",{className:"ml-2 text-xs text-muted-fg",children:["@",v.username]}),k&&r.jsx(Fe,{tone:"success",children:f("telegram_contacts.owner_badge")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ye,{content:f(k?"telegram_contacts.owner_hint":"telegram_contacts.assign_role"),children:r.jsx(IL,{value:N,disabled:k,onChange:j=>g(v,j.target.value),children:m.map(j=>r.jsx("option",{value:j,children:j},j))})}),r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>h(v),children:f("common.delete")})]})]}),r.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[r.jsxs("span",{children:["user_id: ",String(v.user_id)]}),r.jsxs("span",{children:[f("telegram_contacts.last_seen")," ",v.last_seen?v.last_seen.slice(0,10):"—"]}),r.jsx("span",{children:qL(o[N])})]})]},String(v.user_id))})})]});return e?b:r.jsx(Ke,{title:f("telegram_contacts.title"),description:f("telegram_contacts.desc"),children:b})}function qL(e){return!e||e.tools===void 0?"":e.tools==="*"?f("telegram_contacts.tools_all"):Array.isArray(e.tools)?e.tools.length?`${f("telegram_contacts.tools_label")} ${e.tools.join(", ")}`:f("telegram_contacts.tools_none"):""}function $L(){const e=Wn(),[t,s]=Nf(),o=lt(),{health:l,isUp:c}=PC(),{projects:u,isLoading:p,mutate:m}=Xc(),{engines:g,isLoading:h}=HL(),{status:b,mutate:v}=VL(),{channels:k,isLoading:N,mutate:j}=n_(),[y,C]=x.useState(null),[S,E]=x.useState(null),R=async()=>{try{await $l.reload(),o.success(f("admin.reload_success"))}catch(z){o.error(z.message)}},A=async()=>{try{b?.enabled?(await An.stop(),o.info(f("admin.telegram_polling_stopped"))):(await An.start(),o.success(f("admin.telegram_polling_started"))),v()}catch(z){o.error(z.message)}},T=async z=>{if(confirm(f("telegram_channels.delete_confirm",{name:z})))try{await An.channels.remove(z),o.success(f("admin.telegram_channel_removed")),j()}catch(B){o.error(B.message)}},M=async(z,B)=>{if(confirm(f("admin.unregister_confirm",{label:B})))try{await ls.remove(z),o.success(f("project.unregistered")),m()}catch(L){o.error(L.message)}};return r.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-6","data-testid":"screen-admin",children:[r.jsxs("header",{className:"flex items-end justify-between",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:f("admin.title")}),r.jsx("p",{className:"text-sm text-muted-fg",children:f("admin.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Ye,{content:f("daemon.reload_hint"),children:r.jsxs(ce,{size:"sm",onClick:R,children:[f("common.reload")," config"]})}),r.jsxs(ce,{size:"sm",variant:"primary",onClick:()=>{const z=new URLSearchParams(t);z.set("action","add-project"),s(z)},children:[r.jsx(tn,{size:14})," ",f("nav.project")]})]})]}),r.jsx(Ke,{title:f("daemon.version"),children:r.jsxs("div",{className:"grid grid-cols-3 gap-3 text-sm",children:[r.jsx(th,{label:f("daemon.version"),value:l?.version||"—"}),r.jsx(th,{label:f("daemon.uptime"),value:l?`${l.uptime_s}s`:"—"}),r.jsx(th,{label:f("daemon.status"),value:f(c?"daemon.running":"daemon.down"),ok:c})]})}),r.jsxs(Ke,{title:f("admin.engines_title"),description:f("admin.engines_subtitle"),children:[h&&r.jsx(ot,{}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:g.map(z=>r.jsx(Fe,{tone:"info",children:z},z))})]}),r.jsxs(Ke,{title:f("admin.telegram_title"),description:f("admin.telegram_subtitle"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ft,{checked:!!b?.enabled,onChange:A,label:b?.enabled?f("admin.telegram_polling_on"):f("admin.telegram_polling_off")}),r.jsxs(ce,{size:"sm",onClick:()=>C({name:""}),children:[r.jsx(tn,{size:14})," ",f("admin.telegram_add_channel")]})]}),children:[N&&r.jsx(ot,{}),k.length===0&&r.jsx(xt,{children:f("common.none_yet")}),r.jsx("ul",{className:"space-y-2 text-sm",children:k.map(z=>r.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"font-medium",children:z.name}),r.jsxs("div",{className:"flex items-center gap-2",children:[z.project&&r.jsxs(Fe,{tone:"success",children:["project = ",z.project]}),r.jsxs(ce,{size:"sm",variant:"ghost",onClick:()=>E(z),children:[r.jsx(Gs,{size:13})," ",f("admin.telegram_send_test")]}),r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>C(z),children:f("common.edit")}),r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>T(z.name),children:f("common.delete")})]})]}),r.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[r.jsxs("span",{children:["chat_id: ",z.chat_id||"—"]}),r.jsxs("span",{children:["route_to_agent: ",z.route_to_agent||"default APX"]}),r.jsxs("span",{children:["engine: ",z.respond_with_engine?f("admin.engine_badge"):f("admin.engine_badge_no")]})]})]},z.name))})]}),r.jsx(UC,{}),r.jsxs(Ke,{title:f("admin.projects_title"),description:f("admin.projects_subtitle"),children:[p&&r.jsx(ot,{}),r.jsx("ul",{className:"divide-y divide-border",children:u.map(z=>r.jsxs("li",{className:"flex items-center gap-3 py-2",children:[r.jsxs("span",{className:"w-10 font-mono text-xs text-muted-fg",children:["#",z.id]}),r.jsxs("button",{type:"button",className:"flex-1 text-left hover:underline",onClick:()=>e(`/p/${z.id}`),children:[r.jsx("span",{className:"font-medium",children:z.name||z.path.split("/").pop()}),r.jsx("span",{className:"ml-2 text-xs text-muted-fg",children:z.path})]}),r.jsxs(Fe,{children:[z.agents??0," ",f("admin.agents_badge")]}),Number(z.id)!==0&&r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>M(String(z.id),z.name||z.path),children:f("admin.unregister")})]},z.id))})]}),r.jsx(IC,{channel:y,onClose:()=>C(null),onSaved:()=>{C(null),j()}}),r.jsx(BC,{channel:S,onClose:()=>E(null)})]})}function th({label:e,value:t,ok:s}){return r.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-3",children:[r.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),r.jsxs("div",{className:"mt-1 flex items-center gap-2 text-base font-medium",children:[s!==void 0&&r.jsx(Qc,{ok:s}),r.jsx("span",{children:t})]})]})}const HC=x.createContext(null),VC=x.createContext(null),qC=x.createContext(""),$C=x.createContext(null),FC=x.createContext(null),GC=x.createContext(null);function FL({children:e}){const[t,s]=x.useState(null),[o,l]=x.useState(""),[c,u]=x.useState(null);return r.jsx(VC.Provider,{value:s,children:r.jsx(HC.Provider,{value:t,children:r.jsx($C.Provider,{value:l,children:r.jsx(qC.Provider,{value:o,children:r.jsx(GC.Provider,{value:u,children:r.jsx(FC.Provider,{value:c,children:e})})})})})})}function GL(){return x.useContext(HC)}function YL(e,t){const s=x.useContext(VC);x.useEffect(()=>(s?.({collapsed:e,toggle:t}),()=>s?.(null)),[e,t,s])}function KL(){return x.useContext(qC)}function XL(e){const t=x.useContext($C);x.useEffect(()=>(t?.(e),()=>t?.("")),[e,t])}function QL(){return x.useContext(FC)}function WL(e){const t=x.useContext(GC);x.useEffect(()=>(t?.(e),()=>t?.(null)),[e,t])}function YC({sections:e,active:t,onChange:s,collapsed:o,onToggleCollapse:l,actions:c,contentClassName:u,testId:p,children:m}){return YL(o,l),r.jsxs("div",{className:"flex h-full",children:[r.jsx(dD,{sections:e,active:t,onChange:s,collapsed:o}),r.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[c?r.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 px-6 pt-3",children:c}):null,r.jsx("div",{className:Te("flex-1 min-h-0 overflow-y-auto",u),"data-testid":p,children:m})]})]})}const Gj={happy:{eyes:["◕","◕"],mouth:"‿"},wave:{eyes:["◕","◕"],mouth:"▽",top:"·"},confused:{eyes:["◑","◐"],mouth:"o",top:"?"},sad:{eyes:["╥","╥"],mouth:"◠"},excited:{eyes:["★","★"],mouth:"▽",top:"✦"},sleeping:{eyes:["−","−"],mouth:"‿",top:"z z"}};function KC({mood:e="happy",className:t}){const s=Gj[e]??Gj.happy,[o,l]=s.eyes,c="text-emerald-700 dark:text-emerald-600/70";return r.jsxs("div",{"aria-hidden":!0,className:St("select-none whitespace-pre font-mono leading-none text-emerald-400",t),children:[s.top&&r.jsx("div",{children:r.jsx("span",{className:c,children:` ${s.top}`})}),r.jsx("div",{children:" ▄███████▄"}),r.jsxs("div",{children:[" █ ",r.jsx("span",{className:c,children:"██"})," ",r.jsx("span",{className:c,children:"██"})," █"]}),r.jsx("div",{children:` █ ${o} ${l} █`}),r.jsx("div",{children:` █ ${s.mouth} █`}),r.jsx("div",{children:" ▀███████▀"})]})}function XC({mood:e="confused",title:t,titleClassName:s,message:o,action:l,className:c,testId:u}){return r.jsx("div",{className:St("grid h-full place-items-center p-8",c),"data-testid":u,children:r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsx(KC,{mood:e,className:"mb-6 text-sm"}),t!=null&&r.jsx("div",{className:St("font-mono font-semibold leading-none tracking-tight text-foreground",s),children:t}),o!=null&&r.jsx("p",{className:"mt-4 max-w-sm text-sm text-muted-fg",children:o}),l&&r.jsx("div",{className:"mt-6",children:l})]})})}function Yj({pid:e}){const t=et(`/projects/${e}/tasks?state=open`,()=>Nr.list(e)),s=et(`/projects/${e}/routines`,()=>Cr.list(e)),o=et(`/projects/${e}/agents`,()=>rn.list(e)),l=et(`/projects/${e}/mcps`,()=>Er.list(e));return r.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-3",children:[r.jsx(ec,{title:f("project.overview.tasks_open"),value:t.data?.length??"…",href:`/p/${e}/tasks`,icon:Ll}),r.jsx(ec,{title:f("project.overview.routines"),value:s.data?.length??"…",href:`/p/${e}/routines`,icon:Dl}),r.jsx(ec,{title:f("project.overview.agents"),value:o.data?.length??"…",href:`/p/${e}/agents`,icon:un}),r.jsx(ec,{title:f("project.overview.mcps"),value:l.data?.length??"…",href:`/p/${e}/mcps`,icon:$h}),r.jsx(ec,{title:f("project.overview.chat"),value:f("project.overview.chat_value"),href:`/p/${e}/chat`,icon:Xd})]})}function ec({title:e,value:t,href:s,icon:o}){return r.jsxs(Bk,{to:s,className:"flex items-center gap-3 rounded-xl border border-border bg-card p-4 hover:bg-accent/40",children:[r.jsx("span",{className:"grid size-10 place-items-center rounded-lg bg-muted text-muted-fg",children:r.jsx(o,{size:20})}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),r.jsx("div",{className:"text-2xl font-semibold",children:t})]})]})}function ZL(){const e=Wn(),{projects:t,isLoading:s}=Xc();return r.jsxs(Ke,{title:f("base.workspaces_title"),description:f("base.workspaces_desc"),action:r.jsxs(ce,{size:"sm",variant:"primary",onClick:()=>e("/p/0/workspaces?action=add-project"),children:[r.jsx(tn,{size:14})," ",f("base.workspaces_new")]}),children:[s&&r.jsx(ot,{}),!s&&t.length===0&&r.jsx(xt,{children:f("base.workspaces_empty")}),r.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(o=>{const l=String(o.id)==="0",c=l?f("base.title"):o.name||o.path.split("/").pop()||String(o.id);return r.jsxs("button",{type:"button",onClick:()=>e(`/p/${o.id}`),className:"flex cursor-pointer flex-col gap-2 rounded-xl border border-border bg-card p-4 text-left transition-colors hover:border-muted-fg/50",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Qk,{className:"size-4 text-muted-fg"}),r.jsx("span",{className:"truncate text-sm font-semibold",children:c}),r.jsx(Fe,{tone:l?"success":"info",children:l?f("base.title"):kC(o.kind)})]}),r.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:o.path})]},o.id)})})]})}const QC=x.createContext(null),WC=x.createContext(null);function xa(){const e=x.useContext(QC);if(e===null)throw new Error(nn(60));return e}function ZC(){const e=x.useContext(WC);if(e===null)throw new Error(nn(61));return e}const JL=(e,t)=>Object.is(e,t);function wo(e,t,s){return e==null||t==null?Object.is(e,t):s(e,t)}function eP(e,t,s){return!e||e.length===0?!1:e.some(o=>o===void 0?!1:wo(t,o,s))}function kc(e,t,s){return!e||e.length===0?-1:e.findIndex(o=>o===void 0?!1:wo(o,t,s))}function tP(e,t,s){return e.filter(o=>!wo(t,o,s))}function bx(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function JC(e){return e!=null&&e.length>0&&typeof e[0]=="object"&&e[0]!=null&&"items"in e[0]}function nP(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(JC(t)){for(const s of t)for(const o of s.items)if(o&&o.value==null&&o.label!=null)return!0;return!1}for(const s of t)if(s&&s.value==null&&s.label!=null)return!0;return!1}function eN(e,t){if(t&&e!=null)return t(e)??"";if(e&&typeof e=="object"){if("label"in e&&e.label!=null)return String(e.label);if("value"in e)return String(e.value)}return bx(e)}function co(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?bx(e.value):bx(e)}function tN(e,t,s){function o(){return eN(e,s)}if(s&&e!=null)return s(e);if(e&&typeof e=="object"&&"label"in e&&e.label!=null)return e.label;if(t&&!Array.isArray(t))return t[e]??o();if(Array.isArray(t)){const l=t,c=JC(l)?l.flatMap(u=>u.items):l;if(e==null||typeof e!="object"){const u=c.find(p=>p.value===e);return u&&u.label!=null?u.label:o()}if("value"in e){const u=c.find(p=>p&&p.value===e.value);if(u&&u.label!=null)return u.label}}return o()}function sP(e,t,s){return e.reduce((o,l,c)=>(c>0&&o.push(", "),o.push(r.jsx(x.Fragment,{children:tN(l,t,s)},c)),o),[])}const Je={id:Me(e=>e.id),labelId:Me(e=>e.labelId),modal:Me(e=>e.modal),multiple:Me(e=>e.multiple),items:Me(e=>e.items),itemToStringLabel:Me(e=>e.itemToStringLabel),itemToStringValue:Me(e=>e.itemToStringValue),isItemEqualToValue:Me(e=>e.isItemEqualToValue),value:Me(e=>e.value),hasSelectedValue:Me(e=>{const{value:t,multiple:s,itemToStringValue:o}=e;return t==null?!1:s&&Array.isArray(t)?t.length>0:co(t,o)!==""}),hasNullItemLabel:Me((e,t)=>t?nP(e.items):!1),open:Me(e=>e.open),mounted:Me(e=>e.mounted),forceMount:Me(e=>e.forceMount),transitionStatus:Me(e=>e.transitionStatus),openMethod:Me(e=>e.openMethod),activeIndex:Me(e=>e.activeIndex),selectedIndex:Me(e=>e.selectedIndex),isActive:Me((e,t)=>e.activeIndex===t),isSelected:Me((e,t)=>{const s=e.isItemEqualToValue,o=e.value;return e.multiple?Array.isArray(o)&&o.some(l=>wo(t,l,s)):wo(t,o,s)}),isSelectedByFocus:Me((e,t)=>e.selectedIndex===t),popupProps:Me(e=>e.popupProps),triggerProps:Me(e=>e.triggerProps),triggerElement:Me(e=>e.triggerElement),positionerElement:Me(e=>e.positionerElement),listElement:Me(e=>e.listElement),popupSide:Me(e=>e.popupSide),scrollUpArrowVisible:Me(e=>e.scrollUpArrowVisible),scrollDownArrowVisible:Me(e=>e.scrollDownArrowVisible),hasScrollArrows:Me(e=>e.hasScrollArrows)};function aP(e,t,s=(o,l)=>o===l){return e.length===t.length&&e.every((o,l)=>s(o,t[l]))}function mc(e,t=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,s))}const Hs=1;function a_(e,t){return Math.max(0,e-t)}function xf(e,t){if(t<=0)return 0;const s=mc(e,0,t),o=s,l=t-s,c=o<=Hs,u=l<=Hs;return c&&u?o<=l?0:t:c?0:u?t:s}function rP(e){const{id:t,value:s,defaultValue:o=null,onValueChange:l,open:c,defaultOpen:u=!1,onOpenChange:p,name:m,form:g,autoComplete:h,disabled:b=!1,readOnly:v=!1,required:k=!1,modal:N=!0,actionsRef:j,inputRef:y,onOpenChangeComplete:C,items:S,multiple:E=!1,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T=JL,highlightItemOnHover:M=!0,children:z}=e,{clearErrors:B}=Jb(),{setDirty:L,setTouched:U,setFocused:D,validityData:I,setFilled:V,name:$,disabled:q,validation:Y,validationMode:K}=Wc(),F=ip({id:t}),X=q||b,P=$??m,[G,Z]=Vl({controlled:s,default:E?o??Ka:o,name:"Select",state:"value"}),[ee,de]=Vl({controlled:c,default:u,name:"Select",state:"open"}),fe=x.useRef([]),ae=x.useRef([]),oe=x.useRef(null),me=x.useRef(null),Ae=x.useRef(0),ie=x.useRef(null),pe=x.useRef([]),Se=x.useRef(!1),je=x.useRef(null),Be=x.useRef(null),Ve=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),we=x.useRef(!1),{mounted:Ee,setMounted:ve,transitionStatus:Ce}=ti(ee),{openMethod:Le,triggerProps:Pe}=tC(ee),Ie=Xn(()=>new c2({id:F,labelId:void 0,modal:N,multiple:E,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,value:G,open:ee,mounted:Ee,transitionStatus:Ce,items:S,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:{},triggerProps:{},triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1})).current,se=tt(Ie,Je.activeIndex),be=tt(Ie,Je.selectedIndex),$e=tt(Ie,Je.triggerElement),Re=tt(Ie,Je.positionerElement),ze=Z4(Le),We=Le??ze??null,at=x.useMemo(()=>E?"":co(G,A),[E,G,A]),yt=x.useMemo(()=>E&&Array.isArray(G)?G.map(ct=>co(ct,A)):co(G,A),[E,G,A]),_e=cn(Ie.state.triggerElement),Oe=Ue(()=>yt);e_(_e,F,G,Oe,!X,m);const He=x.useRef(G),Xe=E?Array.isArray(G)&&G.length>0:G!=null&&co(G,A)!=="";De(()=>{G!==He.current&&Ie.set("forceMount",!0)},[Ie,G]),De(()=>{V(Xe)},[Xe,V]),De(function(){const zt=pe.current;let mn;if(E){const Sn=Array.isArray(G)?G:[];if(Sn.length===0)mn=null;else{const yn=Sn[Sn.length-1],Ht=kc(zt,yn,T);mn=Ht===-1?null:Ht}}else{const Sn=kc(zt,G,T);mn=Sn===-1?null:Sn}mn===null&&(Be.current=null),!ee&&Ie.set("selectedIndex",mn)},[Xe,E,ee,G,pe,T,Ie,Be]);function rt(ct){const zt=I.initialValue;return Array.isArray(ct)&&Array.isArray(zt)?!aP(ct,zt,(mn,Sn)=>wo(mn,Sn,T)):ct!==zt}Ub(G,()=>{B(P),L(rt(G)),Y.change(G)});const sn=Ue((ct,zt)=>{p?.(ct,zt),!zt.isCanceled&&(de(ct),!ct&&(zt.reason===bo||zt.reason===Vf)&&(U(!0),D(!1),K==="onBlur"&&Y.commit(G)))}),dn=Ue(()=>{ve(!1),Ie.update({activeIndex:null,openMethod:null}),C?.(!1)});ha({enabled:!j,open:ee,ref:oe,onComplete(){ee||dn()}}),x.useImperativeHandle(j,()=>({unmount:dn}),[dn]);const pt=Ue((ct,zt)=>{l?.(ct,zt),!zt.isCanceled&&Z(ct)}),Et=Ue(()=>{const ct=Ie.state.listElement||oe.current;if(!ct)return;const zt=a_(ct.scrollHeight,ct.clientHeight),mn=xf(ct.scrollTop,zt),Sn=mn>0,yn=mn<zt;Ie.state.scrollUpArrowVisible!==Sn&&Ie.set("scrollUpArrowVisible",Sn),Ie.state.scrollDownArrowVisible!==yn&&Ie.set("scrollDownArrowVisible",yn)}),an=b2({open:ee,onOpenChange:sn,elements:{reference:$e,floating:Re}}),Wt=ZS(an,{enabled:!v&&!X,event:"mousedown"}),Zt=Ff(an),Gt=w2(an,{enabled:!v&&!X,listRef:fe,activeIndex:se,selectedIndex:be,disabledIndices:Ka,onNavigate(ct){ct===null&&!ee||Ie.set("activeIndex",ct)},focusItemOnHover:M}),fn=k2(an,{enabled:!v&&!X&&(ee||!E),listRef:ae,activeIndex:se,selectedIndex:be,disabledIndices:ct=>rC(fe.current[ct]),onMatch(ct){ee?Ie.set("activeIndex",ct):pt(pe.current[ct],nt("none"))},onTyping(ct){Se.current=ct}}),es=x.useMemo(()=>{const ct=Fn(fn.reference,Gt.reference,Zt.reference,Wt.reference,Pe);return F&&(ct.id=F),ct},[Wt.reference,fn.reference,Gt.reference,Zt.reference,Pe,F]),ds=x.useMemo(()=>Fn(Xf,fn.floating,Gt.floating,Zt.floating),[fn.floating,Gt.floating,Zt.floating]),js=Gt.item??qt;yb(()=>{Ie.update({popupProps:ds,triggerProps:es})}),De(()=>{Ie.update({id:F,modal:N,multiple:E,value:G,open:ee,mounted:Ee,transitionStatus:Ce,popupProps:ds,triggerProps:es,items:S,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,openMethod:We})},[Ie,F,N,E,G,ee,Ee,Ce,ds,es,S,R,A,T,We]);const pn=x.useMemo(()=>({store:Ie,name:P,required:k,disabled:X,readOnly:v,multiple:E,highlightItemOnHover:M,setValue:pt,setOpen:sn,listRef:fe,popupRef:oe,scrollHandlerRef:me,handleScrollArrowVisibility:Et,scrollArrowsMountedCountRef:Ae,itemProps:js,valueRef:ie,valuesRef:pe,labelsRef:ae,typingRef:Se,selectionRef:Ve,firstItemTextRef:je,selectedItemTextRef:Be,validation:Y,onOpenChangeComplete:C,alignItemWithTriggerActiveRef:we,initialValueRef:He}),[Ie,P,k,X,v,E,M,pt,sn,js,Y,C,Et]),ws=Xa(y,Y.inputRef),ba=E&&Array.isArray(G)&&G.length>0,Ps=E?void 0:P,_a=x.useMemo(()=>!E||!Array.isArray(G)||!P?null:G.map(ct=>{const zt=co(ct,A);return r.jsx("input",{type:"hidden",form:g,name:P,value:zt,disabled:X},zt)}),[E,G,g,P,A,X]);return r.jsx(QC.Provider,{value:pn,children:r.jsxs(WC.Provider,{value:an,children:[z,r.jsx("input",{...Y.getValidationProps(X,{onFocus(){Ie.state.triggerElement?.focus({focusVisible:!0})},onChange(ct){if(ct.nativeEvent.defaultPrevented||X||v)return;const zt=ct.currentTarget.value,mn=nt(fa,ct.nativeEvent);function Sn(){if(E)return;const yn=zt.toLowerCase();let Ht=pe.current.findIndex(Xs=>co(Xs,A).toLowerCase()===yn||eN(Xs,R).toLowerCase()===yn);Ht===-1&&(Ht=pe.current.findIndex((Xs,ni)=>{const Zc=ae.current[ni];return Zc!=null&&Zc.toLowerCase()===yn}));const zn=Ht===-1?void 0:pe.current[Ht];zn!=null&&pt(zn,mn)}Ie.set("forceMount",!0),queueMicrotask(Sn)}}),id:F&&Ps==null?`${F}-hidden-input`:void 0,form:g,name:Ps,autoComplete:h,value:at,disabled:X,required:k&&!ba,readOnly:v,ref:ws,style:P?SS:lb,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),_a]})})}function oP(e,t){return e??t}const kd=2,lP=400,iP={...rx,...Zb,popupSide:e=>e?{"data-popup-side":e}:null,value:()=>null},cP=x.forwardRef(function(t,s){const{render:o,className:l,id:c,disabled:u=!1,nativeButton:p=!0,style:m,...g}=t,{setTouched:h,setFocused:b,validationMode:v,state:k,disabled:N}=Wc(),{labelId:j}=lp(),{store:y,setOpen:C,selectionRef:S,validation:E,readOnly:R,required:A,alignItemWithTriggerActiveRef:T,disabled:M}=xa(),z=N||M||u,B=tt(y,Je.open),L=tt(y,Je.mounted),U=tt(y,Je.value),D=tt(y,Je.triggerProps),I=tt(y,Je.positionerElement),V=tt(y,Je.listElement),$=tt(y,Je.popupSide),q=tt(y,Je.id),Y=tt(y,Je.labelId),K=tt(y,Je.hasSelectedValue),F=L&&I?$:null,X=c??q,P=oP(j,Y);ip({id:X});const G=cn(I),Z=x.useRef(null),{getButtonProps:ee,buttonRef:de}=Hr({disabled:z,native:p}),fe=Ue(Se=>{y.set("triggerElement",Se)}),ae=kn(),oe=kn(),me=kn();x.useEffect(()=>{if(B)return me.start(lP,()=>{S.current.allowUnselectedMouseUp=!0,S.current.allowSelectedMouseUp=!0}),()=>{me.clear()};S.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},oe.clear()},[B,S,oe,me]);const Ae=Fn(D,{id:X,role:"combobox","aria-expanded":B?"true":"false","aria-haspopup":"listbox","aria-controls":B?V?.id??Zd(I)?.id:void 0,"aria-labelledby":P,"aria-readonly":R||void 0,"aria-required":A||void 0,tabIndex:z?-1:0,onFocus(Se){b(!0),B&&T.current&&C(!1,nt(fa,Se.nativeEvent)),ae.start(0,()=>{y.set("forceMount",!0)})},onBlur(Se){Qe(I,Se.relatedTarget)||(h(!0),b(!1),v==="onBlur"&&E.commit(U))},onMouseDown(Se){if(B)return;const je=mt(Se.currentTarget);function Be(Ve){if(!Z.current)return;const we=Ve.target;if(Qe(Z.current,we)||Qe(G.current,we))return;const Ee=nC(Z.current);Ve.clientX>=Ee.left-kd&&Ve.clientX<=Ee.right+kd&&Ve.clientY>=Ee.top-kd&&Ve.clientY<=Ee.bottom+kd||C(!1,nt(_S,Ve))}oe.start(0,()=>{je.addEventListener("mouseup",Be,{once:!0})})}},g,ee),ie=E.getValidationProps(z,Ae);ie.role="combobox";const pe={...k,open:B,disabled:z,value:U,readOnly:R,popupSide:F,placeholder:!K};return Nt("button",t,{ref:[s,Z,de,fe],state:pe,stateAttributesMapping:iP,props:ie})}),uP={value:()=>null},dP=x.forwardRef(function(t,s){const{className:o,render:l,children:c,placeholder:u,style:p,...m}=t,{store:g,valueRef:h}=xa(),b=tt(g,Je.value),v=tt(g,Je.items),k=tt(g,Je.itemToStringLabel),N=tt(g,Je.hasSelectedValue),j=!N&&u!=null&&c==null,y=tt(g,Je.hasNullItemLabel,j),C={value:b,placeholder:!N};let S=null;return typeof c=="function"?S=c(b):c!=null?S=c:!N&&u!=null&&!y?S=u:Array.isArray(b)?S=sP(b,v,k):S=tN(b,v,k),Nt("span",t,{state:C,ref:[s,h],props:[{children:S},m],stateAttributesMapping:uP})}),fP=x.forwardRef(function(t,s){const{render:o,className:l,style:c,...u}=t,{store:p}=xa(),g={open:tt(p,Je.open)};return Nt("span",t,{state:g,ref:s,props:[{"aria-hidden":!0,children:"▼"},u],stateAttributesMapping:C2})}),pP=x.createContext(void 0),mP=x.forwardRef(function(t,s){const{store:o}=xa(),l=tt(o,Je.mounted),c=tt(o,Je.forceMount);return l||c?r.jsx(pP.Provider,{value:!0,children:r.jsx(hb,{ref:s,...t})}):null}),nN=x.createContext(void 0);function r_(){const e=x.useContext(nN);if(!e)throw new Error(nn(59));return e}function bf(e,t){e&&Object.assign(e.style,t)}const sN={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},gP={position:"fixed"},hP=x.forwardRef(function(t,s){const{anchor:o,positionMethod:l="absolute",className:c,render:u,side:p="bottom",align:m="center",sideOffset:g=0,alignOffset:h=0,collisionBoundary:b="clipping-ancestors",collisionPadding:v,arrowPadding:k=5,sticky:N=!1,disableAnchorTracking:j,alignItemWithTrigger:y=!0,collisionAvoidance:C=qS,style:S,...E}=t,{store:R,listRef:A,labelsRef:T,alignItemWithTriggerActiveRef:M,selectedItemTextRef:z,valuesRef:B,initialValueRef:L,popupRef:U,setValue:D}=xa(),I=ZC(),V=tt(R,Je.open),$=tt(R,Je.mounted),q=tt(R,Je.modal),Y=tt(R,Je.value),K=tt(R,Je.openMethod),F=tt(R,Je.positionerElement),X=tt(R,Je.triggerElement),P=tt(R,Je.isItemEqualToValue),G=tt(R,Je.transitionStatus),Z=x.useRef(null),ee=x.useRef(null),[de,fe]=x.useState(y),ae=$&&de&&K!=="touch";!$&&de!==y&&fe(y),De(()=>{$||(Je.scrollUpArrowVisible(R.state)&&R.set("scrollUpArrowVisible",!1),Je.scrollDownArrowVisible(R.state)&&R.set("scrollDownArrowVisible",!1))},[R,$]),x.useImperativeHandle(M,()=>ae),W2((ae||q)&&V,K==="touch",F,X);const oe=Mb({anchor:o,floatingRootContext:I,positionMethod:l,mounted:$,side:p,sideOffset:g,align:m,alignOffset:h,arrowPadding:k,collisionBoundary:b,collisionPadding:v,sticky:N,disableAnchorTracking:j??ae,collisionAvoidance:C,keepMounted:!0}),me=ae?"none":oe.side,Ae=ae?gP:oe.positionerStyles,ie={open:V,side:me,align:oe.align,anchorHidden:oe.anchorHidden};De(()=>{R.set("popupSide",oe.side)},[R,oe.side]);const pe=Ue(we=>{R.set("positionerElement",we)}),Se=Ob(t,ie,{styles:Ae,transitionStatus:G,props:E,refs:[s,pe],hidden:!$,inert:!V}),je=x.useRef(0),Be=Ue(we=>{if(we.size===0&&je.current===0||B.current.length===0)return;const Ee=je.current;if(je.current=we.size,we.size===Ee)return;const ve=nt(fa);if(Ee!==0&&!R.state.multiple&&Y!==null&&kc(B.current,Y,P)===-1){const Le=L.current,Ie=Le!=null&&kc(B.current,Le,P)!==-1?Le:null;D(Ie,ve),Ie===null&&(R.set("selectedIndex",null),z.current=null)}if(Ee!==0&&R.state.multiple&&Array.isArray(Y)){const Ce=Pe=>kc(B.current,Pe,P)!==-1,Le=Y.filter(Pe=>Ce(Pe));(Le.length!==Y.length||Le.some(Pe=>!eP(Y,Pe,P)))&&(D(Le,ve),Le.length===0&&(R.set("selectedIndex",null),z.current=null))}if(V&&ae){R.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const Ce={height:""};bf(F,Ce),bf(U.current,Ce)}}),Ve=x.useMemo(()=>({...oe,side:me,alignItemWithTriggerActive:ae,setControlledAlignItemWithTrigger:fe,scrollUpArrowRef:Z,scrollDownArrowRef:ee}),[oe,me,ae,fe]);return r.jsx(ap,{elementsRef:A,labelsRef:T,onMapChange:Be,children:r.jsxs(nN.Provider,{value:Ve,children:[$&&q&&r.jsx(Bb,{inert:Jf(!V),cutout:X}),Se]})})}),Sd="base-ui-disable-scrollbar",_x={className:Sd,getElement(e){return r.jsx("style",{nonce:e,href:Sd,precedence:"base-ui:low",children:`.${Sd}{scrollbar-width:none}.${Sd}::-webkit-scrollbar{display:none}`})}},xP=x.createContext(void 0),bP={disableStyleElements:!1};function _P(){return x.useContext(xP)??bP}const vP={...Ro,...Ja},yP=x.forwardRef(function(t,s){const{render:o,className:l,style:c,finalFocus:u,...p}=t,{store:m,popupRef:g,onOpenChangeComplete:h,setOpen:b,valueRef:v,firstItemTextRef:k,selectedItemTextRef:N,multiple:j,handleScrollArrowVisibility:y,scrollHandlerRef:C,listRef:S,highlightItemOnHover:E}=xa(),{side:R,align:A,alignItemWithTriggerActive:T,isPositioned:M,setControlledAlignItemWithTrigger:z}=r_(),B=F2()!=null,L=ZC(),U=Wf(),{nonce:D,disableStyleElements:I}=_P(),V=tt(m,Je.id),$=tt(m,Je.open),q=tt(m,Je.openMethod),Y=tt(m,Je.mounted),K=tt(m,Je.popupProps),F=tt(m,Je.transitionStatus),X=tt(m,Je.triggerElement),P=tt(m,Je.positionerElement),G=tt(m,Je.listElement),Z=x.useRef(!1),ee=x.useRef(!1),de=x.useRef({}),fe=Bl(),ae=Ue(ie=>{if(!P||!g.current||!ee.current)return;if(Z.current||!T){y();return}const pe=P.style.top==="0px",Se=P.style.bottom==="0px";if(!pe&&!Se){y();return}const je=Xj(P),Be=gc(P.getBoundingClientRect().height,"y",je),Ve=mt(P),we=$t(P),Ee=we.getComputedStyle(P),ve=parseFloat(Ee.marginTop),Ce=parseFloat(Ee.marginBottom),Le=Kj(we.getComputedStyle(g.current)),Pe=Math.min(Ve.documentElement.clientHeight-ve-Ce,Le),Ie=ie.scrollTop,se=Cd(ie);let be=0,$e=null,Re=!1,ze=!1;const We=Oe=>{P.style.height=`${Oe}px`},at=(Oe,He)=>{const Xe=mc(Oe,0,Pe-Be);Xe>0&&We(Be+Xe),ie.scrollTop=He,Pe-(Be+Xe)<=Hs&&(Z.current=!0),y()},yt=pe?se-Ie:Ie,_e=Math.min(Be+yt,Pe);if(be=_e,yt<=Hs){at(yt,pe?se:0);return}if(Pe-_e>Hs)pe?ze=!0:$e=0;else if(Re=!0,Se&&Ie<se){const Oe=Be+yt-Pe;$e=Ie-(yt-Oe)}if(be=Math.ceil(be),be!==0&&We(be),ze||$e!=null){const Oe=Cd(ie),He=ze?Oe:mc($e,0,Oe);Math.abs(ie.scrollTop-He)>Hs&&(ie.scrollTop=He)}(Re||be>=Pe-Hs)&&(Z.current=!0),y()});x.useImperativeHandle(C,()=>ae,[ae]),ha({open:$,ref:g,onComplete(){$&&h?.(!0)}});const oe={open:$,transitionStatus:F,side:R,align:A};De(()=>{!P||!g.current||Object.keys(de.current).length||(de.current={top:P.style.top||"0",left:P.style.left||"0",right:P.style.right,height:P.style.height,bottom:P.style.bottom,minHeight:P.style.minHeight,maxHeight:P.style.maxHeight,marginTop:P.style.marginTop,marginBottom:P.style.marginBottom})},[g,P]),De(()=>{$||T||(ee.current=!1,Z.current=!1,bf(P,de.current))},[$,T,P,g]),De(()=>{const ie=g.current;if(!$||!X||!P||!ie||T&&!M||m.state.transitionStatus==="ending")return;if(!T){ee.current=!0,fe.request(y),ie.style.removeProperty("--transform-origin");return}const pe=jP(ie);ie.style.removeProperty("--transform-origin");try{let Se=N.current;Se?.isConnected||(Se=!Je.hasSelectedValue(m.state)&&k.current?.isConnected?k.current:null);const je=v.current,Be=$t(P),Ve=Be.getComputedStyle(P),we=Be.getComputedStyle(ie),Ee=mt(X),ve=Xj(X),Ce=Nd(X.getBoundingClientRect(),ve),Le=Nd(P.getBoundingClientRect(),ve),Pe=Ce.height,Ie=G||ie,se=Ie.scrollHeight,be=parseFloat(we.borderBottomWidth),$e=parseFloat(Ve.marginTop)||10,Re=parseFloat(Ve.marginBottom)||10,ze=parseFloat(Ve.minHeight)||100,We=Kj(we),at=5,yt=5,_e=20,Oe=Ee.documentElement.clientHeight-$e-Re,He=Ee.documentElement.clientWidth,Xe=Oe-Ce.bottom+Pe;let rt,sn=U==="rtl"?Ce.right-Le.width:Ce.left,dn=0;if(Se&&je){const pn=Nd(je.getBoundingClientRect(),ve);rt=Nd(Se.getBoundingClientRect(),ve),sn=Le.left+(U==="rtl"?pn.right-rt.right:pn.left-rt.left);const ws=pn.top-Ce.top+pn.height/2;dn=rt.top-Le.top+rt.height/2-ws}const pt=Xe+dn+Re+be;let Et=Math.min(Oe,pt);const an=Oe-$e-Re,Wt=pt-Et,Zt=He-yt;P.style.left=`${mc(sn,at,Zt-Le.width)}px`,P.style.height=`${Et}px`,P.style.maxHeight="none",P.style.marginTop=`${$e}px`,P.style.marginBottom=`${Re}px`,ie.style.height="100%";const Gt=Cd(Ie),fn=Wt>=Gt-Hs;fn&&(Et=Math.min(Oe,Le.height)-(Wt-Gt));const es=Ce.top<_e||Ce.bottom>Oe-_e||Math.ceil(Et)+Hs<Math.min(se,ze),ds=(Be.visualViewport?.scale??1)!==1&&Dr;if(es||ds){ee.current=!0,bf(P,de.current),z(!1);return}const js=Math.max(ze,Et);if(fn){const pn=Math.max(0,Oe-pt);P.style.top=Le.height>=an?"0":`${pn}px`,P.style.height=`${Et}px`,Ie.scrollTop=Cd(Ie)}else P.style.bottom="0",Ie.scrollTop=Wt;if(rt){const pn=Le.top,ws=Le.height,ba=rt.top+rt.height/2,Ps=ws>0?(ba-pn)/ws*100:50,_a=mc(Ps,0,100);ie.style.setProperty("--transform-origin",`50% ${_a}%`)}(js===Oe||Et>=We)&&(Z.current=!0),y(),E&&m.state.selectedIndex===null&&m.state.activeIndex===null&&S.current[0]!=null&&m.set("activeIndex",0),ee.current=!0}finally{pe()}},[m,$,P,X,v,k,N,g,y,T,z,fe,G,S,E,U,M]),x.useEffect(()=>{if(!T||!P||!$)return;const ie=$t(P);function pe(Se){b(!1,nt(i5,Se))}return ht(ie,"resize",pe)},[b,T,P,$]);const me={...G?{role:"presentation","aria-orientation":void 0}:{role:"listbox","aria-multiselectable":j||void 0,id:`${V}-list`},onKeyDown(ie){B&&sp.has(ie.key)&&ie.stopPropagation()},onScroll(ie){G||ae(ie.currentTarget)},...T&&{style:G?{height:"100%"}:sN}},Ae=Nt("div",t,{ref:[s,g],state:oe,stateAttributesMapping:vP,props:[K,me,Zf(F),{className:!G&&T?_x.className:void 0},p]});return r.jsxs(x.Fragment,{children:[!I&&_x.getElement(D),r.jsx(_b,{context:L,modal:!1,disabled:!Y,openInteractionType:q,returnFocus:u,restoreFocus:!0,children:Ae})]})});function Kj(e){const t=e.maxHeight||"";return t.endsWith("px")&&parseFloat(t)||1/0}function Cd(e){return a_(e.scrollHeight,e.clientHeight)}function Xj(e){return r2.getScale(e)}function gc(e,t,s){return e/s[t]}function Nd(e,t){return Oc({x:gc(e.x,"x",t),y:gc(e.y,"y",t),width:gc(e.width,"x",t),height:gc(e.height,"y",t)})}const Qj=[["transform","none"],["scale","1"],["translate","0 0"]];function jP(e){const{style:t}=e,s={};for(const[o,l]of Qj)s[o]=t.getPropertyValue(o),t.setProperty(o,l,"important");return()=>{for(const[o]of Qj){const l=s[o];l?t.setProperty(o,l):t.removeProperty(o)}}}const wP=x.forwardRef(function(t,s){const{render:o,className:l,style:c,...u}=t,{store:p,scrollHandlerRef:m}=xa(),{alignItemWithTriggerActive:g}=r_(),h=tt(p,Je.hasScrollArrows),b=tt(p,Je.openMethod),v=tt(p,Je.multiple),N={id:`${tt(p,Je.id)}-list`,role:"listbox","aria-multiselectable":v||void 0,onScroll(y){m.current?.(y.currentTarget)},...g&&{style:sN},className:h&&b!=="touch"?_x.className:void 0},j=Ue(y=>{p.set("listElement",y)});return Nt("div",t,{ref:[s,j],props:[N,u]})}),aN=x.createContext(void 0);function o_(){const e=x.useContext(aN);if(!e)throw new Error(nn(57));return e}const kP=x.memo(x.forwardRef(function(t,s){const{render:o,className:l,style:c,value:u=null,label:p,disabled:m=!1,nativeButton:g=!1,...h}=t,b=x.useRef(null),v=Gc({label:p,textRef:b,indexGuessBehavior:q2.GuessFromOrder}),{store:k,itemProps:N,setOpen:j,setValue:y,selectionRef:C,typingRef:S,valuesRef:E,multiple:R,selectedItemTextRef:A,disabled:T,readOnly:M}=xa(),z=tt(k,Je.isActive,v.index),B=tt(k,Je.open),L=tt(k,Je.isSelected,u),U=tt(k,Je.isSelectedByFocus,v.index),D=tt(k,Je.isItemEqualToValue),I=v.index,V=I!==-1,$=x.useRef(null);De(()=>{if(!V)return;const ae=E.current;return ae[I]=u,()=>{delete ae[I]}},[V,I,u,E]),De(()=>{if(!V)return;const ae=k.state.value;let oe=ae;R&&Array.isArray(ae)&&(oe=ae.length>0?ae[ae.length-1]:void 0),oe!==void 0&&wo(u,oe,D)&&(k.set("selectedIndex",I),b.current&&(A.current=b.current))},[V,I,R,D,k,u,A]);const q=x.useRef(null),Y=x.useRef("mouse"),K=x.useRef(!1),{getButtonProps:F,buttonRef:X}=Hr({disabled:m,focusableWhenDisabled:!0,native:g,composite:!0}),P={disabled:m,selected:L,highlighted:z};function G(ae){if(T||M)return;const oe=k.state.value;if(R){const me=Array.isArray(oe)?oe:[],Ae=L?tP(me,u,D):[...me,u];y(Ae,nt(El,ae))}else y(u,nt(El,ae)),j(!1,nt(El,ae))}function Z(){C.current.dragY=0}const ee={role:"option","aria-selected":L,tabIndex:B&&z?0:-1,onKeyDown(ae){q.current=ae.key,k.set("activeIndex",I),ae.key===" "&&S.current&&ae.preventDefault()},onClick(ae){const oe=ae.type==="click"&&Y.current!=="touch",me=ae.nativeEvent.pointerType,Ae=oe&&eb(ae.nativeEvent)&&(me!==void 0||z),ie=oe&&!Ae&&!K.current;K.current=!1,!(ae.type==="keydown"&&q.current===null)&&(m||ae.type==="keydown"&&q.current===" "&&S.current||ie||(q.current=null,G(ae.nativeEvent)))},onPointerEnter(ae){Y.current=ae.pointerType},onPointerMove(ae){if(ae.pointerType==="mouse"&&ae.buttons===1){const oe=C.current;oe.dragY+=ae.movementY,oe.dragY**2>=64&&(oe.allowUnselectedMouseUp=!0)}},onPointerDown(ae){Y.current=ae.pointerType,K.current=!0,Z()},onMouseUp(){if(Z(),m||Y.current==="touch"||K.current)return;const ae=!C.current.allowSelectedMouseUp&&L,oe=!C.current.allowUnselectedMouseUp&&!L;ae||oe||(K.current=!0,$.current?.click(),K.current=!1)}},de=Nt("div",t,{ref:[X,s,v.ref,$],state:P,props:[N,ee,h,F]}),fe=x.useMemo(()=>({selected:L,index:I,textRef:b,selectedByFocus:U,hasRegistered:V}),[L,I,b,U,V]);return r.jsx(aN.Provider,{value:fe,children:de})})),SP=x.forwardRef(function(t,s){const o=t.keepMounted??!1,{selected:l}=o_();return o||l?r.jsx(CP,{...t,ref:s}):null}),CP=x.memo(x.forwardRef((e,t)=>{const{render:s,className:o,style:l,keepMounted:c,...u}=e,{selected:p}=o_(),m=x.useRef(null),{transitionStatus:g,setMounted:h}=ti(p),v=Nt("span",e,{ref:[t,m],state:{selected:p,transitionStatus:g},props:[{"aria-hidden":!0,children:"✔️"},u],stateAttributesMapping:Ja});return ha({open:p,ref:m,onComplete(){p||h(!1)}}),v})),NP=x.memo(x.forwardRef(function(t,s){const{index:o,textRef:l,selectedByFocus:c,hasRegistered:u}=o_(),{firstItemTextRef:p,selectedItemTextRef:m}=xa(),{render:g,className:h,style:b,...v}=t,k=x.useCallback(j=>{j&&(u&&o===0&&(p.current=j),u&&c&&(m.current=j))},[p,m,o,c,u]);return Nt("div",t,{ref:[k,s,l],props:v})})),rN=x.forwardRef(function(t,s){const{render:o,className:l,style:c,direction:u,keepMounted:p=!1,...m}=t,g=u==="up",{store:h,popupRef:b,listRef:v,handleScrollArrowVisibility:k,scrollArrowsMountedCountRef:N}=xa(),{side:j,scrollDownArrowRef:y,scrollUpArrowRef:C}=r_(),S=g?Je.scrollUpArrowVisible:Je.scrollDownArrowVisible,E=tt(h,S),R=tt(h,Je.openMethod),A=E&&R!=="touch",T=kn(),M=g?C:y,{mounted:z,transitionStatus:B,setMounted:L}=ti(A);De(()=>(N.current+=1,h.state.hasScrollArrows||h.set("hasScrollArrows",!0),()=>{N.current=Math.max(0,N.current-1),N.current===0&&h.state.hasScrollArrows&&h.set("hasScrollArrows",!1)}),[h,N]),ha({open:A,ref:M,onComplete(){A||L(!1)}});const I=Nt("div",t,{ref:[s,M],state:{direction:u,visible:A,side:j,transitionStatus:B},props:[{"aria-hidden":!0,children:g?"▲":"▼",style:{position:"absolute"},onMouseMove($){if($.movementX===0&&$.movementY===0||T.isStarted())return;h.set("activeIndex",null);function q(){const Y=h.state.listElement??b.current;if(!Y)return;h.set("activeIndex",null),k();const K=a_(Y.scrollHeight,Y.clientHeight),F=xf(Y.scrollTop,K),X=F===(g?0:K),P=v.current;if(F!==Y.scrollTop&&(Y.scrollTop=F),P.length===0&&h.set(g?"scrollUpArrowVisible":"scrollDownArrowVisible",!X),X){T.clear();return}if(P.length>0){const G=M.current?.offsetHeight||0;Y.scrollTop=EP(P,g,F,Y.clientHeight,G,K)}T.start(40,q)}T.start(40,q)},onMouseLeave(){T.clear()}},m],stateAttributesMapping:Ja});return z||p?I:null});function EP(e,t,s,o,l,c){if(t){let h=0;const b=s+l-Hs;for(let N=0;N<e.length;N+=1){const j=e[N];if(j&&j.offsetTop>=b){h=N;break}}const v=Math.max(0,h-1),k=e[v];return v<h&&k?xf(k.offsetTop-l,c):0}let u=e.length-1;const p=s+o-l+Hs;for(let h=0;h<e.length;h+=1){const b=e[h];if(b&&b.offsetTop+b.offsetHeight>p){u=Math.max(0,h-1);break}}const m=Math.min(e.length-1,u+1),g=e[m];return m>u&&g?xf(g.offsetTop+g.offsetHeight-o+l,c):c}const RP=x.forwardRef(function(t,s){return r.jsx(rN,{...t,ref:s,direction:"down"})}),TP=x.forwardRef(function(t,s){return r.jsx(rN,{...t,ref:s,direction:"up"})}),AP=rP;function MP({className:e,...t}){return r.jsx(dP,{"data-slot":"select-value",className:St("flex flex-1 text-left",e),...t})}function OP({className:e,size:t="default",children:s,...o}){return r.jsxs(cP,{"data-slot":"select-trigger","data-size":t,className:St("flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[s,r.jsx(fP,{render:r.jsx(pa,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function zP({className:e,children:t,side:s="bottom",sideOffset:o=4,align:l="center",alignOffset:c=0,alignItemWithTrigger:u=!0,...p}){return r.jsx(mP,{children:r.jsx(hP,{side:s,sideOffset:o,align:l,alignOffset:c,alignItemWithTrigger:u,className:"isolate z-50",children:r.jsxs(yP,{"data-slot":"select-content","data-align-trigger":u,className:St("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...p,children:[r.jsx(LP,{}),r.jsx(wP,{children:t}),r.jsx(PP,{})]})})})}function DP({className:e,children:t,...s}){return r.jsxs(kP,{"data-slot":"select-item",className:St("relative flex w-full cursor-default items-center gap-2 rounded-md py-2 pr-8 pl-2.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...s,children:[r.jsx(NP,{className:"flex min-w-0 flex-1 gap-2 overflow-hidden whitespace-nowrap",children:t}),r.jsx(SP,{render:r.jsx("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:r.jsx(ho,{className:"pointer-events-none"})})]})}function LP({className:e,...t}){return r.jsx(TP,{"data-slot":"select-scroll-up-button",className:St("top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:r.jsx(Gk,{})})}function PP({className:e,...t}){return r.jsx(RP,{"data-slot":"select-scroll-down-button",className:St("bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:r.jsx(pa,{})})}function bt({value:e,onChange:t,options:s,placeholder:o="— elegir —",disabled:l,className:c,showIcon:u=!1}){return r.jsxs(AP,{value:e,onValueChange:p=>t(p??""),disabled:l,children:[r.jsx(OP,{className:Te("h-9 w-full",c),children:r.jsx(MP,{placeholder:o,children:p=>{const m=s.find(h=>h.value===p),g=u?m?.icon:void 0;return r.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[g&&r.jsx(g,{className:"size-3.5 shrink-0"}),r.jsx("span",{className:"truncate",children:m?.label??p})]})}})}),r.jsx(zP,{side:"bottom",sideOffset:6,align:"start",alignItemWithTrigger:!1,className:"w-[var(--anchor-width)] p-1.5",children:s.map(p=>{const m=p.icon;return r.jsx(DP,{value:p.value,disabled:p.disabled,children:r.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[m?r.jsx(m,{className:"size-4 shrink-0 text-muted-fg"}):null,p.description?r.jsxs("span",{className:"flex min-w-0 flex-col leading-tight",children:[r.jsx("span",{className:"truncate font-medium",children:p.label}),r.jsx("span",{className:"truncate text-[11px] text-muted-fg",children:p.description})]}):r.jsx("span",{className:"truncate",children:p.label})]})},p.value)})})]})}const Wj=320;function IP(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function BP(e){return e.agent_slug||e.actor_id||e.author||e.actor_kind||"—"}function UP({m:e}){const[t,s]=x.useState(!1),o=(e.body?.length||0)>Wj,l=!o||t?e.body:`${e.body.slice(0,Wj)}…`;return r.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsx("span",{className:"mt-0.5 shrink-0",children:e.direction==="in"?r.jsx(qk,{size:14,className:"text-blue-400"}):r.jsx(Fk,{size:14,className:"text-emerald-400"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[r.jsx("span",{className:"font-mono",children:IP(e.ts)}),r.jsx(Fe,{tone:"info",children:e.channel}),e.type&&r.jsx(Fe,{children:e.type}),r.jsx("span",{className:"font-medium text-foreground",children:BP(e)})]}),e.body&&r.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words text-xs",children:l}),o&&r.jsx("button",{type:"button",onClick:()=>s(c=>!c),className:"mt-1 text-[11px] font-medium text-sky-400 hover:underline",children:f(t?"logs.show_less":"logs.show_more")})]})]})}function HP(){const[e,t]=x.useState(!1),s=et(e?"/admin/logs?errors":null,()=>$l.logs("errors",200)),o=s.data?.entries||[];return r.jsxs("details",{className:"mb-3 rounded-lg border border-border bg-muted/20",onToggle:l=>t(l.target.open),children:[r.jsxs("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted-fg",children:[f("logs.daemon_errors"),o.length?` · ${o.length}`:""]}),r.jsxs("div",{className:"border-t border-border p-3",children:[s.isLoading&&r.jsx(ot,{}),e&&!s.isLoading&&o.length===0&&r.jsx("p",{className:"text-xs text-muted-fg",children:f("logs.no_errors")}),r.jsx("ul",{className:"space-y-1",children:o.map((l,c)=>r.jsxs("li",{className:"rounded-md bg-card px-2 py-1 text-[11px]",children:[r.jsxs("div",{className:"flex items-center gap-2 text-muted-fg",children:[typeof l.ts=="string"&&r.jsx("span",{className:"font-mono",children:new Date(l.ts).toLocaleString()}),typeof l.level=="string"&&r.jsx("span",{className:"text-destructive",children:l.level})]}),r.jsx("p",{className:"whitespace-pre-wrap break-words font-mono",children:String(l.msg??l.message??l.error??l.raw??JSON.stringify(l)).slice(0,500)})]},c))})]})]})}function VP({pid:e}){const t=!e||String(e)==="0",[s,o]=x.useState(""),[l,c]=x.useState(""),[u,p]=x.useState(""),[m,g]=x.useState(""),h=s.trim()||void 0,b=t?`/messages/global?channel=${h??""}`:`/projects/${e}/messages?channel=${h??""}`,v=et(b,()=>t?pf.global({channel:h,limit:300}):pf.project(e,{channel:h,limit:300})),k=x.useMemo(()=>[...v.data||[]].sort((y,C)=>(C.ts||"").localeCompare(y.ts||"")),[v.data]),N=x.useMemo(()=>Array.from(new Set(k.map(y=>y.type).filter(Boolean))),[k]),j=x.useMemo(()=>k.filter(y=>!(l&&y.direction!==l||u&&y.type!==u||m&&!(y.body||"").toLowerCase().includes(m.toLowerCase()))),[k,l,u,m]);return r.jsxs(Ke,{title:f("logs.title"),description:f(t?"logs.desc_global":"logs.desc_project"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ne,{placeholder:f("logs.filter_channel"),value:s,onChange:y=>o(y.target.value),className:"w-44"}),r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>v.mutate(),children:r.jsx(ua,{size:13})})]}),children:[t&&r.jsx(HP,{}),r.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[r.jsx("div",{className:"w-36",children:r.jsx(bt,{value:l,onChange:c,placeholder:f("logs.filter_dir"),options:[{value:"",label:f("logs.all_directions")},{value:"in",label:f("logs.in")},{value:"out",label:f("logs.out")}]})}),r.jsx("div",{className:"w-40",children:r.jsx(bt,{value:u,onChange:p,placeholder:f("logs.filter_type"),options:[{value:"",label:f("logs.all_types")},...N.map(y=>({value:y,label:y}))]})}),r.jsx(Ne,{placeholder:f("logs.search_text"),value:m,onChange:y=>g(y.target.value),className:"w-56"}),r.jsxs("span",{className:"text-[11px] text-muted-fg",children:[j.length," ",f("logs.count_of")," ",k.length]})]}),v.isLoading&&r.jsx(ot,{}),v.error&&r.jsx(xt,{children:f("logs.error",{msg:v.error.message})}),!v.isLoading&&!v.error&&j.length===0&&r.jsx(xt,{children:h?f("logs.no_activity_ch",{ch:h}):f("logs.no_activity")}),r.jsx("ul",{className:"space-y-1 text-sm",children:j.map((y,C)=>r.jsx(UP,{m:y},`${y.ts}-${C}`))})]})}function oN({value:e,onChange:t,options:s,placeholder:o=f("shared_ui.model_combobox_ph"),invalid:l,invalidHint:c,className:u}){const[p,m]=x.useState(!1),[g,h]=x.useState(e),b=x.useRef(null),v=x.useRef(null),[k,N]=x.useState(null);x.useEffect(()=>{h(e)},[e]),x.useLayoutEffect(()=>{if(!p)return;const E=()=>{const R=b.current;if(!R)return;const A=R.getBoundingClientRect();N({top:A.bottom+4,left:A.left,width:A.width})};return E(),window.addEventListener("scroll",E,!0),window.addEventListener("resize",E),()=>{window.removeEventListener("scroll",E,!0),window.removeEventListener("resize",E)}},[p]),x.useEffect(()=>{if(!p)return;const E=R=>{const A=R.target;b.current?.contains(A)||v.current?.contains(A)||m(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[p]);const j=g.trim().toLowerCase(),C=j&&!(g===e)?s.filter(E=>E.toLowerCase().includes(j)):s,S=E=>{t(E),h(E),m(!1)};return r.jsxs("div",{ref:b,className:Te("relative",u),children:[r.jsxs("div",{className:Te("flex items-center gap-1 rounded-lg border bg-background px-2.5 transition-colors focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",l?"border-amber-500/60":"border-border"),children:[l&&r.jsx(Ye,{content:c||f("models_ui.invalid_hint"),children:r.jsx("span",{children:r.jsx(sS,{className:"size-3.5 shrink-0 text-amber-400"})})}),r.jsx("input",{value:g,placeholder:o,onChange:E=>{h(E.target.value),t(E.target.value),m(!0)},onFocus:()=>m(!0),className:"w-full bg-transparent py-1.5 text-sm outline-none placeholder:text-muted-fg/60"}),r.jsx("button",{type:"button",tabIndex:-1,onClick:()=>m(E=>!E),className:"shrink-0 text-muted-fg hover:text-foreground",children:r.jsx(pa,{className:"size-4"})})]}),p&&C.length>0&&k&&qs.createPortal(r.jsx("ul",{ref:v,style:{position:"fixed",top:k.top,left:k.left,width:k.width},className:"z-[1000] max-h-56 overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-md ring-1 ring-foreground/10",children:C.map(E=>r.jsx("li",{children:r.jsx("button",{type:"button",onMouseDown:R=>{R.preventDefault(),S(E)},className:Te("flex w-full items-center rounded-md px-2 py-1 text-left text-sm hover:bg-accent hover:text-accent-fg",E===e&&"bg-accent/50"),children:r.jsx("span",{className:"truncate font-mono text-xs",children:E})})},E))}),document.body)]})}function Vr(){const{data:e,error:t,isLoading:s,mutate:o}=et("/admin/config",()=>$l.config.get()),l=async(c,u)=>{const p=await $l.config.patch({set:c,unset:u});return await o({config:p.config},{revalidate:!1}),p.config};return{config:e?.config||{},error:t,isLoading:s,mutate:o,patch:l}}function lN(){const{data:e,error:t,isLoading:s,mutate:o}=et("/admin/super-agent",()=>$l.superAgent());return{superAgent:e,error:t,isLoading:s,mutate:o}}const qP={anthropic:"from-orange-600 to-amber-600",openai:"from-emerald-600 to-teal-600",gemini:"from-blue-600 to-indigo-600",groq:"from-cyan-600 to-teal-600",openrouter:"from-violet-600 to-indigo-600",ollama:"from-amber-600 to-orange-600",azure:"from-blue-600 to-cyan-600",mock:"from-slate-600 to-gray-600",custom:"from-slate-600 to-gray-600"},$P={anthropic:"bg-orange-500/20 text-orange-300 border border-orange-500/40",openai:"bg-emerald-500/20 text-emerald-300 border border-emerald-500/40",gemini:"bg-blue-500/20 text-blue-300 border border-blue-500/40",groq:"bg-cyan-500/20 text-cyan-300 border border-cyan-500/40",openrouter:"bg-violet-500/20 text-violet-300 border border-violet-500/40",ollama:"bg-amber-500/20 text-amber-300 border border-amber-500/40",azure:"bg-blue-500/20 text-blue-300 border border-blue-500/40",mock:"bg-slate-500/20 text-slate-300 border border-slate-500/40",custom:"bg-slate-500/20 text-slate-300 border border-slate-500/40"},Sc=[{value:"anthropic",label:"Anthropic"},{value:"openai",label:"OpenAI-compatible"},{value:"gemini",label:"Gemini"},{value:"groq",label:"Groq"},{value:"openrouter",label:"OpenRouter"},{value:"ollama",label:"Ollama"},{value:"azure",label:"Azure OpenAI"},{value:"mock",label:"Mock (test)"},{value:"custom",label:"Custom"}];function nh(e,t){return t&&t in e?e[t]:e.custom}const _f={anthropic:ma,openai:un,gemini:TM,groq:Ll,openrouter:Hx,ollama:tS,azure:gM,mock:Xk,custom:Zl},mo={anthropic:{base_url:"",default_model:"claude-sonnet-4.6",api_key_env:"ANTHROPIC_API_KEY",known_models:["claude-opus-4.8","claude-opus-4.7","claude-opus-4.6","claude-sonnet-4.6","claude-sonnet-4.5","claude-haiku-4.5"]},openai:{base_url:"https://api.openai.com/v1",default_model:"gpt-4o-mini",api_key_env:"OPENAI_API_KEY",known_models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},gemini:{base_url:"https://generativelanguage.googleapis.com/v1beta/openai",default_model:"gemini-2.5-flash",api_key_env:"GEMINI_API_KEY",known_models:["gemini-3.5-pro","gemini-3.5-flash","gemini-3.1-pro","gemini-3.1-flash","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"]},groq:{base_url:"https://api.groq.com/openai/v1",default_model:"llama-3.3-70b-versatile",api_key_env:"GROQ_API_KEY",known_models:["llama-3.3-70b-versatile","llama-3.1-8b-instant","meta-llama/llama-4-scout-17b-16e-instruct","openai/gpt-oss-120b","openai/gpt-oss-20b","groq/compound","groq/compound-mini","qwen/qwen3-32b","whisper-large-v3-turbo"]},openrouter:{base_url:"https://openrouter.ai/api/v1",default_model:"openrouter/auto",api_key_env:"OPENROUTER_API_KEY",known_models:["openrouter/auto","openrouter/free","deepseek/deepseek-r1:free","meta-llama/llama-3.3-70b-instruct:free","google/gemini-2.0-flash-exp:free","qwen/qwen3-235b-a22b:free","anthropic/claude-sonnet-4.5","openai/gpt-4o-mini"]},ollama:{base_url:"http://127.0.0.1:11434",default_model:"gemma2:9b",api_key_env:"",known_models:[]},azure:{base_url:"",default_model:"gpt-4o-mini",api_key_env:"AZURE_OPENAI_API_KEY",known_models:["gpt-4o","gpt-4o-mini"]},mock:{base_url:"",default_model:"mock",api_key_env:"",known_models:["mock"]},custom:{base_url:"",default_model:"",api_key_env:"",known_models:[]}};function iN(e){const t=e.indexOf(":");return t<0?{provider:e,model:""}:{provider:e.slice(0,t),model:e.slice(t+1)}}function sh({value:e,onChange:t,providers:s}){const{provider:o,model:l}=iN(e),c=s.find(h=>h.slug===o),u=!!o&&!c,p=x.useMemo(()=>{const h=c?mo[c.engine]?.known_models||[]:[];return Array.from(new Set([...c?.default_model?[c.default_model]:[],...h]))},[c]),m=h=>{const b=s.find(k=>k.slug===h),v=b?.default_model||mo[b?.engine]?.default_model||"";t(v?`${h}:${v}`:`${h}:`)},g=h=>t(`${o}:${h}`);return r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsx(bt,{value:o,onChange:m,placeholder:u?f("router_panel.provider_not_found",{name:o}):f("router_panel.provider_ph"),options:s.map(h=>({value:h.slug,label:h.slug,icon:_f[h.engine]}))}),r.jsx(oN,{value:l,onChange:g,options:p,invalid:u,invalidHint:f("router_panel.provider_not_configured",{name:o})})]})}function FP(){const e=lt(),{superAgent:t,isLoading:s,mutate:o}=lN(),{config:l,patch:c}=Vr(),[u,p]=x.useState(""),[m,g]=x.useState([]),[h,b]=x.useState(""),[v,k]=x.useState(null),[N,j]=x.useState(!1),[y,C]=x.useState({model:"",fallback:[]});x.useEffect(()=>{if(!t)return;const L=t.model_fallback?.models||[],U=Array.isArray(L)?L:[];p(t.model||""),g(U),C({model:t.model||"",fallback:U})},[t]);const S=x.useMemo(()=>{const L=l.engines||{};return Object.entries(L).map(([U,D])=>({slug:U,engine:D?.engine||U,default_model:D?.default_model||mo[D?.engine||U]?.default_model}))},[l.engines]),E=L=>{const{provider:U}=iN(L);return S.some(D=>D.slug===U)};if(s||!t)return r.jsx(ot,{});const R=u!==y.model||JSON.stringify(m)!==JSON.stringify(y.fallback),A=async()=>{j(!0);try{await c({"super_agent.model":u,"super_agent.model_fallback.enabled":m.length>0,"super_agent.model_fallback.models":m}),e.success(f("router_panel.saved_toast")),C({model:u,fallback:m}),o()}catch(L){e.error(L.message)}finally{j(!1)}},T=()=>{const L=h.trim().replace(/:$/,"");!L||!L.includes(":")||m.includes(L)||(g([...m,L]),b(""))},M=(L,U)=>{const D=[...m];D[L]=U,g(D)},z=L=>{g(m.filter((U,D)=>D!==L)),v===L&&k(null)},B=(L,U)=>{const D=L+U;if(D<0||D>=m.length)return;const I=[...m];[I[L],I[D]]=[I[D],I[L]],g(I)};return r.jsx(Ke,{title:f("router_panel.title"),description:f("router_panel.description"),children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/20 p-3",children:[r.jsxs(Fe,{tone:"success",children:[r.jsx(Hx,{size:11})," ",f("router_panel.badge_default")]}),r.jsx("span",{className:`font-mono text-xs ${!E(u)&&u?"text-amber-400":""}`,children:u||"—"}),m.map(L=>r.jsxs("span",{className:"flex items-center gap-2 text-muted-fg",children:[r.jsx($k,{size:12}),r.jsx("span",{className:`font-mono text-xs ${E(L)?"":"text-amber-400"}`,children:L})]},L))]}),S.length===0?r.jsx("p",{className:"text-xs text-muted-fg",children:f("router_panel.no_providers")}):r.jsx(le,{label:f("router_panel.active_model_label"),hint:f("router_panel.active_model_hint"),children:r.jsx(sh,{value:u,onChange:p,providers:S})}),r.jsxs("div",{className:"rounded-lg border border-border bg-muted/20 p-3",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("div",{className:"text-sm font-medium",children:f("router_panel.fallback_title")}),r.jsx("div",{className:"text-xs text-muted-fg",children:f("router_panel.fallback_desc")})]}),r.jsxs("ul",{className:"mb-3 space-y-1",children:[m.map((L,U)=>{const D=!E(L),I=v===U;return r.jsx("li",{className:"rounded-md bg-card px-2 py-1.5 text-xs",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"w-6 text-muted-fg",children:["#",U+1]}),I?r.jsx("div",{className:"flex-1",children:r.jsx(sh,{value:L,onChange:V=>M(U,V),providers:S})}):r.jsxs("button",{type:"button",onClick:()=>k(U),className:"flex flex-1 items-center gap-1.5 text-left",children:[D&&r.jsx(sS,{size:12,className:"text-amber-400"}),r.jsx("span",{className:`font-mono ${D?"text-amber-400":""}`,children:L})]}),I?r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>k(null),children:f("router_panel.done")}):r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>k(U),children:r.jsx(Eo,{size:12})}),r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>B(U,-1),disabled:U===0,children:"↑"}),r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>B(U,1),disabled:U===m.length-1,children:"↓"}),r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>z(U),children:r.jsx(Zn,{size:12})})]})},`${U}-${L}`)}),m.length===0&&r.jsx("li",{className:"text-xs text-muted-fg",children:f("router_panel.fallback_empty")})]}),S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"text-xs text-muted-fg",children:f("router_panel.add_to_chain")}),r.jsx(sh,{value:h,onChange:b,providers:S}),r.jsxs(ce,{size:"sm",variant:"secondary",onClick:T,disabled:!h.includes(":")||h.endsWith(":"),children:[r.jsx(tn,{size:13})," ",f("router_panel.add_to_chain")]})]})]}),r.jsx(ce,{variant:"primary",loading:N,disabled:!R,onClick:A,children:f(R?"router_panel.save":"router_panel.saved")})]})})}function GP({provider:e,onEdit:t,onDelete:s,onToggle:o}){const l=nh(qP,e.engine),c=nh($P,e.engine),u=nh(_f,e.engine),p=Sc.find(b=>b.value===e.engine)?.label||e.engine,m=typeof e.api_key=="string"&&e.api_key.length>0,g=jo(e.api_key),h=e.is_active!==!1;return r.jsxs("div",{className:"group flex h-full cursor-pointer flex-col gap-3 rounded-xl border border-border bg-card p-4 transition-colors hover:border-muted-fg/50",onClick:t,children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("div",{className:Te("flex size-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br",l),children:r.jsx(u,{className:"size-5 text-white"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("h3",{className:"truncate text-sm font-semibold",children:e.name||e.slug}),r.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:e.slug}),r.jsxs("span",{className:Te("mt-1 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium",c),children:[r.jsx(u,{className:"size-3"})," ",p]})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[r.jsx(Ye,{content:f(h?"providers_modal.toggle_active":"providers_modal.toggle_inactive"),children:r.jsxs("button",{type:"button",onClick:b=>{b.stopPropagation(),o()},className:Te("flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-medium transition-colors",h?"border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/10":"border-border text-muted-fg hover:text-foreground"),children:[r.jsx("span",{className:Te("size-1.5 rounded-full",h?"bg-emerald-400":"bg-muted-fg/40")}),f(h?"providers_card.active":"providers_card.off")]})}),r.jsx(Ye,{content:f("providers_modal.delete"),children:r.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),s()},className:"rounded-md p-1 text-muted-fg hover:bg-destructive/10 hover:text-destructive",children:r.jsx(Zn,{className:"size-3.5"})})})]})]}),r.jsxs("div",{className:"mt-auto space-y-1 text-xs",children:[r.jsx(tc,{label:f("providers_card.model"),value:e.default_model||"—",mono:!0}),e.base_url&&r.jsx(tc,{label:f("providers_card.base_url"),value:e.base_url,mono:!0,truncate:!0}),r.jsx(tc,{label:f("providers_card.api_key"),value:m?g?`…${g}`:f("providers_card.key_set"):"—",mono:!!g}),e.default_temperature!==void 0&&r.jsx(tc,{label:f("providers_card.temp"),value:e.default_temperature.toFixed(1)}),e.pricing?.input_per_million!==void 0&&r.jsx(tc,{label:f("providers_card.price_io"),value:`${e.pricing.input_per_million??0} / ${e.pricing.output_per_million??0}`})]})]})}function tc({label:e,value:t,mono:s,truncate:o}){return r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-muted-fg",children:e}),r.jsx("span",{className:Te("text-foreground",s&&"font-mono",o&&"max-w-[180px] truncate"),children:t})]})}const Zj={name:"",slug:"",engine:"anthropic",base_url:"",api_key_value:"",default_model:"",default_temperature:.7,default_max_tokens:4096,is_active:!0,context_limit_tokens:2e5,model_context_limits_json:"",p_input:"",p_output:"",p_cache_read:"",p_cache_write:""},YP=["anthropic","openai","gemini","groq","openrouter","ollama","custom"];function nc(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ed(e){if(e==null)return"";const t=Number(e);return Number.isFinite(t)?String(t):""}function KP(e){return{name:e.name||e.slug,slug:e.slug,engine:e.engine||"custom",base_url:e.base_url||"",api_key_value:"",default_model:e.default_model||"",default_temperature:e.default_temperature??.7,default_max_tokens:e.default_max_tokens??4096,is_active:e.is_active!==!1,context_limit_tokens:e.context_limit_tokens??2e5,model_context_limits_json:e.model_context_limits?JSON.stringify(e.model_context_limits,null,2):"",p_input:Ed(e.pricing?.input_per_million),p_output:Ed(e.pricing?.output_per_million),p_cache_read:Ed(e.pricing?.cache_read_per_million),p_cache_write:Ed(e.pricing?.cache_write_per_million)}}function XP({open:e,initial:t,existingSlugs:s,onClose:o,onSave:l}){const c=!!t,[u,p]=x.useState(Zj),[m,g]=x.useState(!1),[h,b]=x.useState(null),[v,k]=x.useState([]),[N,j]=x.useState(!1),[y,C]=x.useState(null),[S,E]=x.useState(!1),[R,A]=x.useState("");x.useEffect(()=>{if(!e)return;const F=t?KP(t):Zj;p(F),b(null),C(null),E(!1);const X=mo[F.engine];k(X?.known_models||[])},[e,t]);const T=F=>p(X=>({...X,...F})),M=F=>{const X=mo[F];T({engine:F,name:F==="custom"?u.name:Sc.find(P=>P.value===F)?.label||F,slug:F==="custom"?u.slug:F,base_url:X.base_url,default_model:X.default_model}),k(X.known_models),C(null)},z=F=>{const X=mo[F];T({engine:F,base_url:u.base_url||X.base_url,default_model:u.default_model||X.default_model}),k(X.known_models)},B=async()=>{j(!0),C(null);try{const F=await mf.models({engine:u.engine,slug:u.slug||nc(u.name),base_url:u.base_url||void 0,api_key:u.api_key_value||void 0});if(F.error){C(F.error);return}k(F.models),F.models.length===0&&C(f("providers_modal.err_no_models"))}catch(F){C(F.message||f("providers_modal.err_list_models"))}finally{j(!1)}},L=x.useMemo(()=>u.default_model&&!v.includes(u.default_model)?[u.default_model,...v]:v,[v,u.default_model]),U=()=>{const F=(u.slug||nc(u.name)).trim();if(!F)return b(f("providers_modal.err_slug_required")),null;if(!c&&s.includes(F))return b(f("providers_modal.err_slug_exists",{slug:F})),null;let X;if(u.model_context_limits_json.trim())try{const Z=JSON.parse(u.model_context_limits_json);if(!Z||typeof Z!="object"||Array.isArray(Z))throw new Error;X=Z}catch{return b(f("providers_modal.err_model_limits_json")),null}const G=[u.p_input,u.p_output,u.p_cache_read,u.p_cache_write].map(Z=>Z.trim()).some(Boolean)?{input_per_million:Number(u.p_input||0),output_per_million:Number(u.p_output||0),cache_read_per_million:Number(u.p_cache_read||0),cache_write_per_million:Number(u.p_cache_write||0)}:void 0;return{provider:{slug:F,name:u.name.trim()||F,engine:u.engine,base_url:u.base_url.trim()||void 0,default_model:u.default_model.trim()||void 0,default_temperature:u.default_temperature,default_max_tokens:u.default_max_tokens,is_active:u.is_active,context_limit_tokens:u.context_limit_tokens||void 0,model_context_limits:X,pricing:G},modelLimits:X}},D=()=>{const F=U();if(!F)return;const{provider:X}=F,P={name:X.name,engine:X.engine,is_active:X.is_active!==!1,default_temperature:X.default_temperature,default_max_tokens:X.default_max_tokens};X.base_url&&(P.base_url=X.base_url),X.default_model&&(P.default_model=X.default_model),X.context_limit_tokens&&(P.context_limit_tokens=X.context_limit_tokens),X.model_context_limits&&(P.model_context_limits=X.model_context_limits),X.pricing&&(P.pricing=X.pricing),u.api_key_value.trim()&&(P.api_key=u.api_key_value.trim()),A(JSON.stringify(P,null,2)),b(null),E(!0)},I=async()=>{g(!0),b(null);try{if(S){const X=(u.slug||nc(u.name)).trim();if(!X){b(f("providers_modal.err_slug_required_form"));return}let P;try{P=JSON.parse(R)}catch{b(f("providers_modal.err_json_invalid"));return}if(!P||typeof P!="object"||Array.isArray(P)){b(f("providers_modal.err_json_object"));return}const G=P;if(!G.engine||typeof G.engine!="string"){b(f("providers_modal.err_engine_missing"));return}const Z={slug:X,name:typeof G.name=="string"?G.name:X,engine:String(G.engine),base_url:typeof G.base_url=="string"?G.base_url:void 0,default_model:typeof G.default_model=="string"?G.default_model:void 0,is_active:G.is_active!==!1};await l({provider:Z,raw:G,originalSlug:t?.slug}),o();return}const F=U();if(!F)return;await l({provider:F.provider,apiKeyValue:u.api_key_value.trim()||void 0,originalSlug:t?.slug}),o()}catch(F){b(F.message||f("providers_modal.err_save"))}finally{g(!1)}},V=c&&is(t?.api_key),$=jo(t?.api_key),q=V?f("providers_modal.api_key_set",{suffix:$??""}):"sk-…",Y=u.engine==="ollama",K=mo[u.engine]?.api_key_env;return r.jsx(On,{open:e,onClose:o,title:c?f("providers_modal.edit_title",{name:t?.name||t?.slug||""}):f("providers_modal.new_title"),description:f("providers_modal.description"),size:"lg",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:o,disabled:m,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:I,loading:m,children:f(c?"common.save":"common.create")})]}),children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[c?r.jsx("span",{}):r.jsx("div",{className:"flex flex-wrap gap-1.5",children:YP.map(F=>{const X=_f[F],P=F==="custom"?f("providers_modal.custom"):Sc.find(Z=>Z.value===F)?.label||F,G=u.engine===F;return r.jsxs("button",{type:"button",onClick:()=>M(F),className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${G?"border-emerald-500/50 bg-emerald-500/10 text-emerald-400":"border-border text-muted-fg hover:border-muted-fg/60 hover:text-foreground"}`,children:[r.jsx(X,{className:"size-3.5"})," ",P]},F)})}),r.jsxs("button",{type:"button",onClick:()=>S?E(!1):D(),className:`flex shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${S?"border-sky-500/50 bg-sky-500/10 text-sky-400":"border-border text-muted-fg hover:text-foreground"}`,children:[r.jsx(cM,{className:"size-3.5"})," ",f(S?"providers_modal.form_mode":"providers_modal.json_mode")]})]}),S?r.jsxs("div",{className:"space-y-2",children:[r.jsx(le,{label:f("providers_modal.json_label"),hint:f("providers_modal.json_hint",{slug:u.slug||nc(u.name)||"<slug>"}),children:r.jsx(Mn,{rows:14,className:"font-mono text-xs",value:R,onChange:F=>A(F.target.value),spellCheck:!1})}),r.jsx("p",{className:"text-[11px] text-muted-fg",children:f("providers_modal.json_help")})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("providers_modal.name_label"),children:r.jsx(Ne,{value:u.name,onChange:F=>T({name:F.target.value,slug:c?u.slug:nc(F.target.value)}),placeholder:f("providers_modal.name_ph")})}),r.jsx(le,{label:f("providers_modal.engine_label"),children:r.jsx(bt,{value:u.engine,onChange:F=>z(F),options:Sc.map(F=>({value:F.value,label:F.label,icon:_f[F.value]}))})})]}),r.jsx(le,{label:f("providers_modal.base_url_label"),hint:f("providers_modal.base_url_hint"),children:r.jsx(Ne,{value:u.base_url,onChange:F=>T({base_url:F.target.value}),placeholder:f("providers_modal.base_url_ph")})}),!Y&&r.jsx(le,{label:f("providers_modal.api_key_label"),hint:V?f("providers_modal.api_key_hint_existing"):K?f("providers_modal.api_key_hint_env",{env:K}):f("providers_modal.api_key_hint"),children:r.jsx(Ne,{type:"password",autoComplete:"new-password",value:u.api_key_value,onChange:F=>T({api_key_value:F.target.value}),placeholder:q})}),r.jsx(le,{label:f("providers_modal.model_label"),children:r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(oN,{value:u.default_model,onChange:F=>T({default_model:F}),options:L,className:"flex-1"}),r.jsx(Ye,{content:f("providers_modal.list_models_hint"),children:r.jsxs(ce,{size:"sm",variant:"secondary",onClick:B,disabled:N,"aria-label":f("providers_modal.list_models_hint"),children:[N?r.jsx(Af,{className:"size-3.5 animate-spin"}):r.jsx(ua,{className:"size-3.5"}),f("providers_modal.load_models")]})})]}),y&&r.jsx("p",{className:"text-[11px] text-amber-400",children:y})]})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("providers_modal.max_tokens_label"),children:r.jsx(Ne,{type:"number",min:256,step:256,value:u.default_max_tokens,onChange:F=>T({default_max_tokens:parseInt(F.target.value)||4096})})}),r.jsx(le,{label:f("providers_modal.temperature_label",{value:u.default_temperature.toFixed(1)}),children:r.jsx("input",{type:"range",min:0,max:2,step:.1,value:u.default_temperature,onChange:F=>T({default_temperature:parseFloat(F.target.value)}),className:"mt-2 w-full accent-foreground"})})]}),r.jsxs("details",{className:"rounded-md border border-border bg-muted/20 p-3",children:[r.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted-fg",children:f("providers_modal.pricing_summary")}),r.jsxs("div",{className:"mt-3 space-y-3",children:[r.jsx(le,{label:f("providers_modal.context_limit_label"),children:r.jsx(Ne,{type:"number",min:0,step:1024,value:u.context_limit_tokens,onChange:F=>T({context_limit_tokens:parseInt(F.target.value)||0})})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("providers_modal.price_input"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_input,onChange:F=>T({p_input:F.target.value}),placeholder:"0.15"})}),r.jsx(le,{label:f("providers_modal.price_output"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_output,onChange:F=>T({p_output:F.target.value}),placeholder:"0.60"})}),r.jsx(le,{label:f("providers_modal.price_cache_read"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_cache_read,onChange:F=>T({p_cache_read:F.target.value}),placeholder:"0.03"})}),r.jsx(le,{label:f("providers_modal.price_cache_write"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_cache_write,onChange:F=>T({p_cache_write:F.target.value}),placeholder:"0.00"})})]}),r.jsx(le,{label:f("providers_modal.model_limits_label"),hint:'{"gpt-4o-mini":128000}',children:r.jsx(Mn,{rows:3,className:"font-mono text-xs",value:u.model_context_limits_json,onChange:F=>T({model_context_limits_json:F.target.value})})})]})]}),r.jsx(Ft,{checked:u.is_active,onChange:F=>T({is_active:F}),label:f("providers_modal.active_label")})]}),h&&r.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:h})]})})}const QP=new Set(Sc.map(e=>e.value));function WP(e,t){const s=typeof t.engine=="string"&&t.engine||(QP.has(e)?e:"custom");return{slug:e,name:typeof t.name=="string"?t.name:void 0,engine:s,base_url:typeof t.base_url=="string"?t.base_url:void 0,api_key:typeof t.api_key=="string"?t.api_key:void 0,default_model:typeof t.default_model=="string"?t.default_model:void 0,default_temperature:typeof t.default_temperature=="number"?t.default_temperature:void 0,default_max_tokens:typeof t.default_max_tokens=="number"?t.default_max_tokens:void 0,is_active:typeof t.is_active=="boolean"?t.is_active:void 0,context_limit_tokens:typeof t.context_limit_tokens=="number"?t.context_limit_tokens:void 0,model_context_limits:t.model_context_limits||void 0,pricing:t.pricing||void 0}}function ZP(){const e=lt(),{config:t,isLoading:s,patch:o,mutate:l}=Vr(),[c,u]=x.useState(!1),[p,m]=x.useState(null);if(s)return r.jsx(ot,{});const g=t.engines||{},h=Object.entries(g).map(([C,S])=>WP(C,S||{})),b=h.map(C=>C.slug),v=()=>{m(null),u(!0)},k=C=>{m(C),u(!0)},N=async({provider:C,apiKeyValue:S,raw:E})=>{if(E){await o({[`engines.${C.slug}`]:E}),e.success(f("engines_panel.saved_json")),l();return}const R=`engines.${C.slug}`,A={[`${R}.name`]:C.name,[`${R}.engine`]:C.engine,[`${R}.is_active`]:C.is_active!==!1,[`${R}.default_temperature`]:C.default_temperature,[`${R}.default_max_tokens`]:C.default_max_tokens},T=[],M=(z,B)=>{B===void 0||B===""?T.push(`${R}.${z}`):A[`${R}.${z}`]=B};M("base_url",C.base_url),M("default_model",C.default_model),M("context_limit_tokens",C.context_limit_tokens),M("pricing",C.pricing),M("model_context_limits",C.model_context_limits),S&&(A[`${R}.api_key`]=S),await o(A,T),e.success(f("engines_panel.saved")),l()},j=async C=>{try{await o({[`engines.${C.slug}.is_active`]:C.is_active===!1}),l()}catch(S){e.error(S.message)}},y=async C=>{if(confirm(f("engines_panel.delete_confirm",{name:C.name||C.slug})))try{await o(void 0,[`engines.${C.slug}`]),e.success(f("engines_panel.deleted")),l()}catch(S){e.error(S.message)}};return r.jsxs(Ke,{title:f("engines_panel.title"),description:f("engines_panel.description"),action:r.jsxs(ce,{size:"sm",variant:"primary",onClick:v,children:[r.jsx(tn,{size:14})," ",f("engines_panel.new_btn")]}),children:[h.length===0?r.jsx(xt,{children:f("engines_panel.empty")}):r.jsxs("div",{className:"grid grid-cols-1 items-stretch gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[h.map(C=>r.jsx(GP,{provider:C,onEdit:()=>k(C),onDelete:()=>y(C),onToggle:()=>j(C)},C.slug)),r.jsxs("button",{type:"button",onClick:v,className:"flex min-h-[120px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border text-muted-fg transition-colors hover:border-muted-fg/60 hover:text-foreground",children:[r.jsx(tn,{size:20}),r.jsx("span",{className:"text-sm font-medium",children:f("engines_panel.add_card")})]})]}),r.jsx(XP,{open:c,initial:p,existingSlugs:b,onClose:()=>{u(!1),m(null)},onSave:N})]})}function cN(){return r.jsxs("div",{className:"space-y-6",children:[r.jsx(FP,{}),r.jsx(ZP,{})]})}function JP(){const e=lt(),[t,s]=x.useState(!1),l=et(t?"/agents/vault?include_removed=1":"/agents/vault",()=>rn.vault({includeRemoved:t})),c=l.data||[],[u,p]=x.useState(null),m=async h=>{const b=h.source!=="user",v=b?f("base.defaults_tombstone_msg",{slug:h.slug}):f("base.defaults_delete_msg",{slug:h.slug});if(confirm(v))try{await rn.vaultRemove(h.slug),e.success(f(b?"base.defaults_hidden":"base.defaults_deleted")),l.mutate()}catch(k){e.error(k.message)}},g=async h=>{try{await rn.vaultRestore(h),e.success(f("base.defaults_restored")),l.mutate()}catch(b){e.error(b.message)}};return r.jsxs(Ke,{title:f("base.defaults_title"),description:f("base.defaults_desc"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ft,{checked:t,onChange:s,label:f("base.defaults_show_removed")}),r.jsxs(ce,{size:"sm",onClick:()=>p("new"),children:[r.jsx(tn,{size:14})," ",f("base.defaults_new")]})]}),children:[l.isLoading&&r.jsx(ot,{}),!l.isLoading&&c.length===0&&r.jsx(xt,{children:f("base.defaults_empty")}),r.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:c.map(h=>{const b=t&&h.tombstoned;return r.jsxs("div",{className:`flex flex-col gap-2 rounded-xl border bg-card p-4 ${b?"border-dashed border-border opacity-60":"border-border"}`,children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[r.jsx("div",{className:"flex size-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-slate-600 to-gray-600",children:h.is_master?r.jsx(Ga,{className:"size-4 text-white"}):r.jsx(un,{className:"size-4 text-white"})}),r.jsx("span",{className:"truncate text-sm font-semibold",children:h.slug}),r.jsx(e6,{source:h.source})]}),r.jsx("div",{className:"flex shrink-0 items-center gap-0.5",children:b?r.jsx(ah,{label:f("base.defaults_restore"),onClick:()=>g(h.slug),variant:"secondary",children:r.jsx(Fx,{size:13})}):r.jsxs(r.Fragment,{children:[r.jsx(ah,{label:f("base.defaults_edit"),onClick:()=>p(h),variant:"ghost",children:r.jsx(Eo,{size:13})}),r.jsx(ah,{label:h.source==="user"?f("base.defaults_delete"):f("base.defaults_hide"),onClick:()=>m(h),variant:"ghost-destructive",children:r.jsx(Zn,{size:13})})]})})]}),h.model?r.jsx(Fe,{tone:"info",children:h.model}):r.jsx("span",{className:"text-[10px] text-muted-fg",children:f("agents_ui.model_router_default")}),h.description&&r.jsx("p",{className:"line-clamp-3 text-xs text-muted-fg",children:h.description}),r.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.role&&r.jsx(Fe,{children:h.role}),h.skills?.map(v=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(ma,{size:9})," ",v]},v)),h.tools?.map(v=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(Zl,{size:9})," ",v]},v))]})]},h.slug)})}),u!==null&&r.jsx(t6,{agent:u==="new"?null:u,onClose:()=>p(null),onSaved:()=>{p(null),l.mutate()}})]})}function e6({source:e}){return e==="user"?r.jsx(Fe,{tone:"success",children:f("agents_ui.source_user")}):e==="user-override"?r.jsx(Fe,{tone:"warning",children:f("agents_ui.source_override")}):r.jsx(Fe,{tone:"muted",children:f("agents_ui.source_bundled")})}function ah({label:e,onClick:t,variant:s="ghost",children:o}){const l="inline-flex size-7 items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",c={ghost:"text-muted-fg hover:bg-accent hover:text-accent-fg","ghost-destructive":"text-muted-fg hover:bg-destructive/15 hover:text-destructive",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80"};return r.jsxs(zb,{children:[r.jsx(Db,{render:r.jsx("button",{type:"button",onClick:t,"aria-label":e,className:`${l} ${c[s]}`,children:o})}),r.jsx(Lb,{children:e})]})}function t6({agent:e,onClose:t,onSaved:s}){const o=lt(),[l,c]=x.useState(!1),u=!e,[p,m]=x.useState(e?.slug??""),[g,h]=x.useState(e?.role??""),[b,v]=x.useState(e?.model??""),[k,N]=x.useState(e?.description??""),[j,y]=x.useState(e?.language??"es"),[C,S]=x.useState((e?.skills??[]).join(", ")),[E,R]=x.useState((e?.tools??[]).join(", ")),[A,T]=x.useState(!!e?.is_master),[M,z]=x.useState(e?.body??""),B=async()=>{const L={role:g||void 0,model:b||void 0,description:k||void 0,language:j||void 0,skills:C,tools:E,is_master:A};c(!0);try{if(u){if(!/^[a-z][a-z0-9_-]*$/.test(p))throw new Error(f("base.defaults_slug_invalid"));await rn.vaultCreate(p,L,M),o.success(f("base.defaults_created",{slug:p}))}else await rn.vaultPatch(e.slug,{fields:L,body:M}),o.success(f("base.defaults_saved",{slug:e.slug}));s()}catch(U){o.error(U.message)}finally{c(!1)}};return r.jsx(On,{open:!0,onClose:t,title:u?f("base.defaults_new_title"):f("base.defaults_edit_title",{slug:e.slug}),description:u?f("base.defaults_new_desc"):e.source==="bundled"?f("base.defaults_bundled_desc"):f("base.defaults_user_desc"),size:"lg",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:l,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:B,loading:l,children:f("common.save")})]}),children:r.jsxs("div",{className:"space-y-3",children:[u&&r.jsx(le,{label:"slug",hint:f("agents_ui.slug_kebab_hint"),children:r.jsx(Ne,{autoFocus:!0,value:p,onChange:L=>m(L.target.value),placeholder:"reviewer"})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:"role",children:r.jsx(Ne,{value:g,onChange:L=>h(L.target.value),placeholder:"Code reviewer"})}),r.jsx(le,{label:"model",children:r.jsx(Ne,{value:b,onChange:L=>v(L.target.value),placeholder:"openrouter:..."})}),r.jsx(le,{label:"language",children:r.jsx(Ne,{value:j,onChange:L=>y(L.target.value),placeholder:"es"})}),r.jsx(le,{label:"is_master",children:r.jsx("div",{className:"flex h-9 items-center",children:r.jsx(Ft,{checked:A,onChange:T,label:f("base.defaults_master_label")})})})]}),r.jsx(le,{label:"description",children:r.jsx(Ne,{value:k,onChange:L=>N(L.target.value)})}),r.jsx(le,{label:"skills",hint:f("agents_ui.comma_separated"),children:r.jsx(Ne,{value:C,onChange:L=>S(L.target.value),placeholder:"code-review, git"})}),r.jsx(le,{label:"tools",hint:f("agents_ui.comma_separated"),children:r.jsx(Ne,{value:E,onChange:L=>R(L.target.value),placeholder:"read, write, run"})}),r.jsx(le,{label:"body",hint:f("agents_ui.body_hint"),children:r.jsx(Mn,{value:M,onChange:L=>z(L.target.value),rows:10,placeholder:"# Mission\\n..."})})]})})}const n6=20,Jj=[10,20,50,100];function l_({key:e,fetchPage:t,resetKey:s,initialPageSize:o=n6,swr:l}){const[c,u]=x.useState(1),[p,m]=x.useState(o);x.useEffect(()=>{u(1)},[s]);const g=(c-1)*p,h=et(e==null?null:[e,p,g],()=>t(p,g),{keepPreviousData:!0,...l}),b=h.data?.total??0,v=Math.max(1,Math.ceil(b/p)),k=Math.min(c,v);x.useEffect(()=>{c!==k&&u(k)},[c,k]);const N=b===0?0:g,j=Math.min(g+p,b);return{items:h.data?.items??[],isLoading:h.isLoading,error:h.error,mutate:h.mutate,page:k,pageCount:v,total:b,start:N,end:j,pageSize:p,setPage:u,setPageSize:y=>{m(y),u(1)}}}function s6({page:e,pageCount:t,total:s,start:o,end:l,pageSize:c,onPage:u,onPageSize:p}){return s<=Jj[0]?null:r.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-3 text-xs text-muted-fg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"tabular-nums",children:f("common.pager_range",{from:o+1,to:l,total:s})}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{children:f("common.pager_per_page")}),r.jsx("div",{className:"w-[4.5rem]",children:r.jsx(bt,{value:String(c),onChange:m=>p(Number(m)),options:Jj.map(m=>({value:String(m),label:String(m)}))})})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(ce,{size:"sm",variant:"ghost",disabled:e<=1,onClick:()=>u(e-1),"aria-label":f("common.pager_prev"),children:r.jsx(uM,{size:14})}),r.jsx("span",{className:"px-1 tabular-nums",children:f("common.pager_page",{page:e,total:t})}),r.jsx(ce,{size:"sm",variant:"ghost",disabled:e>=t,onClick:()=>u(e+1),"aria-label":f("common.pager_next"),children:r.jsx(Wl,{size:14})})]})]})}function i_({paged:e,fullHeight:t,className:s,children:o}){const l=r.jsx(s6,{page:e.page,pageCount:e.pageCount,total:e.total,start:e.start,end:e.end,pageSize:e.pageSize,onPage:e.setPage,onPageSize:e.setPageSize});return t?r.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[r.jsx("div",{className:Te("min-h-0 flex-1 overflow-y-auto",s),children:o}),r.jsx("div",{className:"shrink-0",children:l})]}):r.jsxs("div",{className:s,children:[o,l]})}const a6={apx:"success",claude:"info",codex:"warning"};function r6(){const e=lt(),t=op(),[s,o]=x.useState(""),[l,c]=x.useState(""),[u,p]=x.useState(""),[m,g]=x.useState(!1);x.useEffect(()=>{const y=setTimeout(()=>p(l.trim()),350);return()=>clearTimeout(y)},[l]);const h=l_({key:`/sessions?engine=${s}&q=${u}&deep=${m?1:0}`,fetchPage:(y,C)=>HD.page({engine:s||void 0,q:u||void 0,deep:m,limit:y,offset:C}),resetKey:`${s}|${u}|${m?1:0}`}),b=()=>{c(""),p(""),o(""),g(!1)},v=async y=>{try{await navigator.clipboard.writeText(`apx session resume ${y.id} --continue`),e.success(f("base.sessions_cmd_copied"))}catch{e.error(f("base.sessions_copy_failed"))}},k=y=>{const C=`Continue this session: ${y.id} (engine: ${y.engine}${y.title?`, title: "${y.title}"`:""}${y.cwd?`, folder: ${y.cwd}`:""}). With these instructions: `;window.dispatchEvent(new CustomEvent("apx:roby-prompt",{detail:{prompt:C}}))},N=async y=>{if(!y.cwd){e.error(f("base.sessions_no_folder"));return}try{await wC.exec({kind:"open_path",target:y.cwd})}catch(C){e.error(f("base.sessions_folder_failed",{msg:C.message}))}},j=async y=>{const C=y.path||y.cwd;if(!C){e.error(f("base.sessions_no_path"));return}try{await navigator.clipboard.writeText(C),e.success(f("base.sessions_path_copied"))}catch{e.error(f("base.sessions_copy_failed"))}};return r.jsxs(Ke,{fullHeight:!0,title:f("base.sessions_title"),description:f("base.sessions_desc"),action:r.jsx(Ye,{content:f("base.sessions_refresh"),children:r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>h.mutate(),children:r.jsx(ua,{size:13})})}),children:[r.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(_c,{size:14,className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-fg"}),r.jsx(Ne,{className:"pl-8",placeholder:f("base.sessions_search_ph"),value:l,onChange:y=>c(y.target.value)})]}),r.jsx(Ye,{content:f("base.sessions_deep_tip"),children:r.jsx(ce,{size:"sm",variant:m?"primary":"secondary",onClick:()=>g(y=>!y),children:f("base.sessions_deep")})}),r.jsx("div",{className:"w-36",children:r.jsx(bt,{value:s,onChange:o,options:[{value:"",label:f("base.sessions_all")},{value:"apx",label:"apx"},{value:"claude",label:"claude"},{value:"codex",label:"codex"}]})}),r.jsx(Ye,{content:f("base.sessions_clear"),children:r.jsx(ce,{size:"sm",variant:"ghost",onClick:b,children:r.jsx(Ys,{size:14})})})]}),h.isLoading&&r.jsx(ot,{}),h.error&&r.jsx(xt,{children:f("base.sessions_error",{msg:h.error.message})}),!h.isLoading&&!h.error&&h.total===0&&r.jsx(xt,{children:u?f("base.sessions_no_match",{q:u}):f("base.sessions_empty")}),r.jsx(i_,{paged:h,fullHeight:!0,children:r.jsx("ul",{className:"space-y-1 text-sm",children:h.items.map((y,C)=>r.jsxs("li",{className:"group flex items-center gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsx(Fe,{tone:a6[y.engine]||"muted",children:y.engine}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"truncate",children:y.title||y.id}),r.jsxs("div",{className:"flex items-center gap-2 font-mono text-[10px] text-muted-fg",children:[r.jsx("span",{className:"shrink-0",children:y.id}),y.cwd&&r.jsxs("span",{className:"truncate",children:["· ",y.cwd]})]})]}),y.mtime>0&&r.jsx("span",{className:"shrink-0 text-[11px] text-muted-fg",children:new Date(y.mtime).toLocaleString()}),r.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 opacity-60 transition-opacity group-hover:opacity-100",children:[r.jsx(Ye,{content:f("base.sessions_act_cmd"),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_cmd"),onClick:()=>v(y),children:r.jsx(Ya,{size:13})})}),r.jsx(Ye,{content:f("base.sessions_act_ask",{name:t}),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_ask",{name:t}),onClick:()=>k(y),children:r.jsx(un,{size:13})})}),r.jsx(Ye,{content:f("base.sessions_act_folder"),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_folder"),onClick:()=>N(y),children:r.jsx(Rf,{size:13})})}),r.jsx(Ye,{content:f("base.sessions_act_path"),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_path"),onClick:()=>j(y),children:r.jsx(Ec,{size:13})})})]})]},`${y.engine}-${y.id}-${C}`))})})]})}function o6(){const e=Wn(),[t,s]=x.useState("open"),o=l_({key:`/tasks?state=${t}`,fetchPage:(l,c)=>Nr.globalPage({state:t,limit:l,offset:c}),resetKey:t});return r.jsxs(Ke,{fullHeight:!0,title:f("project.global_tasks.title"),description:f("project.global_tasks.subtitle"),action:r.jsx("div",{className:"flex gap-1",children:["open","done","dropped","all"].map(l=>r.jsx(ce,{size:"sm",variant:t===l?"primary":"ghost",onClick:()=>s(l),children:l},l))}),children:[o.isLoading&&r.jsx(ot,{}),!o.isLoading&&o.total===0&&r.jsx(xt,{children:f("project.global_tasks.empty")}),r.jsx(i_,{paged:o,fullHeight:!0,children:r.jsx("ul",{className:"space-y-2 text-sm",children:o.items.map(l=>r.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsx("button",{type:"button",onClick:()=>e(`/p/${l.project_id}/tasks`),title:f("project.global_tasks.go_project"),children:r.jsx(Fe,{tone:"info",children:(l.project_name||"").split("/").pop()||l.project_id})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"font-medium",children:l.title}),r.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[r.jsx("span",{children:l.state}),l.agent&&r.jsxs(Fe,{tone:"muted",children:["@",l.agent]}),l.tags?.map(c=>r.jsxs("span",{children:["#",c]},c)),l.due&&r.jsxs("span",{children:[f("project.global_tasks.due")," ",l.due]})]})]})]},`${l.project_id}-${l.id}`))})})]})}const uN=x.createContext(void 0);function c_(){const e=x.useContext(uN);if(e===void 0)throw new Error(nn(64));return e}let l6=(function(e){return e.activationDirection="data-activation-direction",e.orientation="data-orientation",e})({});const up={tabActivationDirection:e=>({[l6.activationDirection]:e})},i6=x.forwardRef(function(t,s){const{className:o,defaultValue:l=0,onValueChange:c,orientation:u="horizontal",render:p,value:m,style:g,...h}=t,b=t.defaultValue!==void 0,v=x.useRef([]),[k,N]=x.useState(()=>new Map),[j,y]=Vl({controlled:m,default:l,name:"Tabs",state:"value"}),C=m!==void 0,[S,E]=x.useState(()=>new Map),R=x.useRef(void 0),A=x.useCallback(me=>{if(me===void 0)return null;for(const[Ae,ie]of S.entries())if(ie!=null&&me===(ie.value??ie.index))return Ae;return null},[S]),[T,M]=x.useState(()=>({previousValue:j,tabActivationDirection:"none"})),{previousValue:z,tabActivationDirection:B}=T;let L=B,U=!1;z!==j&&(L=ew(z,j,u,S),U=z!=null&&j!=null&&A(j)==null);const D=U?z:j,I=z!==D||B!==L;De(()=>{I&&M({previousValue:D,tabActivationDirection:L})},[D,I,L]);const V=Ue((me,Ae)=>{const ie=ew(j,me,u,S);Ae.activationDirection=ie,c?.(me,Ae),!Ae.isCanceled&&y(me)}),$=Ue((me,Ae)=>{c?.(me,nt(Ae,void 0,void 0,{activationDirection:"none"}))}),q=Ue((me,Ae)=>{N(ie=>{if(ie.get(me)===Ae)return ie;const pe=new Map(ie);return pe.set(me,Ae),pe})}),Y=Ue((me,Ae)=>{N(ie=>{if(!ie.has(me)||ie.get(me)!==Ae)return ie;const pe=new Map(ie);return pe.delete(me),pe})}),K=x.useCallback(me=>k.get(me),[k]),F=x.useCallback(me=>{for(const Ae of S.values())if(me===Ae?.value)return Ae?.id},[S]),X=x.useMemo(()=>({getTabElementBySelectedValue:A,getTabIdByPanelValue:F,getTabPanelIdByValue:K,onValueChange:V,orientation:u,registerMountedTabPanel:q,setTabMap:E,unregisterMountedTabPanel:Y,tabActivationDirection:L,value:j}),[A,F,K,V,u,q,E,Y,L,j]),P=x.useMemo(()=>{for(const me of S.values())if(me!=null&&me.value===j)return me},[S,j]),G=x.useMemo(()=>{for(const me of S.values())if(me!=null&&!me.disabled)return me.value},[S]),Z=x.useRef(!b),ee=x.useRef(l),de=x.useRef(b),fe=x.useRef(!1);De(()=>{if(C)return;function me(Se,je){y(Se),M(Be=>Be.previousValue===Se&&Be.tabActivationDirection==="none"?Be:{previousValue:Se,tabActivationDirection:"none"}),$(Se,je),Z.current=!1}if(S.size===0){fe.current&&j!==null&&!R.current?.isConnected&&me(null,q1);return}fe.current=!0,R.current=S.keys().next().value;const Ae=P?.disabled,ie=P==null&&j!==null;if(!Ae&&j===ee.current&&(de.current=!1),de.current&&Ae&&j===ee.current)return;const pe=Z.current;if(Ae||ie){const Se=G??null;if(j===Se){Z.current=!1;return}let je=q1;pe?je=$1:Ae&&(je=vS),me(Se,je);return}pe&&P!=null&&($(j,$1),Z.current=!1)},[G,C,$,P,y,S,j]);const oe=Nt("div",t,{state:{orientation:u,tabActivationDirection:L},ref:s,props:h,stateAttributesMapping:up});return r.jsx(uN.Provider,{value:X,children:r.jsx(ap,{elementsRef:v,children:oe})})});function ew(e,t,s,o){if(e==null||t==null)return"none";let l=null,c=null;for(const[m,g]of o.entries()){if(g==null)continue;const h=g.value??g.index;if(e===h&&(l=m),t===h&&(c=m),l!=null&&c!=null)break}if(l==null||c==null)return l!==c&&(typeof e=="number"||typeof e=="string")&&typeof e==typeof t?s==="horizontal"?t>e?"right":"left":t>e?"down":"up":"none";const u=l.getBoundingClientRect(),p=c.getBoundingClientRect();if(s==="horizontal"){if(p.left<u.left)return"left";if(p.left>u.left)return"right"}else{if(p.top<u.top)return"up";if(p.top>u.top)return"down"}return"none"}const dN="data-composite-item-active",fN=x.createContext(void 0);function c6(){const e=x.useContext(fN);if(e===void 0)throw new Error(nn(65));return e}const u6=x.forwardRef(function(t,s){const{className:o,disabled:l=!1,render:c,value:u,id:p,nativeButton:m=!0,style:g,...h}=t,{value:b,getTabPanelIdByValue:v,orientation:k,tabActivationDirection:N}=c_(),{activateOnFocus:j,highlightedTabIndex:y,onTabActivation:C,registerTabResizeObserverElement:S,setHighlightedTabIndex:E,tabsListElement:R}=c6(),A=Ks(p),T=x.useMemo(()=>({disabled:l,id:A,value:u}),[l,A,u]),{compositeProps:M,compositeRef:z,index:B}=sC({metadata:T}),L=u===b,U=x.useRef(!1),D=x.useRef(null);De(()=>{const Z=D.current;if(Z)return S(Z)},[S]),De(()=>{if(U.current){U.current=!1;return}if(!(L&&B>-1&&y!==B))return;const Z=R;if(Z!=null){const ee=qn(mt(Z));if(ee&&Qe(Z,ee))return}l||E(B)},[L,B,y,E,l,R]);const{getButtonProps:I,buttonRef:V}=Hr({disabled:l,native:m,focusableWhenDisabled:!0}),$=v(u),q=x.useRef(!1),Y=x.useRef(!1);function K(Z){L||l||C(u,nt(fa,Z.nativeEvent,void 0,{activationDirection:"none"}))}function F(Z){L||(B>-1&&!l&&E(B),!l&&j&&(!q.current||q.current&&Y.current)&&C(u,nt(fa,Z.nativeEvent,void 0,{activationDirection:"none"})))}function X(Z){if(L||l)return;q.current=!0;function ee(){q.current=!1,Y.current=!1}(!Z.button||Z.button===0)&&(Y.current=!0,mt(Z.currentTarget).addEventListener("pointerup",ee,{once:!0}))}return Nt("button",t,{state:{disabled:l,active:L,orientation:k,tabActivationDirection:N},ref:[s,V,z,D],props:[M,{role:"tab","aria-controls":$,"aria-selected":L,id:A,onClick:K,onFocus:F,onPointerDown:X,[dN]:L?"":void 0,onKeyDownCapture(){U.current=!0}},h,I],stateAttributesMapping:up})});let d6=(function(e){return e.index="data-index",e.activationDirection="data-activation-direction",e.orientation="data-orientation",e.hidden="data-hidden",e[e.startingStyle=yo.startingStyle]="startingStyle",e[e.endingStyle=yo.endingStyle]="endingStyle",e})({});const f6={...up,...Ja},p6=x.forwardRef(function(t,s){const{className:o,value:l,render:c,keepMounted:u=!1,style:p,...m}=t,{value:g,getTabIdByPanelValue:h,orientation:b,tabActivationDirection:v,registerMountedTabPanel:k,unregisterMountedTabPanel:N}=c_(),j=Ks(),y=x.useMemo(()=>({id:j,value:l}),[j,l]),{ref:C,index:S}=Gc({metadata:y}),E=l===g,{mounted:R,transitionStatus:A,setMounted:T}=ti(E),M=!R,z=h(l),B={hidden:M,orientation:b,tabActivationDirection:v,transitionStatus:A},L=x.useRef(null),U=Nt("div",t,{state:B,ref:[s,C,L],props:[{"aria-labelledby":z,hidden:M,id:j,role:"tabpanel",tabIndex:E?0:-1,inert:Jf(!E),[d6.index]:S},m],stateAttributesMapping:f6});return ha({open:E,ref:L,onComplete(){E||T(!1)}}),De(()=>{if(!(M&&!u)&&j!=null)return k(l,j),()=>{N(l,j)}},[M,u,l,j,k,N]),u||R?U:null}),m6=[];function g6(e){const{loopFocus:t=!0,orientation:s="both",grid:o,onLoop:l,direction:c,highlightedIndex:u,onHighlightedIndexChange:p,rootRef:m,enableHomeAndEndKeys:g=!1,stopEventPropagation:h=!1,disabledIndices:b,modifierKeys:v=m6}=e,[k,N]=x.useState(0),j=o!=null,y=x.useRef(null),C=Xa(y,m),S=x.useRef([]),E=x.useRef(!1),R=u??k,A=Ue((L,U=!1)=>{if((p??N)(L),U){const D=S.current[L];Nj(y.current,D,c,s)}}),T=Ue(L=>{if(L.size===0||E.current)return;E.current=!0;const U=Array.from(L.keys()),D=U.find(V=>V?.hasAttribute(dN))??null,I=D?U.indexOf(D):-1;if(I!==-1)A(I);else if(tf(U,R,b)){const V=qa(U,{disabledIndices:b});vc(U,V)||A(V)}Nj(y.current,D,c,s)});De(()=>{if(b==null||u!=null||!E.current)return;const L=S.current;if(tf(L,R,b)){const U=qa(L,{disabledIndices:b});vc(L,U)||A(U)}},[b,u,R,S,A]);const M=Ue((L,U,D)=>l?l(L,U,D,S):D),z=Ue(L=>{const U=g?sp:K2;if(!U.has(L.key)||h6(L,v)||!y.current)return;const I=c==="rtl",V=I?uf:df,$={horizontal:V,vertical:wc,both:V}[s],q=I?df:uf,Y={horizontal:q,vertical:jc,both:q}[s],K=Un(L.nativeEvent);if(K!=null&&Cj(K)&&!rC(K)){const de=K.selectionStart,fe=K.selectionEnd,ae=K.value??"";if(de==null||L.shiftKey||de!==fe||L.key!==Y&&de<ae.length||L.key!==$&&de>0)return}let F=R;const X=Bd(S,b),P=tx(S,b);o!=null&&(F=o({disabledIndices:b,elementsRef:S,event:L,highlightedIndex:R,loopFocus:t,maxIndex:P,minIndex:X,onLoop:M,orientation:s,rtl:I}));const G={horizontal:[V],vertical:[wc],both:[V,wc]}[s],Z={horizontal:[q],vertical:[jc],both:[q,jc]}[s],ee=j?U:{horizontal:g?pz:G2,vertical:g?mz:Y2,both:U}[s];g&&(L.key===tp?F=X:L.key===np&&(F=P)),F===R&&(G.includes(L.key)||Z.includes(L.key))&&(t&&F===P&&G.includes(L.key)?(F=X,l&&(F=l(L,R,F,S))):t&&F===X&&Z.includes(L.key)?(F=P,l&&(F=l(L,R,F,S))):F=qa(S.current,{startingIndex:F,decrement:Z.includes(L.key),disabledIndices:b})),F!==R&&!vc(S.current,F)&&(h&&L.stopPropagation(),ee.has(L.key)&&L.preventDefault(),A(F,!0),queueMicrotask(()=>{S.current[F]?.focus()}))});return{props:{ref:C,onFocus(L){const U=y.current,D=Un(L.nativeEvent);!U||D==null||!Cj(D)||D.setSelectionRange(0,D.value.length??0)},onKeyDown:z},highlightedIndex:R,onHighlightedIndexChange:A,elementsRef:S,disabledIndices:b,onMapChange:T,relayKeyboardEvent:z}}function h6(e,t){for(const s of _z.values())if(!t.includes(s)&&e.getModifierState(s))return!0;return!1}function x6(e){const{render:t,className:s,style:o,refs:l=Ka,props:c=Ka,state:u=qt,stateAttributesMapping:p,highlightedIndex:m,onHighlightedIndexChange:g,orientation:h,grid:b,loopFocus:v,onLoop:k,enableHomeAndEndKeys:N,onMapChange:j,stopEventPropagation:y=!0,rootRef:C,disabledIndices:S,modifierKeys:E,highlightItemOnHover:R=!1,tag:A="div",...T}=e,M=Wf(),{props:z,highlightedIndex:B,onHighlightedIndexChange:L,elementsRef:U,onMapChange:D,relayKeyboardEvent:I}=g6({grid:b,loopFocus:v,onLoop:k,orientation:h,highlightedIndex:m,onHighlightedIndexChange:g,rootRef:C,stopEventPropagation:y,enableHomeAndEndKeys:N,direction:M,disabledIndices:S,modifierKeys:E}),V=Nt(A,e,{state:u,ref:l,props:[z,...c,T],stateAttributesMapping:p}),$=x.useMemo(()=>({highlightedIndex:B,onHighlightedIndexChange:L,highlightItemOnHover:R,relayKeyboardEvent:I}),[B,L,R,I]);return r.jsx(B2.Provider,{value:$,children:r.jsx(ap,{elementsRef:U,onMapChange:q=>{j?.(q),D(q)},children:V})})}const b6=x.forwardRef(function(t,s){const{activateOnFocus:o=!1,className:l,loopFocus:c=!0,render:u,style:p,...m}=t,{onValueChange:g,orientation:h,value:b,setTabMap:v,tabActivationDirection:k}=c_(),[N,j]=x.useState(0),[y,C]=x.useState(null),S=x.useRef(new Set),E=x.useRef(new Set),R=x.useRef(null);De(()=>{if(typeof ResizeObserver>"u")return;const U=new ResizeObserver(()=>{S.current.forEach(D=>{D()})});return R.current=U,y&&U.observe(y),E.current.forEach(D=>{U.observe(D)}),()=>{U.disconnect(),R.current=null}},[y]);const A=Ue(U=>(S.current.add(U),()=>{S.current.delete(U)})),T=Ue(U=>(E.current.add(U),R.current?.observe(U),()=>{E.current.delete(U),R.current?.unobserve(U)})),M=Ue((U,D)=>{U!==b&&g(U,D)}),z={orientation:h,tabActivationDirection:k},B={"aria-orientation":h==="vertical"?"vertical":void 0,role:"tablist"},L=x.useMemo(()=>({activateOnFocus:o,highlightedTabIndex:N,registerIndicatorUpdateListener:A,registerTabResizeObserverElement:T,onTabActivation:M,setHighlightedTabIndex:j,tabsListElement:y}),[o,N,A,T,M,j,y]);return r.jsx(fN.Provider,{value:L,children:r.jsx(x6,{render:u,className:l,style:p,state:z,refs:[s,C],props:[B,m],stateAttributesMapping:up,highlightedIndex:N,enableHomeAndEndKeys:!0,loopFocus:c,orientation:h,onHighlightedIndexChange:j,onMapChange:v,disabledIndices:Ka})})});function dp({className:e,...t}){return r.jsx(i6,{"data-slot":"tabs",className:St("flex flex-col gap-4",e),...t})}const _6=Wb("inline-flex h-9 w-fit items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground data-[variant=line]:h-8 data-[variant=line]:gap-1 data-[variant=line]:rounded-none data-[variant=line]:bg-transparent data-[variant=line]:p-0",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function fp({className:e,variant:t="default",...s}){return r.jsx(b6,{"data-slot":"tabs-list","data-variant":t,className:St(_6({variant:t}),e),...s})}function ra({className:e,...t}){return r.jsx(u6,{"data-slot":"tabs-trigger",className:St("inline-flex h-7 items-center justify-center gap-1.5 rounded-md border border-transparent px-3 py-1 text-sm font-medium whitespace-nowrap text-muted-fg transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-active:bg-background data-active:text-foreground data-active:shadow-sm dark:data-active:border-input dark:data-active:bg-input/30 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function Ds({className:e,...t}){return r.jsx(p6,{"data-slot":"tabs-content",className:St("text-sm outline-none",e),...t})}function tw(e,t){let s=e;for(const o of t.split(".")){if(!s||typeof s!="object"||Array.isArray(s))return;s=s[o]}return s}function u_(e,t=""){const s={};for(const[o,l]of Object.entries(e)){const c=t?`${t}.${o}`:o;l&&typeof l=="object"&&!Array.isArray(l)?Object.assign(s,u_(l,c)):s[c]=l}return s}function v6(e){const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON debe ser objeto.");return t}function vx({sections:e,source:t,placeholderSource:s,jsonTitle:o,jsonDescription:l,saveLabel:c=f("common.save"),onSaveFields:u,onSaveJson:p,busy:m}){const g=e[0]?.key||"json",[h,b]=x.useState({}),[v,k]=x.useState(""),[N,j]=x.useState("");x.useEffect(()=>{const E={};for(const R of e.flatMap(A=>A.fields))E[R.path]=tw(t,R.path)??"";b(E),k(JSON.stringify(t||{},null,2)),j("")},[t,e]);const y=x.useMemo(()=>new Set(e.flatMap(E=>E.fields.map(R=>R.path))),[e]),C=async()=>{const E={},R=[];for(const A of e.flatMap(T=>T.fields)){const T=h[A.path];if(!is(T)){if(T===""||T===void 0||T===null){R.push(A.path);continue}if(A.kind==="number"){const M=Number(T);Number.isFinite(M)&&(E[A.path]=M)}else E[A.path]=T}}await u(E,R.filter(A=>y.has(A)))},S=async()=>{j("");try{await p(v6(v))}catch(E){j(E.message)}};return r.jsxs(dp,{defaultValue:g,className:"space-y-4",children:[r.jsxs(fp,{className:"flex flex-wrap",children:[e.map(E=>r.jsx(ra,{value:E.key,children:E.label},E.key)),r.jsx(ra,{value:"json",children:"JSON"})]}),e.map(E=>r.jsx(Ds,{value:E.key,children:r.jsxs("div",{className:"space-y-4",children:[E.description&&r.jsx("p",{className:"text-sm text-muted-fg",children:E.description}),r.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:E.fields.map(R=>r.jsx(y6,{field:R,value:h[R.path],inherited:tw(s,R.path),onChange:A=>b(T=>({...T,[R.path]:A}))},R.path))}),r.jsx(ce,{variant:"primary",loading:m,onClick:C,children:c})]})},E.key)),r.jsx(Ds,{value:"json",children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium",children:o}),l&&r.jsx("p",{className:"text-xs text-muted-fg",children:l})]}),r.jsx(Mn,{rows:18,className:"font-mono text-xs",value:v,onChange:E=>k(E.target.value)}),N&&r.jsx("p",{className:"text-xs text-destructive",children:N}),r.jsx(ce,{variant:"primary",loading:m,onClick:S,children:f("settings_ui.save_json")})]})})]})}function y6({field:e,value:t,inherited:s,onChange:o}){const l=e.placeholder||nw(s)||(is(t)?Ar(t):""),c=e.hint||(s!==void 0?`Heredado: ${nw(s)}`:void 0);return e.kind==="boolean"?r.jsx("div",{className:"flex items-end pb-1",children:r.jsx(Ft,{checked:t===!0,onChange:o,label:e.label})}):r.jsx(le,{label:e.label,hint:c,children:e.kind==="select"?r.jsx(bt,{value:String(t||""),onChange:o,placeholder:l||"(sin override)",options:[{value:"",label:l||"(sin override)"},...(e.options||[]).map(u=>({value:String(u.value),label:u.label}))]}):e.kind==="textarea"?r.jsx(Mn,{rows:4,value:String(t||""),placeholder:l,onChange:u=>o(u.target.value)}):r.jsx(Ne,{type:e.kind==="password"?"password":e.kind==="number"?"number":"text",value:String(is(t)?"":t||""),placeholder:e.kind==="password"&&is(t)?Ar(t):e.kind==="password"&&is(s)?Ar(s):l,onChange:u=>o(u.target.value)})})}function nw(e){return e==null||e===""?"":is(e)?Ar(e):Array.isArray(e)?e.join(", "):typeof e=="object"?JSON.stringify(e):String(e)}function j6(){return[{key:"routing",label:f("settings_ui.cfg_overrides_label"),description:f("settings_ui.cfg_overrides_desc"),fields:[{path:"route_to_agent",label:f("settings_ui.cfg_route_to_agent"),placeholder:"master"},{path:"super_agent.model",label:f("settings_ui.cfg_super_agent_model")},{path:"super_agent.permission_mode",label:f("settings_ui.cfg_permission_mode"),kind:"select",options:Yx.map(e=>({value:e,label:e}))},{path:"super_agent.system",label:f("settings_ui.cfg_extra_prompt"),kind:"textarea"}]},{key:"telegram",label:f("settings_ui.cfg_telegram_label"),fields:[{path:"telegram.route_to_agent",label:f("settings_ui.cfg_route_to_agent")},{path:"telegram.chat_id",label:f("settings_ui.cfg_chat_id")},{path:"telegram.bot_token",label:f("settings_ui.cfg_bot_token"),kind:"password"},{path:"telegram.respond_with_engine",label:f("settings_ui.cfg_respond_with_engine"),kind:"boolean"}]},{key:"engines",label:f("settings_ui.cfg_engines_label"),fields:[{path:"engines.ollama.base_url",label:f("settings_ui.cfg_ollama_url")},{path:"engines.anthropic.api_key",label:f("settings_ui.cfg_anthropic_key"),kind:"password"},{path:"engines.openai.api_key",label:f("settings_ui.cfg_openai_key"),kind:"password"},{path:"engines.groq.api_key",label:f("settings_ui.cfg_groq_key"),kind:"password"},{path:"engines.openrouter.api_key",label:f("settings_ui.cfg_openrouter_key"),kind:"password"},{path:"engines.gemini.api_key",label:f("settings_ui.cfg_gemini_key"),kind:"password"}]}]}function w6(){return[{key:"identity",label:f("settings_ui.cfg_project_label"),description:f("settings_ui.cfg_project_desc"),fields:[{path:"name",label:f("settings_ui.cfg_name")},{path:"version",label:f("settings_ui.cfg_version")},{path:"apf",label:f("settings_ui.cfg_apc_spec")},{path:"apx",label:f("settings_ui.cfg_apx_install")},{path:"apx_id",label:f("settings_ui.cfg_apx_storage_id")}]}]}function k6({pid:e}){const t=lt(),s=Wn(),{project:o,mutate:l}=Xb(e),c=et(`/projects/${e}/config`,()=>ls.config.show(e)),u=String(e)==="0";if(c.isLoading)return r.jsx(ot,{});if(!c.data)return r.jsx(xt,{children:f("project.config.no_data")});const p=async g=>{await ls.apcProject.put(e,g),t.success(f("project.config.save_project")),c.mutate()},m=async g=>{await ls.config.put(e,g),t.success(f("project.config.save_override")),c.mutate()};return r.jsxs("div",{className:"space-y-6",children:[r.jsx(Ke,{title:f("project.config.section_title"),description:f("project.config.section_desc"),children:r.jsxs(dp,{defaultValue:"override",className:"space-y-4",children:[r.jsxs(fp,{children:[r.jsx(ra,{value:"override",children:"Override"}),r.jsx(ra,{value:"project",children:"APC project"}),r.jsx(ra,{value:"effective",children:"Effective"})]}),r.jsx(Ds,{value:"override",children:r.jsx(vx,{sections:j6(),source:c.data.project_only,placeholderSource:c.data.effective,jsonTitle:c.data.project_config_path,jsonDescription:".apc/config.json. Overrides del proyecto.",onSaveFields:async(g,h)=>{await ls.config.set(e,g),h.length&&await ls.config.unset(e,h),t.success(f("project.config.save_fields_success")),c.mutate()},onSaveJson:m})}),r.jsx(Ds,{value:"project",children:r.jsx(vx,{sections:w6(),source:c.data.apc_project||{},jsonTitle:c.data.project_json_path,jsonDescription:".apc/project.json. Metadata APC portable.",onSaveFields:async(g,h)=>{await ls.apcProject.set(e,C6(g),h),t.success(f("project.config.save_meta_success")),c.mutate()},onSaveJson:p})}),r.jsx(Ds,{value:"effective",children:r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-muted-fg",children:f("project.config.effective_read")}),r.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-muted/40 p-3 text-xs",children:JSON.stringify(c.data.effective,null,2)})]})})]})}),!u&&o?r.jsx(S6,{pid:e,label:o.name||o.path,onRebuilt:()=>c.mutate(),onUnregistered:()=>{l(),s("/")}}):null]})}function S6({pid:e,label:t,onRebuilt:s,onUnregistered:o}){const l=lt(),[c,u]=x.useState(null),[p,m]=x.useState(null),g=async()=>{u("rebuild");try{await ls.rebuild(e),l.success(f("project.rebuild_done")),s()}catch(b){l.error(b.message)}finally{u(null),m(null)}},h=async()=>{u("unregister");try{await ls.remove(e),l.success(f("project.unregistered")),o()}catch(b){l.error(b.message)}finally{u(null),m(null)}};return r.jsxs(r.Fragment,{children:[r.jsx(Ke,{title:f("project.danger.title"),description:f("project.danger.subtitle"),children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border bg-muted/30 px-3 py-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-sm font-medium",children:f("project.rebuild")}),r.jsx("div",{className:"text-xs text-muted-fg",children:f("project.danger.rebuild_desc")})]}),r.jsxs(ce,{size:"sm",variant:"secondary",onClick:()=>m("rebuild"),children:[r.jsx(ua,{size:13})," ",f("project.rebuild")]})]}),r.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-red-500/40 bg-red-500/5 px-3 py-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-sm font-medium",children:f("admin.unregister")}),r.jsx("div",{className:"text-xs text-muted-fg",children:f("project.danger.unregister_desc")})]}),r.jsxs(ce,{size:"sm",variant:"destructive",onClick:()=>m("unregister"),children:[r.jsx(Zn,{size:13})," ",f("admin.unregister")]})]})]})}),r.jsx(On,{open:p==="rebuild",onClose:()=>c?null:m(null),title:f("project.danger.rebuild_confirm_title"),description:f("project.danger.rebuild_confirm_desc",{label:t}),size:"sm",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:g,loading:c==="rebuild",children:f("project.rebuild")})]}),children:r.jsx("p",{className:"text-sm text-muted-fg",children:f("project.danger.rebuild_long")})}),r.jsx(On,{open:p==="unregister",onClose:()=>c?null:m(null),title:f("project.danger.unregister_confirm_title"),description:f("project.unregister_confirm",{label:t}),size:"sm",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:f("common.cancel")}),r.jsx(ce,{variant:"destructive",onClick:h,loading:c==="unregister",children:f("admin.unregister")})]}),children:r.jsx("p",{className:"text-sm text-muted-fg",children:f("project.danger.unregister_long")})})]})}function C6(e){const t={};for(const[s,o]of Object.entries(u_(e)))is(o)||(t[s]=o);return t}const N6=["","es","en","pt","fr","it","de"],sw=e=>e.split(",").map(t=>t.trim()).filter(Boolean);function pN(e){return e.is_master?{gradient:"from-violet-600 to-indigo-600",Icon:Ga}:{gradient:"from-slate-600 to-gray-600",Icon:un}}function E6(e){const t=e.filter(u=>u.is_master),s=t.length===1?t[0]:null,o=u=>u.parent?u.parent:s&&!u.is_master&&u.slug!==s.slug?s.slug:null,l=new Map,c=[];for(const u of e){const p=o(u);p&&e.some(m=>m.slug===p)?(l.has(p)||l.set(p,[]),l.get(p).push(u)):c.push(u)}return{roots:c,childrenByParent:l}}function R6({pid:e}){const t=Wn();lt();const s=et(`/projects/${e}/agents`,()=>rn.list(e)),[o,l]=x.useState("hierarchy"),[c,u]=x.useState(!1),[p,m]=x.useState(!1),g=s.data||[],h=N=>t(`/p/${e}/agents/${N}`),b=N=>t(N?`/p/${e}/chat?agent=${N}`:`/p/${e}/chat`),{roots:v,childrenByParent:k}=x.useMemo(()=>E6(g),[g]);return r.jsxs(Ke,{title:f("project.agents.title"),description:f("project.agents.subtitle_full"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex rounded-lg border border-border p-0.5",children:[r.jsxs("button",{onClick:()=>l("hierarchy"),className:Te("flex items-center gap-1 rounded-md px-2 py-1 text-xs",o==="hierarchy"?"bg-accent text-accent-fg":"text-muted-fg"),children:[r.jsx(Hx,{size:13})," ",f("project.agents.hierarchy")]}),r.jsxs("button",{onClick:()=>l("list"),className:Te("flex items-center gap-1 rounded-md px-2 py-1 text-xs",o==="list"?"bg-accent text-accent-fg":"text-muted-fg"),children:[r.jsx(HM,{size:13})," ",f("project.agents.list_view")]})]}),r.jsxs(ce,{size:"sm",variant:"ghost",onClick:()=>m(!0),children:[r.jsx(ZM,{size:13})," ",f("project.agents.import")]}),r.jsxs(ce,{size:"sm",variant:"secondary",onClick:()=>b(),children:[r.jsx(Gs,{size:13})," ",f("project.agents.chat")]}),r.jsxs(ce,{size:"sm",variant:"primary","data-testid":"agent-new",onClick:()=>u(!0),children:[r.jsx(tn,{size:14})," ",f("project.agents.new")]})]}),children:[s.isLoading&&r.jsx(ot,{}),!s.isLoading&&g.length===0&&r.jsx(xt,{children:f("project.agents.empty_text")}),!s.isLoading&&g.length>0&&(o==="hierarchy"?r.jsx(A6,{roots:v,childrenByParent:k,onOpen:h,onChat:b}):r.jsx(M6,{agents:g,onOpen:h,onChat:b})),r.jsx(O6,{open:c,pid:e,agents:g,onClose:()=>u(!1),onCreated:()=>{u(!1),s.mutate()}}),r.jsx(T6,{open:p,pid:e,existing:g.map(N=>N.slug),onClose:()=>m(!1),onImported:()=>s.mutate()})]})}function T6({open:e,onClose:t,onImported:s,pid:o,existing:l}){const c=lt(),u=et(e?"/agents/vault":null,()=>rn.vault()),[p,m]=x.useState(""),g=u.data||[],h=async b=>{m(b);try{await rn.import(o,b),c.success(f("project.agents.import_success",{slug:b})),s()}catch(v){c.error(v.message)}finally{m("")}};return r.jsxs(On,{open:e,onClose:t,title:f("project.agents.import_title"),description:f("project.agents.import_desc"),size:"lg",footer:r.jsx(ce,{variant:"ghost",onClick:t,children:f("common.close")}),children:[u.isLoading&&r.jsx(ot,{}),!u.isLoading&&g.length===0&&r.jsx(xt,{children:f("project.agents.import_empty")}),r.jsx("ul",{className:"space-y-2",children:g.map(b=>{const v=l.includes(b.slug);return r.jsxs("li",{className:"flex items-center gap-3 rounded-lg border border-border bg-muted/30 p-3",children:[r.jsx(un,{size:16,className:"shrink-0 text-muted-fg"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium",children:b.slug}),b.is_master&&r.jsxs(Fe,{tone:"success",children:[r.jsx(Ga,{size:9})," ",f("project.agents.orchestrator")]}),b.model&&r.jsx(Fe,{tone:"info",children:b.model})]}),b.description&&r.jsx("p",{className:"truncate text-xs text-muted-fg",children:b.description})]}),r.jsx(ce,{size:"sm",variant:"primary",disabled:v||p===b.slug,loading:p===b.slug,onClick:()=>h(b.slug),children:f(v?"project.agents.import_already":"project.agents.import_btn")})]},b.slug)})})]})}function A6({roots:e,childrenByParent:t,onOpen:s,onChat:o}){return r.jsx("div",{className:"space-y-8",children:e.map(l=>{const c=t.get(l.slug)||[];return r.jsxs("div",{className:"flex flex-col items-center",children:[r.jsx(rh,{agent:l,onOpen:s,onChat:o,wide:!0}),c.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"h-5 w-px bg-border"}),r.jsx("div",{className:"flex flex-wrap items-start justify-center gap-4 border-t border-border pt-5",children:c.map(u=>r.jsxs("div",{className:"flex flex-col items-center",children:[r.jsx(rh,{agent:u,onOpen:s,onChat:o}),(t.get(u.slug)||[]).length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"h-4 w-px bg-border"}),r.jsx("div",{className:"flex flex-wrap justify-center gap-3 border-t border-border pt-4",children:(t.get(u.slug)||[]).map(p=>r.jsx(rh,{agent:p,onOpen:s,onChat:o,compact:!0},p.slug))})]})]},u.slug))})]})]},l.slug)})})}function rh({agent:e,onOpen:t,onChat:s,wide:o,compact:l}){const{gradient:c,Icon:u}=pN(e);return r.jsxs("div",{"data-testid":`agent-card-${e.slug}`,className:Te("cursor-pointer rounded-xl border border-border bg-card p-3 transition-colors hover:border-muted-fg/50",o?"w-64":l?"w-44":"w-52"),onClick:()=>t(e.slug),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:Te("flex size-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br",c),children:r.jsx(u,{className:"size-4 text-white"})}),r.jsx("span",{className:"truncate text-sm font-semibold",children:e.slug})]}),r.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.is_master&&r.jsxs(Fe,{tone:"success",children:[r.jsx(Ga,{size:9})," ",f("project.agents.orchestrator")]}),e.role&&r.jsx(Fe,{children:e.role}),e.model&&!l&&r.jsx(Fe,{tone:"info",children:e.model})]}),r.jsxs("div",{className:"mt-2 flex items-center gap-3 border-t border-border pt-2 text-xs text-muted-fg",onClick:p=>p.stopPropagation(),children:[r.jsxs("button",{onClick:()=>t(e.slug),className:"flex items-center gap-1 hover:text-foreground",children:[r.jsx(Ef,{size:12})," ",f("project.agents.view")]}),r.jsxs("button",{onClick:()=>s(e.slug),className:"flex items-center gap-1 text-emerald-500 hover:text-emerald-400",children:[r.jsx(Gs,{size:12})," ",f("project.agents.chat")]})]})]})}function M6({agents:e,onOpen:t,onChat:s}){const o=[...e].sort((l,c)=>+!!c.is_master-+!!l.is_master||l.slug.localeCompare(c.slug));return r.jsx("div",{className:"space-y-2",children:o.map(l=>{const{gradient:c,Icon:u}=pN(l);return r.jsxs("div",{"data-testid":`agent-card-${l.slug}`,className:"flex cursor-pointer items-center gap-4 rounded-xl border border-border bg-muted/30 p-3 hover:border-muted-fg/50",onClick:()=>t(l.slug),children:[r.jsx("div",{className:Te("flex size-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br",c),children:r.jsx(u,{className:"size-4 text-white"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx("span",{className:"text-sm font-semibold",children:l.slug}),l.is_master&&r.jsxs(Fe,{tone:"success",children:[r.jsx(Ga,{size:10})," ",f("project.agents.orchestrator")]}),l.role&&r.jsx(Fe,{children:l.role}),l.model&&r.jsx(Fe,{tone:"info",children:l.model}),l.parent&&r.jsxs("span",{className:"text-[10px] text-violet-400",children:["↳ ",l.parent]})]}),l.description&&r.jsx("p",{className:"mt-1 truncate text-xs text-muted-fg",children:l.description}),r.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[l.skills?.map(p=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(ma,{size:9})," ",p]},p)),l.tools?.map(p=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(Zl,{size:9})," ",p]},p))]})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3 text-xs text-muted-fg",onClick:p=>p.stopPropagation(),children:[r.jsxs("button",{onClick:()=>t(l.slug),className:"flex items-center gap-1 hover:text-foreground",children:[r.jsx(Ef,{size:12})," ",f("project.agents.view")]}),r.jsxs("button",{onClick:()=>s(l.slug),className:"flex items-center gap-1 text-emerald-500 hover:text-emerald-400",children:[r.jsx(Gs,{size:12})," ",f("project.agents.chat")]})]})]},l.slug)})})}function O6({open:e,onClose:t,onCreated:s,pid:o,agents:l}){const c=lt(),[u,p]=x.useState(""),[m,g]=x.useState(""),[h,b]=x.useState(""),[v,k]=x.useState(""),[N,j]=x.useState(""),[y,C]=x.useState(""),[S,E]=x.useState(""),[R,A]=x.useState(!1),[T,M]=x.useState(""),[z,B]=x.useState(!1),L=()=>{p(""),g(""),b(""),k(""),j(""),C(""),E(""),A(!1),M("")},U=async()=>{if(!/^[a-z][a-z0-9_-]*$/.test(u)){c.error(f("project.agents.slug_invalid"));return}B(!0);try{await rn.create(o,{slug:u,role:m||void 0,model:h||void 0,language:v||void 0,description:N||void 0,skills:sw(y),tools:sw(S),is_master:R,parent:T||void 0}),c.success(f("project.agents.create_success",{slug:u})),s(),L()}catch(D){c.error(D?.message||f("project.agents.create_error"))}finally{B(!1)}};return r.jsx(On,{open:e,onClose:t,title:f("project.agents.new_title"),description:f("project.agents.new_desc"),size:"lg",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:z,children:f("common.cancel")}),r.jsx(ce,{variant:"primary","data-testid":"agent-create-submit",onClick:U,loading:z,children:f("common.create")})]}),children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("project.agents.slug_label"),children:r.jsx(Ne,{autoFocus:!0,"data-testid":"agent-slug",value:u,onChange:D=>p(D.target.value),placeholder:f("project.agents.slug_ph")})}),r.jsx(le,{label:f("project.agents.role_label"),children:r.jsx(Ne,{value:m,onChange:D=>g(D.target.value),placeholder:f("project.agents.role_ph")})})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("project.agents.model_label"),hint:f("project.agents.model_hint"),children:r.jsx(Ne,{value:h,onChange:D=>b(D.target.value)})}),r.jsx(le,{label:f("project.agents.lang_label"),children:r.jsx(bt,{value:v,onChange:k,options:N6.map(D=>({value:D,label:D||"—"}))})})]}),r.jsx(le,{label:f("project.agents.desc_label"),children:r.jsx(Mn,{rows:2,value:N,onChange:D=>j(D.target.value),placeholder:f("project.agents.desc_ph")})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("project.agents.skills_label"),children:r.jsx(Ne,{value:y,onChange:D=>C(D.target.value),placeholder:f("project.agents.skills_ph")})}),r.jsx(le,{label:f("project.agents.tools_label"),children:r.jsx(Ne,{value:S,onChange:D=>E(D.target.value),placeholder:f("project.agents.tools_ph")})})]}),r.jsxs("div",{className:"grid grid-cols-2 items-end gap-3",children:[r.jsx(le,{label:f("project.agents.parent_label"),hint:f("project.agents.parent_hint"),children:r.jsx(bt,{value:T,onChange:M,placeholder:f("project.agents.none_parent"),options:[{value:"",label:f("project.agents.none_parent")},...l.filter(D=>D.slug!==u).map(D=>({value:D.slug,label:D.slug}))]})}),r.jsx(Ft,{checked:R,onChange:A,label:f("project.agents.master_label")})]})]})})}function Rd(e){return e.split(`
622
+ `)}}if(p.trim())try{s(JSON.parse(p.trim()))}catch{}}const UD={get:()=>ge.get("/health")},ls={list:()=>ge.get("/projects"),register:e=>ge.post("/projects",{path:e}),remove:e=>ge.del(`/projects/${encodeURIComponent(e)}`),rebuild:e=>ge.post(`/projects/${encodeURIComponent(e)}/rebuild`),config:{show:e=>ge.get(`/projects/${e}/config`),set:(e,t)=>ge.patch(`/projects/${e}/config`,{set:t}),unset:(e,t)=>ge.patch(`/projects/${e}/config`,{unset:t}),put:(e,t)=>ge.put(`/projects/${e}/config`,t)},apcProject:{set:(e,t,s)=>ge.patch(`/projects/${e}/apc-project`,{set:t,unset:s}),put:(e,t)=>ge.put(`/projects/${e}/apc-project`,t)},memory:{get:e=>ge.get(`/projects/${e}/memory`),put:(e,t)=>ge.put(`/projects/${e}/memory`,{body:t})}},rn={list:e=>ge.get(`/projects/${e}/agents`),get:(e,t)=>ge.get(`/projects/${e}/agents/${t}`),create:(e,t)=>ge.post(`/projects/${e}/agents`,t),update:(e,t,s)=>ge.patch(`/projects/${e}/agents/${encodeURIComponent(t)}`,s),remove:(e,t)=>ge.del(`/projects/${e}/agents/${encodeURIComponent(t)}`),chat:(e,t,s)=>ge.post(`/projects/${e}/agents/${encodeURIComponent(t)}/chat`,s),memory:{get:(e,t)=>ge.get(`/projects/${e}/agents/${t}/memory`),put:(e,t,s)=>ge.put(`/projects/${e}/agents/${t}/memory`,{body:s})},vault:e=>ge.get(e?.includeRemoved?"/agents/vault?include_removed=1":"/agents/vault"),vaultCreate:(e,t={},s="")=>ge.post("/agents/vault",{slug:e,fields:t,body:s}),vaultPatch:(e,t)=>ge.patch(`/agents/vault/${encodeURIComponent(e)}`,t),vaultRemove:e=>ge.del(`/agents/vault/${encodeURIComponent(e)}`),vaultRestore:e=>ge.post(`/agents/vault/${encodeURIComponent(e)}/restore`),import:(e,t)=>ge.post(`/projects/${e}/agents/import`,{slug:t})},Kb={list:(e,t)=>ge.get(`/projects/${e}/agents/${t}/conversations`),get:(e,t,s)=>ge.get(`/projects/${e}/agents/${t}/conversations/${s}`),compact:(e,t,s)=>ge.post(s?`/projects/${e}/agents/${t}/conversations/${s}/compact`:`/projects/${e}/agents/${t}/compact`,{})},Cr={list:e=>ge.get(`/projects/${e}/routines`),get:(e,t)=>ge.get(`/projects/${e}/routines/${t}`),run:(e,t)=>ge.post(`/projects/${e}/routines/${t}/run`),enable:(e,t)=>ge.post(`/projects/${e}/routines/${t}/enable`),disable:(e,t)=>ge.post(`/projects/${e}/routines/${t}/disable`),upsert:(e,t)=>ge.post(`/projects/${e}/routines`,t),remove:(e,t)=>ge.del(`/projects/${e}/routines/${encodeURIComponent(t)}`)},Nr={list:(e,t="open")=>ge.get(`/projects/${e}/tasks?state=${t}`).then(s=>wl(s).items),global:(e="open")=>ge.get(`/tasks?state=${e}`).then(t=>wl(t).items),listPage:(e,{state:t,limit:s,offset:o})=>ge.get(`/projects/${e}/tasks?state=${t}&limit=${s}&offset=${o}`).then(l=>wl(l)),globalPage:({state:e,limit:t,offset:s})=>ge.get(`/tasks?state=${e}&limit=${t}&offset=${s}`).then(o=>wl(o)),add:(e,t)=>ge.post(`/projects/${e}/tasks`,t),done:(e,t)=>ge.post(`/projects/${e}/tasks/${t}/done`),drop:(e,t)=>ge.post(`/projects/${e}/tasks/${t}/drop`),reopen:(e,t)=>ge.post(`/projects/${e}/tasks/${t}/reopen`)},Er={list:e=>ge.get(`/projects/${e}/mcps`),check:e=>ge.get(`/projects/${e}/mcps/check`),add:(e,t,s)=>ge.post(`/projects/${e}/mcps?scope=${t}`,s),remove:(e,t,s="shared")=>ge.del(`/projects/${e}/mcps/${encodeURIComponent(t)}?scope=${s}`),test:(e,t)=>ge.post(`/projects/${e}/mcps/${encodeURIComponent(t)}/test`,{}),logs:(e,t)=>ge.get(`/projects/${e}/mcps/${encodeURIComponent(t)}/logs`)},Dc={list:(e,t={})=>ge.get(`/projects/${e}/vars${t.reveal?"?reveal=1":""}`),get:(e,t,s={})=>ge.get(`/projects/${e}/vars/${encodeURIComponent(t)}${s.reveal?"?reveal=1":""}`),upsert:(e,t)=>ge.post(`/projects/${e}/vars`,t),remove:(e,t,s="project")=>ge.del(`/projects/${e}/vars/${encodeURIComponent(t)}?scope=${s}`)},eh=e=>{const t=new URLSearchParams;for(const[o,l]of Object.entries(e))l!==void 0&&l!==""&&t.set(o,String(l));const s=t.toString();return s?`?${s}`:""},pf={global:(e={})=>ge.get(`/messages/global${eh(e)}`),project:(e,t={})=>ge.get(`/projects/${e}/messages${eh(t)}`),search:(e,t,s=50)=>ge.get(`/projects/${e}/messages/search${eh({q:t,limit:s})}`)},HD={global:e=>ge.get(`/sessions${e?`?engine=${encodeURIComponent(e)}`:""}`).then(t=>({sessions:wl(t).items})),page:({engine:e,q:t,deep:s,limit:o,offset:l})=>{const c=new URLSearchParams({limit:String(o),offset:String(l)});return e&&c.set("engine",e),t?.trim()&&c.set("q",t.trim()),s&&c.set("deep","1"),ge.get(`/sessions?${c.toString()}`).then(u=>wl(u))}},VD={list:()=>ge.get("/tools")},An={channels:{list:()=>ge.get("/telegram/channels"),upsert:e=>ge.post("/telegram/channels",e),patch:(e,t)=>ge.patch(`/telegram/channels/${e}`,t),remove:e=>ge.del(`/telegram/channels/${encodeURIComponent(e)}`)},contacts:{list:()=>ge.get("/telegram/contacts"),patch:(e,t)=>ge.patch(`/telegram/contacts/${encodeURIComponent(String(e))}`,t),remove:e=>ge.del(`/telegram/contacts/${encodeURIComponent(String(e))}`)},roles:{list:()=>ge.get("/telegram/roles"),set:(e,t)=>ge.put(`/telegram/roles/${encodeURIComponent(e)}`,{tools:t}),remove:e=>ge.del(`/telegram/roles/${encodeURIComponent(e)}`)},status:()=>ge.get("/telegram/status"),start:()=>ge.post("/telegram/start"),stop:()=>ge.post("/telegram/stop"),send:e=>ge.post("/telegram/send",e)},mf={list:()=>ge.get("/engines"),models:e=>ge.post("/engines/models",e)},$l={reload:()=>ge.post("/admin/reload"),shutdown:()=>ge.post("/admin/shutdown"),config:{get:()=>ge.get("/admin/config"),patch:e=>ge.patch("/admin/config",e)},superAgent:()=>ge.get("/admin/super-agent"),logs:(e="errors",t=200)=>ge.get(`/admin/logs?file=${e}&limit=${t}`)},Fl={list:()=>ge.get("/pair/list"),revoke:e=>ge.del(`/pair/revoke/${encodeURIComponent(e)}`),init:()=>ge.post("/pair/init",{}),status:e=>ge.get(`/pair/status/${encodeURIComponent(e)}`),confirm:e=>ge.post("/pair/confirm",e)},Pj={get:()=>ge.get("/identity"),patch:e=>ge.patch("/identity",e)},jC={send:(e,t)=>ge.post(`/projects/${e}/super-agent/chat`,t),stream:(e,t,s,o)=>yC(`/projects/${e}/super-agent/chat/stream`,t,s,o),summarize:e=>ge.post("/super-agent/summarize",e)},Ij={dirs:e=>ge.get(`/admin/fs/dirs?path=${encodeURIComponent(e)}`),pickDir:e=>ge.get(`/admin/fs/pick-dir${e?`?prompt=${encodeURIComponent(e)}`:""}`)},qD=["alloy","echo","fable","onyx","nova","shimmer"],$D=["Kore","Puck","Charon","Fenrir","Aoede"],FD=["eleven_multilingual_v2","eleven_turbo_v2_5","eleven_flash_v2_5"],GD=["tts-1","tts-1-hd"],YD=["happy","sad","excited","angry","calm","whisper","shout","laugh","cry","narrator","neutral"],KD=["tiny","base","small","medium","large-v2","large-v3","large-v3-turbo"],gf={piper:{name:"Piper",note:"Local, offline (CLI + .onnx model). No API key.",local:!0},elevenlabs:{name:"ElevenLabs",note:"Cloud, multilingual. Requires an API key."},openai:{name:"OpenAI",note:"Cloud (tts-1 / tts-1-hd) or any OpenAI-compatible endpoint (set a base URL for a local server, e.g. QVox)."},gemini:{name:"Gemini",note:"Cloud (preview). Uses your Gemini key."},mock:{name:"Mock",note:"Silent test engine. Always available as a fallback.",local:!0}};async function XD(e){const t=Yb(),s=await fetch(`/voice/tts?path=${encodeURIComponent(e)}`,{headers:t?{authorization:`Bearer ${t}`}:{}});if(!s.ok){const l=await s.text().catch(()=>"");throw new Error(`No se pudo leer el audio (${s.status}): ${l.slice(0,160)}`)}const o=await s.blob();return URL.createObjectURL(o)}const hf={providers:()=>ge.get("/tts/providers"),sttHardware:()=>ge.get("/transcribe/hardware"),sttModels:e=>ge.get(`/transcribe/models?backend=${e}`),say:e=>ge.post("/tts/say",e),turn:e=>ge.post("/voice/turn",e)},wC={manifest:()=>ge.get("/deck/manifest"),setWidget:(e,t)=>ge.patch(`/deck/widgets/${encodeURIComponent(e)}`,t),exec:e=>ge.post("/deck/exec",e)},lo=e=>`/projects/${e}/code/sessions`,Ba={sessions:{list:e=>ge.get(lo(e)).then(t=>t.sessions),get:(e,t)=>ge.get(`${lo(e)}/${t}`),create:(e,t={})=>ge.post(lo(e),t),update:(e,t,s)=>ge.patch(`${lo(e)}/${t}`,s),remove:(e,t)=>ge.del(`${lo(e)}/${t}`)},changes:(e,t)=>ge.get(`${lo(e)}/${t}/changes`),stream:(e,t,s,o,l)=>yC(`${lo(e)}/${t}/chat/stream`,s,o,l)},Ml={list:e=>ge.get(`/projects/${encodeURIComponent(e)}/artifacts`),read:(e,t)=>ge.get(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),run:(e,t,s=[])=>ge.post(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}/run`,{args:s}),remove:(e,t)=>ge.del(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`),write:(e,t,s)=>ge.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{content:s}),rename:(e,t,s)=>ge.patch(`/projects/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`,{newName:s})},fc={list:e=>ge.get(e?`/skills?project_path=${encodeURIComponent(e)}`:"/skills"),inspector:()=>ge.get("/skills/inspector"),updateInspector:e=>ge.put("/skills/inspector",e),index:(e={})=>ge.post("/skills/index",e),inspect:(e,t)=>ge.post("/skills/inspect",{prompt:e,project_path:t})};function Xc(){const{data:e,error:t,isLoading:s,mutate:o}=et("/projects",()=>ls.list(),{refreshInterval:Of.projects});return{projects:(e||[]).slice().sort((c,u)=>{const p=Number(c.id),m=Number(u.id);return p===0&&m!==0?-1:m===0&&p!==0?1:p-m}),error:t,isLoading:s,mutate:o}}function Xb(e){const{projects:t,isLoading:s,mutate:o}=Xc();return{project:t.find(c=>String(c.id)===e)??null,isLoading:s,mutate:o}}function Qb(){const{data:e,error:t,isLoading:s,mutate:o}=et("/identity",()=>Pj.get());return{identity:e||{},error:t,isLoading:s,mutate:o,save:async c=>{const u=await Pj.patch(c);return await o(u,{revalidate:!1}),u}}}function op(){const{identity:e}=Qb();return e?.agent_name?.trim()||"APX"}function QD(){return[{id:"desktop",label:f("nav.modules.desktop"),href:"/m/desktop",icon:qx},{id:"code",label:f("nav.modules.code"),href:"/m/code",icon:Ya}]}function WD(e,t,s){const[o,l]=x.useState(t);return x.useLayoutEffect(()=>{const c=e.current;if(!c||!s)return;const u=()=>{const m=c.clientHeight;if(!m)return;const g=parseFloat(getComputedStyle(c).rowGap)||12,b=(c.querySelector("[data-rail-probe]")?.offsetHeight??56)+g,k=Math.max(0,Math.floor((m+g)/b))-1;l(k>=t?t:Math.max(0,k-1))};u();const p=new ResizeObserver(u);return p.observe(c),()=>p.disconnect()},[e,t,s]),s?Math.min(o,t):t}function Bj({projects:e,label:t,sublabel:s,icon:o,tooltip:l,header:c,active:u,testId:p,onSelect:m,isActive:g}){return r.jsxs(oC,{children:[r.jsxs(lC,{"data-testid":p,title:l,"aria-label":l,className:"group flex w-full cursor-pointer flex-col items-center gap-1",children:[r.jsx("span",{className:Te("flex size-10 items-center justify-center rounded-xl text-xs font-bold transition-all","bg-muted/40 text-muted-fg hover:bg-accent hover:text-foreground",u&&"ring-2 ring-foreground ring-offset-2 ring-offset-card"),children:o??t}),s&&r.jsx("span",{className:"block max-w-[3.6rem] truncate text-[9px] leading-tight text-muted-fg group-hover:text-foreground",children:s})]}),r.jsxs(iC,{side:"right",align:"start",sideOffset:8,className:"max-h-[70vh] w-64",children:[r.jsx("div",{className:"px-1.5 py-1 text-xs font-medium text-muted-foreground",children:c}),e.map(h=>{const b=h.name||h.path.split("/").pop()||String(h.id),v=`/p/${h.id}`,{initials:k,idleClass:N}=az(b);return r.jsxs(tD,{"data-testid":`project-menu-item-${h.id}`,onClick:()=>m(v),className:Te(g(v)&&"bg-accent/60 text-foreground"),children:[r.jsx("span",{className:Te("flex size-6 shrink-0 items-center justify-center rounded-md text-[10px] font-bold",N),children:k}),r.jsx("span",{className:"truncate",children:b})]},h.id)})]})]})}function ZD({onSelect:e,onOpenRoby:t,onOpenAddProject:s}){const{projects:o,isLoading:l}=Xc(),c=Qn(),u=QD(),p=op(),m=x.useRef(null),{collapsed:g,toggle:h}=$b(Tn.sidebarCollapsed+".projects"),b=S=>c.pathname===S||c.pathname.startsWith(`${S}/`),v=o.find(S=>String(S.id)==="0"),k=o.filter(S=>String(S.id)!=="0").sort((S,E)=>Number(E.id)-Number(S.id)),N=WD(m,k.length,!g&&k.length>0),j=k.slice(0,N),y=k.slice(N),C=y.some(S=>b(`/p/${S.id}`));return r.jsxs("aside",{className:"flex h-full w-20 flex-col items-center gap-3 overflow-hidden bg-transparent py-3",children:[r.jsx(Ye,{content:f("nav.apx_admin"),side:"right",children:r.jsx("button",{type:"button",onClick:()=>e("/"),"data-testid":"nav-home",className:"mb-2 cursor-pointer",children:r.jsx(o3,{size:36})})}),l&&r.jsx("div",{className:"size-10 animate-pulse rounded-xl bg-muted"}),v&&r.jsx(bl,{label:f("base.title"),testId:"project-avatar-0",title:f("base.subtitle"),active:b("/p/0"),isDefault:!0,icon:r.jsx("img",{src:"/modules/superagent.png",alt:f("base.title"),className:"size-7 object-contain",draggable:!1}),onClick:()=>e("/p/0")}),u.map(S=>r.jsx(bl,{label:S.label,testId:`module-avatar-${S.id}`,title:S.label,active:b(S.href),icon:r.jsx(S.icon,{size:18}),onClick:()=>e(S.href)},S.id)),r.jsxs("div",{className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3",children:[k.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"my-0.5 h-px w-8 rounded-full bg-border"}),r.jsx(Ye,{content:f(g?"nav.expand_projects":"nav.collapse_projects"),side:"right",children:r.jsx("button",{type:"button",onClick:h,"data-testid":"nav-toggle-projects","aria-label":f(g?"nav.expand_projects":"nav.collapse_projects"),"aria-expanded":!g,className:"flex h-5 w-8 cursor-pointer items-center justify-center rounded-md text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:r.jsx(pa,{className:Te("size-3.5 transition-transform",g&&"-rotate-90")})})})]}),r.jsxs("div",{ref:m,className:"flex min-h-0 w-full flex-1 flex-col items-center gap-3 overflow-hidden",children:[k.length>0&&g&&r.jsx(Bj,{projects:k,icon:r.jsx(RM,{size:18}),sublabel:String(k.length),tooltip:f("nav.all_projects"),header:f("nav.all_projects"),active:k.some(S=>b(`/p/${S.id}`)),testId:"nav-projects-folder",onSelect:e,isActive:b}),k.length>0&&!g&&r.jsxs(r.Fragment,{children:[r.jsx("div",{"data-rail-probe":!0,"aria-hidden":!0,className:"invisible absolute w-full",children:r.jsx(bl,{label:"Ag",active:!1,onClick:()=>{}})}),j.map(S=>{const E=S.name||S.path.split("/").pop()||String(S.id),R=`/p/${S.id}`;return r.jsx("div",{"data-rail-item":!0,className:"w-full",children:r.jsx(bl,{label:E,testId:`project-avatar-${S.id}`,title:`${E} — ${S.path}`,active:b(R),onClick:()=>e(R)})},S.id)}),y.length>0&&r.jsx(Bj,{projects:y,label:`+${y.length}`,tooltip:f("nav.more_projects",{count:y.length}),header:f("nav.more_projects",{count:y.length}),active:C,testId:"nav-projects-overflow",onSelect:e,isActive:b})]}),r.jsx(bl,{label:f("nav.add_project"),isAdd:!0,testId:"nav-add-project",icon:r.jsx(tn,{size:18}),active:!1,onClick:()=>s?s():e("/?action=add-project"),title:f("nav.add_project")})]})]}),r.jsx(bl,{label:f("nav.settings"),isSettings:!0,testId:"nav-settings",icon:r.jsx(Rc,{size:16}),active:c.pathname==="/settings"||c.pathname.startsWith("/settings/"),onClick:()=>e("/settings"),title:f("nav.settings")}),r.jsx(Ye,{content:f("settings_ui.documentation"),side:"right",children:r.jsx("a",{href:"https://agentprojectcontext.github.io/apx/docs/",target:"_blank",rel:"noopener noreferrer","data-testid":"nav-docs","aria-label":f("settings_ui.documentation"),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:r.jsx(lM,{size:18})})}),r.jsx(Ye,{content:f("superagent.talk",{persona:p}),side:"right",children:r.jsx("button",{type:"button",onClick:t,"data-testid":"nav-roby","aria-label":f("superagent.talk",{persona:p}),className:"flex size-10 items-center justify-center rounded-xl border border-border/60 bg-muted/30 text-muted-fg transition-colors hover:bg-accent hover:text-foreground",children:r.jsx(un,{size:18})})})]})}function kC(e){switch(e){case"personal":return f("settings_ui.kind_personal");case"company":return f("settings_ui.kind_company");case"app":return f("settings_ui.kind_app");case"software":return f("settings_ui.kind_software");case"default":return f("settings_ui.kind_default");case"other":return f("settings_ui.kind_other");default:return f("nav.project")}}function Ke({title:e,description:t,action:s,className:o,children:l,fullHeight:c}){return r.jsxs("section",{className:Te("rounded-xl border border-border bg-card p-5",c&&"flex h-full min-h-0 flex-col",o),children:[r.jsxs("header",{className:Te("mb-4 flex items-start justify-between gap-4",c&&"shrink-0"),children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:e}),t&&r.jsx("p",{className:"mt-0.5 text-sm text-muted-fg",children:t})]}),s]}),r.jsx("div",{className:Te(c&&"flex min-h-0 flex-1 flex-col"),children:l})]})}function Uj({children:e}){return r.jsx("kbd",{className:"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-muted-fg",children:e})}function Qc({ok:e}){return r.jsx("span",{className:Te("inline-block size-2 rounded-full",e===null?"bg-muted-fg":e?"bg-emerald-500":"bg-red-500")})}const JD=x.forwardRef(function(t,s){const{render:o,className:l,disabled:c=!1,focusableWhenDisabled:u=!1,nativeButton:p=!0,style:m,...g}=t,{getButtonProps:h,buttonRef:b}=Hr({disabled:c,focusableWhenDisabled:u,native:p});return Nt("button",t,{state:{disabled:c},ref:[s,b],props:[g,h]})}),Hj=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Vj=Tc,Wb=(e,t)=>s=>{var o;if(t?.variants==null)return Vj(e,s?.class,s?.className);const{variants:l,defaultVariants:c}=t,u=Object.keys(l).map(g=>{const h=s?.[g],b=c?.[g];if(h===null)return null;const v=Hj(h)||Hj(b);return l[g][v]}),p=s&&Object.entries(s).reduce((g,h)=>{let[b,v]=h;return v===void 0||(g[b]=v),g},{}),m=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((g,h)=>{let{class:b,className:v,...k}=h;return Object.entries(k).every(N=>{let[j,y]=N;return Array.isArray(y)?y.includes({...c,...p}[j]):{...c,...p}[j]===y})?[...g,b,v]:g},[]);return Vj(e,u,m,s?.class,s?.className)},eL=Wb("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",outline:"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",ghost:"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",xs:"h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",lg:"h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",icon:"size-8","icon-xs":"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg","icon-lg":"size-9"}},defaultVariants:{variant:"default",size:"default"}});function Wa({className:e,variant:t="default",size:s="default",...o}){return r.jsx(JD,{"data-slot":"button",className:St(eL({variant:t,size:s,className:e})),...o})}let qj=(function(e){return e.disabled="data-disabled",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.filled="data-filled",e.focused="data-focused",e})({});const tL={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},pc={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},nL={disabled:!1,...pc},Zb={valid(e){return e===null?null:e?{[qj.valid]:""}:{[qj.invalid]:""}}},sL={invalid:void 0,name:void 0,validityData:{state:tL,errors:[],error:"",value:"",initialValue:null},setValidityData:En,disabled:void 0,touched:pc.touched,setTouched:En,dirty:pc.dirty,setDirty:En,filled:pc.filled,setFilled:En,focused:pc.focused,setFocused:En,validate:()=>null,validationMode:"onSubmit",validationDebounceTime:0,shouldValidateOnChange:()=>!1,state:nL,markedDirtyRef:{current:!1},registerFieldControl:En,validation:{getValidationProps:(e,t=qt)=>t,inputRef:{current:null},registerInput:En,commit:async()=>{},change:En}},aL=x.createContext(sL);function Wc(e=!0){const t=x.useContext(aL);if(t.setValidityData===En&&!e)throw new Error(nn(28));return t}const rL=x.createContext({formRef:{current:{fields:new Map}},errors:{},clearErrors:En,validationMode:"onSubmit",submitAttemptedRef:{current:!1}});function Jb(){return x.useContext(rL)}const oL=x.createContext({controlId:void 0,registerControlId:En,labelId:void 0,setLabelId:En,messageIds:[],setMessageIds:En,getDescriptionProps:e=>e});function lp(){return x.useContext(oL)}function lL(e,t,s,o=!0,l){const[c,u]=x.useState(),p=Ks(l?`${l}-label`:void 0),m=e??t??c;return De(()=>{const g=e||t||!o?void 0:iL(s.current,p);c!==g&&u(g)}),m}function iL(e,t){const s=cL(e);if(s)return!s.id&&t&&(s.id=t),s.id||void 0}function cL(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const s=e.id;if(s){const l=e.nextElementSibling;if(l&&l.htmlFor===s)return l}const o=e.labels;return o&&o[0]}function ip(e={}){const{id:t,implicit:s=!1,controlRef:o}=e,{controlId:l,registerControlId:c}=lp(),u=Ks(t),p=s?l:void 0,m=Xn(()=>Symbol("labelable-control")),g=x.useRef(!1),h=x.useRef(t!=null),b=Ue(()=>{!g.current||c===En||(g.current=!1,c(m.current,void 0))});return De(()=>{if(c===En)return;let v;if(s){const k=o?.current;gt(k)&&k.closest("label")!=null?v=t??null:v=p??u}else if(t!=null)h.current=!0,v=t;else if(h.current)v=u;else{b();return}if(v===void 0){b();return}g.current=!0,c(m.current,v)},[t,o,p,c,s,u,m,b]),x.useEffect(()=>b,[b]),l??u}function e_(e,t,s,o,l=!0,c){const{registerFieldControl:u}=Wc(),p=x.useRef(null);p.current||(p.current=Symbol()),De(()=>{const m=p.current;return!m||!l?void 0:(u(m,{controlRef:e,getValue:o,id:t,name:c,value:s}),()=>{u(m,void 0)})},[e,l,o,t,c,u,s])}const uL=x.forwardRef(function(t,s){const{render:o,className:l,id:c,name:u,value:p,disabled:m=!1,onValueChange:g,defaultValue:h,autoFocus:b=!1,style:v,...k}=t,{state:N,name:j,disabled:y,setTouched:C,setDirty:S,validityData:E,setFocused:R,setFilled:A,validationMode:T,validation:M}=Wc(),{clearErrors:z}=Jb(),B=y||m,L=j??u,U={...N,disabled:B},{labelId:D}=lp(),I=ip({id:c});De(()=>{const X=p!=null;M.inputRef.current?.value||X&&p!==""?A(!0):X&&p===""&&A(!1)},[M.inputRef,A,p]);const V=x.useRef(null);De(()=>{b&&V.current===qn(mt(V.current))&&R(!0)},[b,R]);const[$]=Vl({controlled:p,default:h,name:"FieldControl",state:"value"}),q=p!==void 0,Y=q?$:void 0,K=Ue(()=>M.inputRef.current?.value);return e_(M.inputRef,I,Y,K,!B,u),Nt("input",t,{ref:[s,V],state:U,props:[{id:I,disabled:B,name:L,ref:M.inputRef,"aria-labelledby":D,autoFocus:b,...q?{value:Y}:{defaultValue:h},onChange(X){const P=X.currentTarget.value;g?.(P,nt(fa,X.nativeEvent)),S(P!==E.initialValue),A(P!==""),X.nativeEvent.defaultPrevented||(z(L),M.change(P))},onFocus(){R(!0)},onBlur(X){C(!0),R(!1),T==="onBlur"&&M.commit(X.currentTarget.value)},onKeyDown(X){X.currentTarget.tagName==="INPUT"&&X.key==="Enter"&&(C(!0),M.commit(X.currentTarget.value))}},k,X=>M.getValidationProps(B,X)],stateAttributesMapping:Zb})}),dL=x.forwardRef(function(t,s){return r.jsx(uL,{ref:s,...t})});function fL({className:e,type:t,...s}){return r.jsx(dL,{type:t,"data-slot":"input",className:St("h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...s})}function pL({className:e,...t}){return r.jsx("textarea",{"data-slot":"textarea",className:St("flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",e),...t})}function mL(e){return Nt(e.defaultTagName??"div",e,e)}const gL=Wb("group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",secondary:"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",destructive:"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",outline:"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",ghost:"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",link:"text-primary underline-offset-4 hover:underline"}},defaultVariants:{variant:"default"}});function hL({className:e,variant:t="default",render:s,...o}){return mL({defaultTagName:"span",props:Fn({className:St(gL({variant:t}),e)},o),render:s,state:{slot:"badge",variant:t}})}const SC=x.createContext(void 0);function xL(){const e=x.useContext(SC);if(e===void 0)throw new Error(nn(63));return e}let $j=(function(e){return e.checked="data-checked",e.unchecked="data-unchecked",e.disabled="data-disabled",e.readonly="data-readonly",e.required="data-required",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.filled="data-filled",e.focused="data-focused",e})({});const CC={...Zb,checked(e){return e?{[$j.checked]:""}:{[$j.unchecked]:""}}},bL=x.forwardRef(function(t,s){const{checked:o,className:l,defaultChecked:c,"aria-labelledby":u,form:p,id:m,inputRef:g,name:h,nativeButton:b=!1,onCheckedChange:v,readOnly:k=!1,required:N=!1,disabled:j=!1,render:y,uncheckedValue:C,value:S,style:E,...R}=t,{clearErrors:A}=Jb(),{state:T,setTouched:M,setDirty:z,validityData:B,setFilled:L,setFocused:U,validationMode:D,disabled:I,name:V,validation:$}=Wc(),{labelId:q}=lp(),Y=I||j,K=V??h,F=x.useRef(null),X=Xa(F,g,$.inputRef),P=x.useRef(null),G=Ks(),Z=ip({id:m,implicit:!1,controlRef:P}),ee=b?void 0:Z,[de,fe]=Vl({controlled:o,default:!!c,name:"Switch",state:"checked"});e_(P,G,de,void 0,!Y,h),De(()=>{F.current&&L(F.current.checked)},[F,L]),Ub(de,()=>{A(K),z(de!==B.initialValue),L(de),$.change(de)});const{getButtonProps:ae,buttonRef:oe}=Hr({disabled:Y,native:b}),me=lL(u,q,F,!b,ee),Ae={id:b?Z:G,role:"switch","aria-checked":de,"aria-readonly":k||void 0,"aria-required":N||void 0,"aria-labelledby":me,onFocus(){Y||U(!0)},onBlur(){const je=F.current;!je||Y||(M(!0),U(!1),D==="onBlur"&&$.commit(je.checked))},onClick(je){if(k||Y)return;je.preventDefault();const Be=F.current;Be&&Be.dispatchEvent(new($t(Be)).PointerEvent("click",{bubbles:!0,shiftKey:je.shiftKey,ctrlKey:je.ctrlKey,altKey:je.altKey,metaKey:je.metaKey}))}},ie=Fn({checked:de,disabled:Y,form:p,id:ee,name:K,required:N,style:K?SS:lb,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:X,onChange(je){if(je.nativeEvent.defaultPrevented)return;if(k){je.preventDefault();return}const Be=je.currentTarget.checked,Ve=nt(fa,je.nativeEvent);v?.(Be,Ve),!Ve.isCanceled&&fe(Be)},onFocus(){P.current?.focus()}},je=>$.getValidationProps(Y,je),S!==void 0?{value:S}:qt),pe=x.useMemo(()=>({...T,checked:de,disabled:Y,readOnly:k,required:N}),[T,de,Y,k,N]),Se=Nt("span",t,{state:pe,ref:[s,P,oe],props:[Ae,R,ae,je=>$.getValidationProps(Y,je)],stateAttributesMapping:CC});return r.jsxs(SC.Provider,{value:pe,children:[Se,!de&&K&&C!==void 0&&r.jsx("input",{type:"hidden",form:p,name:K,value:C,disabled:Y}),r.jsx("input",{...ie,suppressHydrationWarning:!0})]})}),_L=x.forwardRef(function(t,s){const{render:o,className:l,style:c,...u}=t,p=xL();return Nt("span",t,{state:p,ref:s,stateAttributesMapping:CC,props:u})});function vL({className:e,size:t="default",...s}){return r.jsx(bL,{"data-slot":"switch","data-size":t,className:St("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...s,children:r.jsx(_L,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function yL({className:e,...t}){return r.jsx(Af,{role:"status","aria-label":"Loading",className:St("size-4 animate-spin",e),...t})}const NC=x.createContext(!1),EC=x.createContext(void 0);function To(e){const t=x.useContext(EC);if(e===!1&&t===void 0)throw new Error(nn(27));return t}const jL={...Ro,...Ja},RC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,forceRender:u=!1,...p}=t,{store:m}=To(),g=m.useState("open"),h=m.useState("nested"),b=m.useState("mounted"),v=m.useState("transitionStatus");return Nt("div",t,{state:{open:g,transitionStatus:v},ref:[m.context.backdropRef,s],stateAttributesMapping:jL,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},p],enabled:u||!h})}),cp=x.forwardRef(function(t,s){const{render:o,className:l,style:c,disabled:u=!1,nativeButton:p=!0,...m}=t,{store:g}=To(),h=g.useState("open"),{getButtonProps:b,buttonRef:v}=Hr({disabled:u,native:p}),k={disabled:u};function N(j){h&&g.setOpen(!1,nt(l5,j.nativeEvent))}return Nt("button",t,{state:k,ref:[s,v],props:[{onClick:N},m,b]})}),TC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,id:u,...p}=t,{store:m}=To(),g=Ks(u);return m.useSyncedValueWithCleanup("descriptionElementId",g),Nt("p",t,{ref:s,props:[{id:g},p]})});let wL=(function(e){return e.nestedDialogs="--nested-dialogs",e})({}),kL=(function(e){return e[e.open=po.open]="open",e[e.closed=po.closed]="closed",e[e.startingStyle=po.startingStyle]="startingStyle",e[e.endingStyle=po.endingStyle]="endingStyle",e.nested="data-nested",e.nestedDialogOpen="data-nested-dialog-open",e})({});const AC=x.createContext(void 0);function SL(){const e=x.useContext(AC);if(e===void 0)throw new Error(nn(26));return e}const CL={...Ro,...Ja,nestedDialogOpen(e){return e?{[kL.nestedDialogOpen]:""}:null}},MC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,finalFocus:u,initialFocus:p,...m}=t,{store:g}=To(),h=g.useState("descriptionElementId"),b=g.useState("disablePointerDismissal"),v=g.useState("floatingRootContext"),k=g.useState("popupProps"),N=g.useState("modal"),j=g.useState("mounted"),y=g.useState("nested"),C=g.useState("nestedOpenDialogCount"),S=g.useState("open"),E=g.useState("openMethod"),R=g.useState("titleElementId"),A=g.useState("transitionStatus"),T=g.useState("role"),M=v.useState("floatingId"),z=m.id??M;SL(),ha({open:S,ref:g.context.popupRef,onComplete(){S&&g.context.onOpenChangeComplete?.(!0)}});const B=p===void 0?f4(g.context.popupRef):p,L=C>0,U=g.useStateSetter("popupElement"),I=Nt("div",t,{state:{open:S,nested:y,transitionStatus:A,nestedDialogOpen:L},props:[k,{id:z,"aria-labelledby":R??void 0,"aria-describedby":h??void 0,role:T,...Xf,hidden:!j,onKeyDown(V){sp.has(V.key)&&V.stopPropagation()},style:{[wL.nestedDialogs]:C}},m],ref:[s,g.context.popupRef,U],stateAttributesMapping:CL});return r.jsx(_b,{context:v,openInteractionType:E,disabled:!j,closeOnFocusOut:!b,initialFocus:B,returnFocus:u,modal:N!==!1,restoreFocus:"popup",children:I})}),OC=x.forwardRef(function(t,s){const{keepMounted:o=!1,...l}=t,{store:c}=To(),u=c.useState("mounted"),p=c.useState("modal"),m=c.useState("open");return u||o?r.jsx(AC.Provider,{value:o,children:r.jsxs(hb,{ref:s,...l,children:[u&&p===!0&&r.jsx(Bb,{ref:c.context.internalBackdropRef,inert:Jf(!m)}),t.children]})}):null});function NL(e){const{store:t,actionsRef:s}=e,o=t.useState("open");g4(t,o),wb(t);const{forceUnmount:l}=kb(o,t),c=x.useCallback(()=>{t.setOpen(!1,nt(rb))},[t]);x.useImperativeHandle(s,()=>({unmount:l,close:c}),[l,c])}function EL({store:e,parentContext:t,isDrawer:s}){const o=e.useState("open"),l=e.useState("disablePointerDismissal"),c=e.useState("modal"),u=e.useState("popupElement"),p=e.useState("floatingRootContext"),[m,g]=x.useState(0),[h,b]=x.useState(0),v=m===0,k=Ff(p,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:c==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(C){if(!e.context.outsidePressEnabledRef.current||"button"in C&&C.button!==0||"touches"in C&&C.touches.length!==1)return!1;const S=Un(C);return v&&!l?c&&(e.context.internalBackdropRef.current||e.context.backdropRef.current)?e.context.internalBackdropRef.current===S||e.context.backdropRef.current===S||Qe(S,u)&&!S?.hasAttribute("data-base-ui-portal"):!0:!1},escapeKey:v});Q2(o&&c===!0,u),e.useContextCallback("onNestedDialogOpen",(C,S)=>{g(C),b(S)}),e.useContextCallback("onNestedDialogClose",()=>{g(0),b(0)}),x.useEffect(()=>(t?.onNestedDialogOpen&&o&&t.onNestedDialogOpen(m+1,h+(s?1:0)),t?.onNestedDialogClose&&!o&&t.onNestedDialogClose(),()=>{t?.onNestedDialogClose&&o&&t.onNestedDialogClose()}),[s,o,m,h,t]);const N=k.reference??qt,j=k.trigger??qt,y=k.floating??qt;return Sb(e,{activeTriggerProps:N,inactiveTriggerProps:j,popupProps:y,nestedOpenDialogCount:m,nestedOpenDrawerCount:h}),null}const RL={...Eb,modal:Me(e=>e.modal),nested:Me(e=>e.nested),nestedOpenDialogCount:Me(e=>e.nestedOpenDialogCount),nestedOpenDrawerCount:Me(e=>e.nestedOpenDrawerCount),disablePointerDismissal:Me(e=>e.disablePointerDismissal),openMethod:Me(e=>e.openMethod),descriptionElementId:Me(e=>e.descriptionElementId),titleElementId:Me(e=>e.titleElementId),viewportElement:Me(e=>e.viewportElement),role:Me(e=>e.role)};class t_ extends Yf{constructor(t,s,o=!1){const l=new Fc,c=TL(t);c.floatingRootContext=h2(l,s,o),super(c,{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:l,onOpenChange:void 0,onOpenChangeComplete:void 0},RL)}setOpen=(t,s)=>{if(s.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!t&&s.trigger==null&&this.state.activeTriggerId!=null&&(s.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(t,s),s.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,s);const o={open:t};jb(o,t,s.trigger),this.update(o)};static useStore(t,s){return f2(t,(l,c)=>new t_(s,l,c),!0).store}}function TL(e={}){return{...Cb(),modal:!0,disablePointerDismissal:!1,popupElement:null,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}function AL(e,t="dialog"){const{children:s,open:o,defaultOpen:l=!1,onOpenChange:c,onOpenChangeComplete:u,disablePointerDismissal:p=!1,modal:m=!0,actionsRef:g,handle:h,triggerId:b,defaultTriggerId:v=null}=e,k=t==="drawer",N=t==="alert-dialog",j=N?!0:m,y=N||p,C=N?"alertdialog":"dialog",S=To(!0),R={modal:j,disablePointerDismissal:y,nested:!!S,role:C},A=t_.useStore(h?.store,{open:l,openProp:o,activeTriggerId:v,triggerIdProp:b,...R});yb(()=>{const U=o===void 0&&A.state.open===!1&&l===!0?{open:!0,activeTriggerId:v}:null;N?A.update(U?{...R,...U}:R):U&&A.update(U)}),A.useControlledProp("openProp",o),A.useControlledProp("triggerIdProp",b),A.useSyncedValues(R),A.useContextCallback("onOpenChange",c),A.useContextCallback("onOpenChangeComplete",u);const T=A.useState("open"),M=A.useState("mounted"),z=A.useState("payload");NL({store:A,actionsRef:g});const B=T||M,L=x.useMemo(()=>({store:A}),[A]);return r.jsx(NC.Provider,{value:!1,children:r.jsxs(EC.Provider,{value:L,children:[B&&r.jsx(EL,{store:A,parentContext:S?.store.context,isDrawer:k}),typeof s=="function"?s({payload:z}):s]})})}function zC(e){const t=x.useContext(NC)?"drawer":"dialog";return AL(e,t)}const DC=x.forwardRef(function(t,s){const{render:o,className:l,style:c,id:u,...p}=t,{store:m}=To(),g=Ks(u);return m.useSyncedValueWithCleanup("titleElementId",g),Nt("h2",t,{ref:s,props:[{id:g},p]})});function mx({...e}){return r.jsx(zC,{"data-slot":"dialog",...e})}function ML({...e}){return r.jsx(OC,{"data-slot":"dialog-portal",...e})}function OL({...e}){return r.jsx(cp,{"data-slot":"dialog-close",...e})}function zL({className:e,...t}){return r.jsx(RC,{"data-slot":"dialog-overlay",className:St("fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",e),...t})}function gx({className:e,children:t,showCloseButton:s=!0,...o}){return r.jsxs(ML,{children:[r.jsx(zL,{}),r.jsxs(MC,{"data-slot":"dialog-content",className:St("fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...o,children:[t,s&&r.jsxs(cp,{"data-slot":"dialog-close",render:r.jsx(Wa,{variant:"ghost",className:"absolute top-2 right-2",size:"icon-sm"}),children:[r.jsx(Ys,{}),r.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function hx({className:e,...t}){return r.jsx("div",{"data-slot":"dialog-header",className:St("flex flex-col gap-2",e),...t})}function Fj({className:e,showCloseButton:t=!1,children:s,...o}){return r.jsxs("div",{"data-slot":"dialog-footer",className:St("-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",e),...o,children:[s,t&&r.jsx(cp,{render:r.jsx(Wa,{variant:"outline"}),children:"Close"})]})}function xx({className:e,...t}){return r.jsx(DC,{"data-slot":"dialog-title",className:St("font-heading text-base leading-none font-medium",e),...t})}function DL({className:e,...t}){return r.jsx(TC,{"data-slot":"dialog-description",className:St("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",e),...t})}const LL={primary:"default",secondary:"outline",ghost:"ghost",destructive:"destructive"},PL={sm:"sm",md:"default"};function ce({variant:e="secondary",size:t="md",loading:s,className:o,children:l,disabled:c,type:u="button",...p}){return r.jsxs(Wa,{type:u,variant:LL[e],size:PL[t],disabled:c||s,className:o,...p,children:[s?r.jsx(vs,{size:14}):null,l]})}function Ne(e){return r.jsx(fL,{...e})}function Mn(e){return r.jsx(pL,{...e})}function IL(e){return r.jsx("select",{...e,className:Te("h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",e.className)})}function le({label:e,hint:t,badge:s,children:o}){return r.jsxs("div",{className:"block space-y-1",children:[r.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[e,s&&r.jsx("span",{className:"rounded bg-muted px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-muted-foreground",children:s})]}),o,t&&r.jsx("span",{className:"block text-[11px] text-muted-foreground/70",children:t})]})}function Ft({checked:e,onChange:t,label:s,disabled:o}){return r.jsxs("label",{className:Te("inline-flex items-center gap-2",o&&"opacity-50"),children:[r.jsx(vL,{checked:e,onCheckedChange:t,disabled:o}),s&&r.jsx("span",{className:"text-sm",children:s})]})}function Fe({children:e,tone:t="muted",className:s}){const o=t==="danger"?"destructive":t==="muted"?"secondary":"outline",l={muted:"",danger:"",success:"text-emerald-400 border-emerald-500/30",warning:"text-amber-400 border-amber-500/30",info:"text-sky-400 border-sky-500/30"};return r.jsx(hL,{variant:o,className:Te("rounded-md",l[t],s),children:e})}function On({open:e,onClose:t,title:s,description:o,children:l,footer:c,size:u="md"}){const p={sm:"sm:max-w-md",md:"sm:max-w-lg",lg:"sm:max-w-2xl",xl:"sm:max-w-4xl"};return r.jsx(mx,{open:e,onOpenChange:m=>{m||t()},children:r.jsxs(gx,{className:Te("flex max-h-[88vh] w-full flex-col gap-0 p-0",p[u]),children:[(s||o)&&r.jsxs(hx,{className:"shrink-0 border-b border-border px-5 py-4 pr-12",children:[s&&r.jsx(xx,{children:s}),o&&r.jsx(DL,{children:o})]}),r.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:l}),c&&r.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-5 py-4",children:c})]})})}function vs({size:e=14}){return r.jsx(yL,{style:{width:e,height:e}})}function xt({children:e}){return r.jsx("div",{className:"rounded-lg border border-dashed border-border bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground",children:e})}function ot({label:e="Cargando…"}){return r.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[r.jsx(vs,{})," ",e]})}const LC=x.createContext(null);let BL=1;function UL({children:e}){const[t,s]=x.useState([]),o=x.useCallback((c,u)=>{const p=BL++;s(m=>[...m,{id:p,kind:c,message:u}]),setTimeout(()=>{s(m=>m.filter(g=>g.id!==p))},4500)},[]),l=x.useMemo(()=>({show:o,success:c=>o("success",c),error:c=>o("error",c),info:c=>o("info",c)}),[o]);return x.useEffect(()=>(window.__apxToast=l,()=>{delete window.__apxToast}),[l]),r.jsxs(LC.Provider,{value:l,children:[e,r.jsx("div",{className:"pointer-events-none fixed bottom-4 right-4 z-[100] flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",children:t.map(c=>r.jsx("div",{className:Te("pointer-events-auto overflow-hidden rounded-lg border bg-card px-3 py-2 text-sm shadow-lg",c.kind==="success"&&"border-emerald-500/40",c.kind==="error"&&"border-destructive/60",c.kind==="info"&&"border-border"),children:r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("span",{className:Te("mt-1 size-2 shrink-0 rounded-full",c.kind==="success"&&"bg-emerald-500",c.kind==="error"&&"bg-destructive",c.kind==="info"&&"bg-sky-500")}),r.jsx("span",{className:"flex-1 break-words",children:c.message})]})},c.id))})]})}function lt(){const e=x.useContext(LC);if(!e)throw new Error("useToast must be used inside <ToastProvider>");return e}function PC(){const{data:e,error:t,isLoading:s}=et("/health",()=>UD.get(),{refreshInterval:Of.health});return{health:e,error:t,isLoading:s,isUp:!t&&!!e}}function HL(){const{data:e,error:t,isLoading:s,mutate:o}=et("/engines",()=>mf.list());return{engines:e?.engines||[],error:t,isLoading:s,mutate:o}}function VL(){const{data:e,error:t,isLoading:s,mutate:o}=et("/telegram/status",()=>An.status(),{refreshInterval:Of.telegramStatus});return{status:e,error:t,isLoading:s,mutate:o}}function n_(){const{data:e,error:t,isLoading:s,mutate:o}=et("/telegram/channels",()=>An.channels.list());return{channels:e?.channels||[],error:t,isLoading:s,mutate:o}}function s_(){const{data:e,error:t,isLoading:s,mutate:o}=et("/telegram/contacts",()=>An.contacts.list());return{contacts:e?.contacts||[],roles:e?.roles||{},channelOwners:e?.channel_owners||[],error:t,isLoading:s,mutate:o}}function is(e){return typeof e=="string"&&e.startsWith("*** set ***")}function Ar(e,t="(no seteada)"){return is(e)?e:t}function jo(e){if(typeof e!="string")return null;const t=e.match(/\(\.\.\.([^)]+)\)/);return t?t[1]:null}function IC({channel:e,onClose:t,onSaved:s}){const o=lt(),[l,c]=x.useState(!1),[u,p]=x.useState({name:""});x.useEffect(()=>{p(e?{...e,bot_token:""}:{name:""})},[e?.name]);const m=async()=>{if(!u.name?.trim()){o.error(f("telegram_channel_dialog.name_required"));return}c(!0);try{e&&e.name!==""&&e?.name===u.name?await An.channels.patch(e.name,u):await An.channels.upsert(u),o.success(f("telegram_channel_dialog.saved")),s()}catch(g){o.error(g.message)}finally{c(!1)}};return r.jsx(On,{open:!!e,onClose:t,title:e?.name?f("telegram_channel_dialog.edit_title",{name:e.name}):f("telegram_channel_dialog.new_title"),description:f("telegram_ui.channel_dialog_desc"),footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:l,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:m,loading:l,children:f("common.save")})]}),children:r.jsxs("div",{className:"space-y-3",children:[r.jsx(le,{label:f("telegram_channel_dialog.name_label"),children:r.jsx(Ne,{value:u.name,onChange:g=>p({...u,name:g.target.value}),disabled:!!e?.name})}),r.jsx(le,{label:f("telegram_channel_dialog.token_label"),hint:e?.bot_token?Ar(e.bot_token):f("telegram_ui.bot_token_hint"),children:r.jsx(Ne,{type:"password",value:u.bot_token||"",onChange:g=>p({...u,bot_token:g.target.value}),placeholder:e?.bot_token?Ar(e.bot_token):""})}),r.jsx(le,{label:f("telegram_channel_dialog.chat_id"),children:r.jsx(Ne,{value:u.chat_id||"",onChange:g=>p({...u,chat_id:g.target.value})})}),r.jsx(le,{label:f("telegram_channel_dialog.project_label"),hint:f("telegram_channel_dialog.project_hint"),children:r.jsx(Ne,{value:u.project||"",onChange:g=>p({...u,project:g.target.value})})}),r.jsx(le,{label:f("telegram_channel_dialog.route_label"),hint:f("telegram_channel_dialog.route_hint"),children:r.jsx(Ne,{value:u.route_to_agent||"",onChange:g=>p({...u,route_to_agent:g.target.value})})}),r.jsx(le,{label:f("telegram_channel_dialog.owner_label"),hint:f("telegram_channel_dialog.owner_hint"),children:r.jsx(Ne,{value:u.owner_user_id!=null?String(u.owner_user_id):"",onChange:g=>{const h=g.target.value.trim();p({...u,owner_user_id:h===""?void 0:/^\d+$/.test(h)?Number(h):h})},placeholder:"889721252"})}),r.jsx(Ft,{checked:!!u.respond_with_engine,onChange:g=>p({...u,respond_with_engine:g}),label:f("telegram_channel_dialog.respond_label")})]})})}function BC({channel:e,onClose:t}){const s=lt(),[o,l]=x.useState(f("admin.telegram_default_message")),[c,u]=x.useState(!1),p=async()=>{if(!(!o.trim()||!e)){u(!0);try{await An.send({text:o,channel:e.name}),s.success(f("telegram_ui.message_sent")),t()}catch(m){s.error(m.message)}finally{u(!1)}}};return r.jsx(On,{open:!!e,onClose:t,title:e?f("telegram_send_dialog.title",{name:e.name}):"",description:e?f("telegram_ui.send_chat_id",{id:e.chat_id||"—"}):"",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:c,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:p,loading:c,children:f("chat_ui.send")})]}),children:r.jsx(le,{label:f("telegram_ui.message_label"),children:r.jsx(Mn,{rows:4,value:o,onChange:m=>l(m.target.value)})})})}function UC({bare:e=!1}){const t=lt(),{contacts:s,roles:o,channelOwners:l,isLoading:c,mutate:u}=s_(),p=new Set(l.filter(v=>v.owner_user_id!=null).map(v=>String(v.owner_user_id))),m=Array.from(new Set(["owner","guest",...Object.keys(o)])),g=async(v,k)=>{try{await An.contacts.patch(v.user_id,{role:k}),t.success(f("telegram_ui.role_assigned",{name:v.name||v.user_id,role:k})),u()}catch(N){t.error(N.message)}},h=async v=>{if(confirm(f("telegram_contacts.delete_confirm",{name:v.name||String(v.user_id)})))try{await An.contacts.remove(v.user_id),t.success(f("telegram_contacts.removed")),u()}catch(k){t.error(k.message)}},b=r.jsxs(r.Fragment,{children:[c&&r.jsx(ot,{}),!c&&s.length===0&&r.jsx(xt,{children:f("telegram_contacts.empty")}),s.length>0&&r.jsx("ul",{className:"space-y-2 text-sm",children:s.map(v=>{const k=p.has(String(v.user_id)),N=k?"owner":v.role||"guest";return r.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("span",{className:"font-medium",children:v.name||"—"}),v.username&&r.jsxs("span",{className:"ml-2 text-xs text-muted-fg",children:["@",v.username]}),k&&r.jsx(Fe,{tone:"success",children:f("telegram_contacts.owner_badge")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ye,{content:f(k?"telegram_contacts.owner_hint":"telegram_contacts.assign_role"),children:r.jsx(IL,{value:N,disabled:k,onChange:j=>g(v,j.target.value),children:m.map(j=>r.jsx("option",{value:j,children:j},j))})}),r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>h(v),children:f("common.delete")})]})]}),r.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[r.jsxs("span",{children:["user_id: ",String(v.user_id)]}),r.jsxs("span",{children:[f("telegram_contacts.last_seen")," ",v.last_seen?v.last_seen.slice(0,10):"—"]}),r.jsx("span",{children:qL(o[N])})]})]},String(v.user_id))})})]});return e?b:r.jsx(Ke,{title:f("telegram_contacts.title"),description:f("telegram_contacts.desc"),children:b})}function qL(e){return!e||e.tools===void 0?"":e.tools==="*"?f("telegram_contacts.tools_all"):Array.isArray(e.tools)?e.tools.length?`${f("telegram_contacts.tools_label")} ${e.tools.join(", ")}`:f("telegram_contacts.tools_none"):""}function $L(){const e=Wn(),[t,s]=Nf(),o=lt(),{health:l,isUp:c}=PC(),{projects:u,isLoading:p,mutate:m}=Xc(),{engines:g,isLoading:h}=HL(),{status:b,mutate:v}=VL(),{channels:k,isLoading:N,mutate:j}=n_(),[y,C]=x.useState(null),[S,E]=x.useState(null),R=async()=>{try{await $l.reload(),o.success(f("admin.reload_success"))}catch(z){o.error(z.message)}},A=async()=>{try{b?.enabled?(await An.stop(),o.info(f("admin.telegram_polling_stopped"))):(await An.start(),o.success(f("admin.telegram_polling_started"))),v()}catch(z){o.error(z.message)}},T=async z=>{if(confirm(f("telegram_channels.delete_confirm",{name:z})))try{await An.channels.remove(z),o.success(f("admin.telegram_channel_removed")),j()}catch(B){o.error(B.message)}},M=async(z,B)=>{if(confirm(f("admin.unregister_confirm",{label:B})))try{await ls.remove(z),o.success(f("project.unregistered")),m()}catch(L){o.error(L.message)}};return r.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-6","data-testid":"screen-admin",children:[r.jsxs("header",{className:"flex items-end justify-between",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:f("admin.title")}),r.jsx("p",{className:"text-sm text-muted-fg",children:f("admin.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Ye,{content:f("daemon.reload_hint"),children:r.jsxs(ce,{size:"sm",onClick:R,children:[f("common.reload")," config"]})}),r.jsxs(ce,{size:"sm",variant:"primary",onClick:()=>{const z=new URLSearchParams(t);z.set("action","add-project"),s(z)},children:[r.jsx(tn,{size:14})," ",f("nav.project")]})]})]}),r.jsx(Ke,{title:f("daemon.version"),children:r.jsxs("div",{className:"grid grid-cols-3 gap-3 text-sm",children:[r.jsx(th,{label:f("daemon.version"),value:l?.version||"—"}),r.jsx(th,{label:f("daemon.uptime"),value:l?`${l.uptime_s}s`:"—"}),r.jsx(th,{label:f("daemon.status"),value:f(c?"daemon.running":"daemon.down"),ok:c})]})}),r.jsxs(Ke,{title:f("admin.engines_title"),description:f("admin.engines_subtitle"),children:[h&&r.jsx(ot,{}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:g.map(z=>r.jsx(Fe,{tone:"info",children:z},z))})]}),r.jsxs(Ke,{title:f("admin.telegram_title"),description:f("admin.telegram_subtitle"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ft,{checked:!!b?.enabled,onChange:A,label:b?.enabled?f("admin.telegram_polling_on"):f("admin.telegram_polling_off")}),r.jsxs(ce,{size:"sm",onClick:()=>C({name:""}),children:[r.jsx(tn,{size:14})," ",f("admin.telegram_add_channel")]})]}),children:[N&&r.jsx(ot,{}),k.length===0&&r.jsx(xt,{children:f("common.none_yet")}),r.jsx("ul",{className:"space-y-2 text-sm",children:k.map(z=>r.jsxs("li",{className:"rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"font-medium",children:z.name}),r.jsxs("div",{className:"flex items-center gap-2",children:[z.project&&r.jsxs(Fe,{tone:"success",children:["project = ",z.project]}),r.jsxs(ce,{size:"sm",variant:"ghost",onClick:()=>E(z),children:[r.jsx(Gs,{size:13})," ",f("admin.telegram_send_test")]}),r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>C(z),children:f("common.edit")}),r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>T(z.name),children:f("common.delete")})]})]}),r.jsxs("div",{className:"mt-1 grid grid-cols-3 gap-2 text-xs text-muted-fg",children:[r.jsxs("span",{children:["chat_id: ",z.chat_id||"—"]}),r.jsxs("span",{children:["route_to_agent: ",z.route_to_agent||"default APX"]}),r.jsxs("span",{children:["engine: ",z.respond_with_engine?f("admin.engine_badge"):f("admin.engine_badge_no")]})]})]},z.name))})]}),r.jsx(UC,{}),r.jsxs(Ke,{title:f("admin.projects_title"),description:f("admin.projects_subtitle"),children:[p&&r.jsx(ot,{}),r.jsx("ul",{className:"divide-y divide-border",children:u.map(z=>r.jsxs("li",{className:"flex items-center gap-3 py-2",children:[r.jsxs("span",{className:"w-10 font-mono text-xs text-muted-fg",children:["#",z.id]}),r.jsxs("button",{type:"button",className:"flex-1 text-left hover:underline",onClick:()=>e(`/p/${z.id}`),children:[r.jsx("span",{className:"font-medium",children:z.name||z.path.split("/").pop()}),r.jsx("span",{className:"ml-2 text-xs text-muted-fg",children:z.path})]}),r.jsxs(Fe,{children:[z.agents??0," ",f("admin.agents_badge")]}),Number(z.id)!==0&&r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>M(String(z.id),z.name||z.path),children:f("admin.unregister")})]},z.id))})]}),r.jsx(IC,{channel:y,onClose:()=>C(null),onSaved:()=>{C(null),j()}}),r.jsx(BC,{channel:S,onClose:()=>E(null)})]})}function th({label:e,value:t,ok:s}){return r.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-3",children:[r.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),r.jsxs("div",{className:"mt-1 flex items-center gap-2 text-base font-medium",children:[s!==void 0&&r.jsx(Qc,{ok:s}),r.jsx("span",{children:t})]})]})}const HC=x.createContext(null),VC=x.createContext(null),qC=x.createContext(""),$C=x.createContext(null),FC=x.createContext(null),GC=x.createContext(null);function FL({children:e}){const[t,s]=x.useState(null),[o,l]=x.useState(""),[c,u]=x.useState(null);return r.jsx(VC.Provider,{value:s,children:r.jsx(HC.Provider,{value:t,children:r.jsx($C.Provider,{value:l,children:r.jsx(qC.Provider,{value:o,children:r.jsx(GC.Provider,{value:u,children:r.jsx(FC.Provider,{value:c,children:e})})})})})})}function GL(){return x.useContext(HC)}function YL(e,t){const s=x.useContext(VC);x.useEffect(()=>(s?.({collapsed:e,toggle:t}),()=>s?.(null)),[e,t,s])}function KL(){return x.useContext(qC)}function XL(e){const t=x.useContext($C);x.useEffect(()=>(t?.(e),()=>t?.("")),[e,t])}function QL(){return x.useContext(FC)}function WL(e){const t=x.useContext(GC);x.useEffect(()=>(t?.(e),()=>t?.(null)),[e,t])}function YC({sections:e,active:t,onChange:s,collapsed:o,onToggleCollapse:l,actions:c,contentClassName:u,testId:p,children:m}){return YL(o,l),r.jsxs("div",{className:"flex h-full",children:[r.jsx(dD,{sections:e,active:t,onChange:s,collapsed:o}),r.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[c?r.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 px-6 pt-3",children:c}):null,r.jsx("div",{className:Te("flex-1 min-h-0 overflow-y-auto",u),"data-testid":p,children:m})]})]})}const Gj={happy:{eyes:["◕","◕"],mouth:"‿"},wave:{eyes:["◕","◕"],mouth:"▽",top:"·"},confused:{eyes:["◑","◐"],mouth:"o",top:"?"},sad:{eyes:["╥","╥"],mouth:"◠"},excited:{eyes:["★","★"],mouth:"▽",top:"✦"},sleeping:{eyes:["−","−"],mouth:"‿",top:"z z"}};function KC({mood:e="happy",className:t}){const s=Gj[e]??Gj.happy,[o,l]=s.eyes,c="text-emerald-700 dark:text-emerald-600/70";return r.jsxs("div",{"aria-hidden":!0,className:St("select-none whitespace-pre font-mono leading-none text-emerald-400",t),children:[s.top&&r.jsx("div",{children:r.jsx("span",{className:c,children:` ${s.top}`})}),r.jsx("div",{children:" ▄███████▄"}),r.jsxs("div",{children:[" █ ",r.jsx("span",{className:c,children:"██"})," ",r.jsx("span",{className:c,children:"██"})," █"]}),r.jsx("div",{children:` █ ${o} ${l} █`}),r.jsx("div",{children:` █ ${s.mouth} █`}),r.jsx("div",{children:" ▀███████▀"})]})}function XC({mood:e="confused",title:t,titleClassName:s,message:o,action:l,className:c,testId:u}){return r.jsx("div",{className:St("grid h-full place-items-center p-8",c),"data-testid":u,children:r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsx(KC,{mood:e,className:"mb-6 text-sm"}),t!=null&&r.jsx("div",{className:St("font-mono font-semibold leading-none tracking-tight text-foreground",s),children:t}),o!=null&&r.jsx("p",{className:"mt-4 max-w-sm text-sm text-muted-fg",children:o}),l&&r.jsx("div",{className:"mt-6",children:l})]})})}function Yj({pid:e}){const t=et(`/projects/${e}/tasks?state=open`,()=>Nr.list(e)),s=et(`/projects/${e}/routines`,()=>Cr.list(e)),o=et(`/projects/${e}/agents`,()=>rn.list(e)),l=et(`/projects/${e}/mcps`,()=>Er.list(e));return r.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-3",children:[r.jsx(ec,{title:f("project.overview.tasks_open"),value:t.data?.length??"…",href:`/p/${e}/tasks`,icon:Ll}),r.jsx(ec,{title:f("project.overview.routines"),value:s.data?.length??"…",href:`/p/${e}/routines`,icon:Dl}),r.jsx(ec,{title:f("project.overview.agents"),value:o.data?.length??"…",href:`/p/${e}/agents`,icon:un}),r.jsx(ec,{title:f("project.overview.mcps"),value:l.data?.length??"…",href:`/p/${e}/mcps`,icon:$h}),r.jsx(ec,{title:f("project.overview.chat"),value:f("project.overview.chat_value"),href:`/p/${e}/chat`,icon:Xd})]})}function ec({title:e,value:t,href:s,icon:o}){return r.jsxs(Bk,{to:s,className:"flex items-center gap-3 rounded-xl border border-border bg-card p-4 hover:bg-accent/40",children:[r.jsx("span",{className:"grid size-10 place-items-center rounded-lg bg-muted text-muted-fg",children:r.jsx(o,{size:20})}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-fg",children:e}),r.jsx("div",{className:"text-2xl font-semibold",children:t})]})]})}function ZL(){const e=Wn(),{projects:t,isLoading:s}=Xc();return r.jsxs(Ke,{title:f("base.workspaces_title"),description:f("base.workspaces_desc"),action:r.jsxs(ce,{size:"sm",variant:"primary",onClick:()=>e("/p/0/workspaces?action=add-project"),children:[r.jsx(tn,{size:14})," ",f("base.workspaces_new")]}),children:[s&&r.jsx(ot,{}),!s&&t.length===0&&r.jsx(xt,{children:f("base.workspaces_empty")}),r.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(o=>{const l=String(o.id)==="0",c=l?f("base.title"):o.name||o.path.split("/").pop()||String(o.id);return r.jsxs("button",{type:"button",onClick:()=>e(`/p/${o.id}`),className:"flex cursor-pointer flex-col gap-2 rounded-xl border border-border bg-card p-4 text-left transition-colors hover:border-muted-fg/50",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Qk,{className:"size-4 text-muted-fg"}),r.jsx("span",{className:"truncate text-sm font-semibold",children:c}),r.jsx(Fe,{tone:l?"success":"info",children:l?f("base.title"):kC(o.kind)})]}),r.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:o.path})]},o.id)})})]})}const QC=x.createContext(null),WC=x.createContext(null);function xa(){const e=x.useContext(QC);if(e===null)throw new Error(nn(60));return e}function ZC(){const e=x.useContext(WC);if(e===null)throw new Error(nn(61));return e}const JL=(e,t)=>Object.is(e,t);function wo(e,t,s){return e==null||t==null?Object.is(e,t):s(e,t)}function eP(e,t,s){return!e||e.length===0?!1:e.some(o=>o===void 0?!1:wo(t,o,s))}function kc(e,t,s){return!e||e.length===0?-1:e.findIndex(o=>o===void 0?!1:wo(o,t,s))}function tP(e,t,s){return e.filter(o=>!wo(t,o,s))}function bx(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function JC(e){return e!=null&&e.length>0&&typeof e[0]=="object"&&e[0]!=null&&"items"in e[0]}function nP(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(JC(t)){for(const s of t)for(const o of s.items)if(o&&o.value==null&&o.label!=null)return!0;return!1}for(const s of t)if(s&&s.value==null&&s.label!=null)return!0;return!1}function eN(e,t){if(t&&e!=null)return t(e)??"";if(e&&typeof e=="object"){if("label"in e&&e.label!=null)return String(e.label);if("value"in e)return String(e.value)}return bx(e)}function co(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?bx(e.value):bx(e)}function tN(e,t,s){function o(){return eN(e,s)}if(s&&e!=null)return s(e);if(e&&typeof e=="object"&&"label"in e&&e.label!=null)return e.label;if(t&&!Array.isArray(t))return t[e]??o();if(Array.isArray(t)){const l=t,c=JC(l)?l.flatMap(u=>u.items):l;if(e==null||typeof e!="object"){const u=c.find(p=>p.value===e);return u&&u.label!=null?u.label:o()}if("value"in e){const u=c.find(p=>p&&p.value===e.value);if(u&&u.label!=null)return u.label}}return o()}function sP(e,t,s){return e.reduce((o,l,c)=>(c>0&&o.push(", "),o.push(r.jsx(x.Fragment,{children:tN(l,t,s)},c)),o),[])}const Je={id:Me(e=>e.id),labelId:Me(e=>e.labelId),modal:Me(e=>e.modal),multiple:Me(e=>e.multiple),items:Me(e=>e.items),itemToStringLabel:Me(e=>e.itemToStringLabel),itemToStringValue:Me(e=>e.itemToStringValue),isItemEqualToValue:Me(e=>e.isItemEqualToValue),value:Me(e=>e.value),hasSelectedValue:Me(e=>{const{value:t,multiple:s,itemToStringValue:o}=e;return t==null?!1:s&&Array.isArray(t)?t.length>0:co(t,o)!==""}),hasNullItemLabel:Me((e,t)=>t?nP(e.items):!1),open:Me(e=>e.open),mounted:Me(e=>e.mounted),forceMount:Me(e=>e.forceMount),transitionStatus:Me(e=>e.transitionStatus),openMethod:Me(e=>e.openMethod),activeIndex:Me(e=>e.activeIndex),selectedIndex:Me(e=>e.selectedIndex),isActive:Me((e,t)=>e.activeIndex===t),isSelected:Me((e,t)=>{const s=e.isItemEqualToValue,o=e.value;return e.multiple?Array.isArray(o)&&o.some(l=>wo(t,l,s)):wo(t,o,s)}),isSelectedByFocus:Me((e,t)=>e.selectedIndex===t),popupProps:Me(e=>e.popupProps),triggerProps:Me(e=>e.triggerProps),triggerElement:Me(e=>e.triggerElement),positionerElement:Me(e=>e.positionerElement),listElement:Me(e=>e.listElement),popupSide:Me(e=>e.popupSide),scrollUpArrowVisible:Me(e=>e.scrollUpArrowVisible),scrollDownArrowVisible:Me(e=>e.scrollDownArrowVisible),hasScrollArrows:Me(e=>e.hasScrollArrows)};function aP(e,t,s=(o,l)=>o===l){return e.length===t.length&&e.every((o,l)=>s(o,t[l]))}function mc(e,t=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,s))}const Hs=1;function a_(e,t){return Math.max(0,e-t)}function xf(e,t){if(t<=0)return 0;const s=mc(e,0,t),o=s,l=t-s,c=o<=Hs,u=l<=Hs;return c&&u?o<=l?0:t:c?0:u?t:s}function rP(e){const{id:t,value:s,defaultValue:o=null,onValueChange:l,open:c,defaultOpen:u=!1,onOpenChange:p,name:m,form:g,autoComplete:h,disabled:b=!1,readOnly:v=!1,required:k=!1,modal:N=!0,actionsRef:j,inputRef:y,onOpenChangeComplete:C,items:S,multiple:E=!1,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T=JL,highlightItemOnHover:M=!0,children:z}=e,{clearErrors:B}=Jb(),{setDirty:L,setTouched:U,setFocused:D,validityData:I,setFilled:V,name:$,disabled:q,validation:Y,validationMode:K}=Wc(),F=ip({id:t}),X=q||b,P=$??m,[G,Z]=Vl({controlled:s,default:E?o??Ka:o,name:"Select",state:"value"}),[ee,de]=Vl({controlled:c,default:u,name:"Select",state:"open"}),fe=x.useRef([]),ae=x.useRef([]),oe=x.useRef(null),me=x.useRef(null),Ae=x.useRef(0),ie=x.useRef(null),pe=x.useRef([]),Se=x.useRef(!1),je=x.useRef(null),Be=x.useRef(null),Ve=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),we=x.useRef(!1),{mounted:Ee,setMounted:ve,transitionStatus:Ce}=ti(ee),{openMethod:Le,triggerProps:Pe}=tC(ee),Ie=Xn(()=>new c2({id:F,labelId:void 0,modal:N,multiple:E,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,value:G,open:ee,mounted:Ee,transitionStatus:Ce,items:S,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:{},triggerProps:{},triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1})).current,se=tt(Ie,Je.activeIndex),be=tt(Ie,Je.selectedIndex),$e=tt(Ie,Je.triggerElement),Re=tt(Ie,Je.positionerElement),ze=Z4(Le),We=Le??ze??null,at=x.useMemo(()=>E?"":co(G,A),[E,G,A]),yt=x.useMemo(()=>E&&Array.isArray(G)?G.map(ct=>co(ct,A)):co(G,A),[E,G,A]),_e=cn(Ie.state.triggerElement),Oe=Ue(()=>yt);e_(_e,F,G,Oe,!X,m);const He=x.useRef(G),Xe=E?Array.isArray(G)&&G.length>0:G!=null&&co(G,A)!=="";De(()=>{G!==He.current&&Ie.set("forceMount",!0)},[Ie,G]),De(()=>{V(Xe)},[Xe,V]),De(function(){const zt=pe.current;let mn;if(E){const Sn=Array.isArray(G)?G:[];if(Sn.length===0)mn=null;else{const yn=Sn[Sn.length-1],Ht=kc(zt,yn,T);mn=Ht===-1?null:Ht}}else{const Sn=kc(zt,G,T);mn=Sn===-1?null:Sn}mn===null&&(Be.current=null),!ee&&Ie.set("selectedIndex",mn)},[Xe,E,ee,G,pe,T,Ie,Be]);function rt(ct){const zt=I.initialValue;return Array.isArray(ct)&&Array.isArray(zt)?!aP(ct,zt,(mn,Sn)=>wo(mn,Sn,T)):ct!==zt}Ub(G,()=>{B(P),L(rt(G)),Y.change(G)});const sn=Ue((ct,zt)=>{p?.(ct,zt),!zt.isCanceled&&(de(ct),!ct&&(zt.reason===bo||zt.reason===Vf)&&(U(!0),D(!1),K==="onBlur"&&Y.commit(G)))}),dn=Ue(()=>{ve(!1),Ie.update({activeIndex:null,openMethod:null}),C?.(!1)});ha({enabled:!j,open:ee,ref:oe,onComplete(){ee||dn()}}),x.useImperativeHandle(j,()=>({unmount:dn}),[dn]);const pt=Ue((ct,zt)=>{l?.(ct,zt),!zt.isCanceled&&Z(ct)}),Et=Ue(()=>{const ct=Ie.state.listElement||oe.current;if(!ct)return;const zt=a_(ct.scrollHeight,ct.clientHeight),mn=xf(ct.scrollTop,zt),Sn=mn>0,yn=mn<zt;Ie.state.scrollUpArrowVisible!==Sn&&Ie.set("scrollUpArrowVisible",Sn),Ie.state.scrollDownArrowVisible!==yn&&Ie.set("scrollDownArrowVisible",yn)}),an=b2({open:ee,onOpenChange:sn,elements:{reference:$e,floating:Re}}),Wt=ZS(an,{enabled:!v&&!X,event:"mousedown"}),Zt=Ff(an),Gt=w2(an,{enabled:!v&&!X,listRef:fe,activeIndex:se,selectedIndex:be,disabledIndices:Ka,onNavigate(ct){ct===null&&!ee||Ie.set("activeIndex",ct)},focusItemOnHover:M}),fn=k2(an,{enabled:!v&&!X&&(ee||!E),listRef:ae,activeIndex:se,selectedIndex:be,disabledIndices:ct=>rC(fe.current[ct]),onMatch(ct){ee?Ie.set("activeIndex",ct):pt(pe.current[ct],nt("none"))},onTyping(ct){Se.current=ct}}),es=x.useMemo(()=>{const ct=Fn(fn.reference,Gt.reference,Zt.reference,Wt.reference,Pe);return F&&(ct.id=F),ct},[Wt.reference,fn.reference,Gt.reference,Zt.reference,Pe,F]),ds=x.useMemo(()=>Fn(Xf,fn.floating,Gt.floating,Zt.floating),[fn.floating,Gt.floating,Zt.floating]),js=Gt.item??qt;yb(()=>{Ie.update({popupProps:ds,triggerProps:es})}),De(()=>{Ie.update({id:F,modal:N,multiple:E,value:G,open:ee,mounted:Ee,transitionStatus:Ce,popupProps:ds,triggerProps:es,items:S,itemToStringLabel:R,itemToStringValue:A,isItemEqualToValue:T,openMethod:We})},[Ie,F,N,E,G,ee,Ee,Ce,ds,es,S,R,A,T,We]);const pn=x.useMemo(()=>({store:Ie,name:P,required:k,disabled:X,readOnly:v,multiple:E,highlightItemOnHover:M,setValue:pt,setOpen:sn,listRef:fe,popupRef:oe,scrollHandlerRef:me,handleScrollArrowVisibility:Et,scrollArrowsMountedCountRef:Ae,itemProps:js,valueRef:ie,valuesRef:pe,labelsRef:ae,typingRef:Se,selectionRef:Ve,firstItemTextRef:je,selectedItemTextRef:Be,validation:Y,onOpenChangeComplete:C,alignItemWithTriggerActiveRef:we,initialValueRef:He}),[Ie,P,k,X,v,E,M,pt,sn,js,Y,C,Et]),ws=Xa(y,Y.inputRef),ba=E&&Array.isArray(G)&&G.length>0,Ps=E?void 0:P,_a=x.useMemo(()=>!E||!Array.isArray(G)||!P?null:G.map(ct=>{const zt=co(ct,A);return r.jsx("input",{type:"hidden",form:g,name:P,value:zt,disabled:X},zt)}),[E,G,g,P,A,X]);return r.jsx(QC.Provider,{value:pn,children:r.jsxs(WC.Provider,{value:an,children:[z,r.jsx("input",{...Y.getValidationProps(X,{onFocus(){Ie.state.triggerElement?.focus({focusVisible:!0})},onChange(ct){if(ct.nativeEvent.defaultPrevented||X||v)return;const zt=ct.currentTarget.value,mn=nt(fa,ct.nativeEvent);function Sn(){if(E)return;const yn=zt.toLowerCase();let Ht=pe.current.findIndex(Xs=>co(Xs,A).toLowerCase()===yn||eN(Xs,R).toLowerCase()===yn);Ht===-1&&(Ht=pe.current.findIndex((Xs,ni)=>{const Zc=ae.current[ni];return Zc!=null&&Zc.toLowerCase()===yn}));const zn=Ht===-1?void 0:pe.current[Ht];zn!=null&&pt(zn,mn)}Ie.set("forceMount",!0),queueMicrotask(Sn)}}),id:F&&Ps==null?`${F}-hidden-input`:void 0,form:g,name:Ps,autoComplete:h,value:at,disabled:X,required:k&&!ba,readOnly:v,ref:ws,style:P?SS:lb,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),_a]})})}function oP(e,t){return e??t}const kd=2,lP=400,iP={...rx,...Zb,popupSide:e=>e?{"data-popup-side":e}:null,value:()=>null},cP=x.forwardRef(function(t,s){const{render:o,className:l,id:c,disabled:u=!1,nativeButton:p=!0,style:m,...g}=t,{setTouched:h,setFocused:b,validationMode:v,state:k,disabled:N}=Wc(),{labelId:j}=lp(),{store:y,setOpen:C,selectionRef:S,validation:E,readOnly:R,required:A,alignItemWithTriggerActiveRef:T,disabled:M}=xa(),z=N||M||u,B=tt(y,Je.open),L=tt(y,Je.mounted),U=tt(y,Je.value),D=tt(y,Je.triggerProps),I=tt(y,Je.positionerElement),V=tt(y,Je.listElement),$=tt(y,Je.popupSide),q=tt(y,Je.id),Y=tt(y,Je.labelId),K=tt(y,Je.hasSelectedValue),F=L&&I?$:null,X=c??q,P=oP(j,Y);ip({id:X});const G=cn(I),Z=x.useRef(null),{getButtonProps:ee,buttonRef:de}=Hr({disabled:z,native:p}),fe=Ue(Se=>{y.set("triggerElement",Se)}),ae=kn(),oe=kn(),me=kn();x.useEffect(()=>{if(B)return me.start(lP,()=>{S.current.allowUnselectedMouseUp=!0,S.current.allowSelectedMouseUp=!0}),()=>{me.clear()};S.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},oe.clear()},[B,S,oe,me]);const Ae=Fn(D,{id:X,role:"combobox","aria-expanded":B?"true":"false","aria-haspopup":"listbox","aria-controls":B?V?.id??Zd(I)?.id:void 0,"aria-labelledby":P,"aria-readonly":R||void 0,"aria-required":A||void 0,tabIndex:z?-1:0,onFocus(Se){b(!0),B&&T.current&&C(!1,nt(fa,Se.nativeEvent)),ae.start(0,()=>{y.set("forceMount",!0)})},onBlur(Se){Qe(I,Se.relatedTarget)||(h(!0),b(!1),v==="onBlur"&&E.commit(U))},onMouseDown(Se){if(B)return;const je=mt(Se.currentTarget);function Be(Ve){if(!Z.current)return;const we=Ve.target;if(Qe(Z.current,we)||Qe(G.current,we))return;const Ee=nC(Z.current);Ve.clientX>=Ee.left-kd&&Ve.clientX<=Ee.right+kd&&Ve.clientY>=Ee.top-kd&&Ve.clientY<=Ee.bottom+kd||C(!1,nt(_S,Ve))}oe.start(0,()=>{je.addEventListener("mouseup",Be,{once:!0})})}},g,ee),ie=E.getValidationProps(z,Ae);ie.role="combobox";const pe={...k,open:B,disabled:z,value:U,readOnly:R,popupSide:F,placeholder:!K};return Nt("button",t,{ref:[s,Z,de,fe],state:pe,stateAttributesMapping:iP,props:ie})}),uP={value:()=>null},dP=x.forwardRef(function(t,s){const{className:o,render:l,children:c,placeholder:u,style:p,...m}=t,{store:g,valueRef:h}=xa(),b=tt(g,Je.value),v=tt(g,Je.items),k=tt(g,Je.itemToStringLabel),N=tt(g,Je.hasSelectedValue),j=!N&&u!=null&&c==null,y=tt(g,Je.hasNullItemLabel,j),C={value:b,placeholder:!N};let S=null;return typeof c=="function"?S=c(b):c!=null?S=c:!N&&u!=null&&!y?S=u:Array.isArray(b)?S=sP(b,v,k):S=tN(b,v,k),Nt("span",t,{state:C,ref:[s,h],props:[{children:S},m],stateAttributesMapping:uP})}),fP=x.forwardRef(function(t,s){const{render:o,className:l,style:c,...u}=t,{store:p}=xa(),g={open:tt(p,Je.open)};return Nt("span",t,{state:g,ref:s,props:[{"aria-hidden":!0,children:"▼"},u],stateAttributesMapping:C2})}),pP=x.createContext(void 0),mP=x.forwardRef(function(t,s){const{store:o}=xa(),l=tt(o,Je.mounted),c=tt(o,Je.forceMount);return l||c?r.jsx(pP.Provider,{value:!0,children:r.jsx(hb,{ref:s,...t})}):null}),nN=x.createContext(void 0);function r_(){const e=x.useContext(nN);if(!e)throw new Error(nn(59));return e}function bf(e,t){e&&Object.assign(e.style,t)}const sN={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},gP={position:"fixed"},hP=x.forwardRef(function(t,s){const{anchor:o,positionMethod:l="absolute",className:c,render:u,side:p="bottom",align:m="center",sideOffset:g=0,alignOffset:h=0,collisionBoundary:b="clipping-ancestors",collisionPadding:v,arrowPadding:k=5,sticky:N=!1,disableAnchorTracking:j,alignItemWithTrigger:y=!0,collisionAvoidance:C=qS,style:S,...E}=t,{store:R,listRef:A,labelsRef:T,alignItemWithTriggerActiveRef:M,selectedItemTextRef:z,valuesRef:B,initialValueRef:L,popupRef:U,setValue:D}=xa(),I=ZC(),V=tt(R,Je.open),$=tt(R,Je.mounted),q=tt(R,Je.modal),Y=tt(R,Je.value),K=tt(R,Je.openMethod),F=tt(R,Je.positionerElement),X=tt(R,Je.triggerElement),P=tt(R,Je.isItemEqualToValue),G=tt(R,Je.transitionStatus),Z=x.useRef(null),ee=x.useRef(null),[de,fe]=x.useState(y),ae=$&&de&&K!=="touch";!$&&de!==y&&fe(y),De(()=>{$||(Je.scrollUpArrowVisible(R.state)&&R.set("scrollUpArrowVisible",!1),Je.scrollDownArrowVisible(R.state)&&R.set("scrollDownArrowVisible",!1))},[R,$]),x.useImperativeHandle(M,()=>ae),W2((ae||q)&&V,K==="touch",F,X);const oe=Mb({anchor:o,floatingRootContext:I,positionMethod:l,mounted:$,side:p,sideOffset:g,align:m,alignOffset:h,arrowPadding:k,collisionBoundary:b,collisionPadding:v,sticky:N,disableAnchorTracking:j??ae,collisionAvoidance:C,keepMounted:!0}),me=ae?"none":oe.side,Ae=ae?gP:oe.positionerStyles,ie={open:V,side:me,align:oe.align,anchorHidden:oe.anchorHidden};De(()=>{R.set("popupSide",oe.side)},[R,oe.side]);const pe=Ue(we=>{R.set("positionerElement",we)}),Se=Ob(t,ie,{styles:Ae,transitionStatus:G,props:E,refs:[s,pe],hidden:!$,inert:!V}),je=x.useRef(0),Be=Ue(we=>{if(we.size===0&&je.current===0||B.current.length===0)return;const Ee=je.current;if(je.current=we.size,we.size===Ee)return;const ve=nt(fa);if(Ee!==0&&!R.state.multiple&&Y!==null&&kc(B.current,Y,P)===-1){const Le=L.current,Ie=Le!=null&&kc(B.current,Le,P)!==-1?Le:null;D(Ie,ve),Ie===null&&(R.set("selectedIndex",null),z.current=null)}if(Ee!==0&&R.state.multiple&&Array.isArray(Y)){const Ce=Pe=>kc(B.current,Pe,P)!==-1,Le=Y.filter(Pe=>Ce(Pe));(Le.length!==Y.length||Le.some(Pe=>!eP(Y,Pe,P)))&&(D(Le,ve),Le.length===0&&(R.set("selectedIndex",null),z.current=null))}if(V&&ae){R.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const Ce={height:""};bf(F,Ce),bf(U.current,Ce)}}),Ve=x.useMemo(()=>({...oe,side:me,alignItemWithTriggerActive:ae,setControlledAlignItemWithTrigger:fe,scrollUpArrowRef:Z,scrollDownArrowRef:ee}),[oe,me,ae,fe]);return r.jsx(ap,{elementsRef:A,labelsRef:T,onMapChange:Be,children:r.jsxs(nN.Provider,{value:Ve,children:[$&&q&&r.jsx(Bb,{inert:Jf(!V),cutout:X}),Se]})})}),Sd="base-ui-disable-scrollbar",_x={className:Sd,getElement(e){return r.jsx("style",{nonce:e,href:Sd,precedence:"base-ui:low",children:`.${Sd}{scrollbar-width:none}.${Sd}::-webkit-scrollbar{display:none}`})}},xP=x.createContext(void 0),bP={disableStyleElements:!1};function _P(){return x.useContext(xP)??bP}const vP={...Ro,...Ja},yP=x.forwardRef(function(t,s){const{render:o,className:l,style:c,finalFocus:u,...p}=t,{store:m,popupRef:g,onOpenChangeComplete:h,setOpen:b,valueRef:v,firstItemTextRef:k,selectedItemTextRef:N,multiple:j,handleScrollArrowVisibility:y,scrollHandlerRef:C,listRef:S,highlightItemOnHover:E}=xa(),{side:R,align:A,alignItemWithTriggerActive:T,isPositioned:M,setControlledAlignItemWithTrigger:z}=r_(),B=F2()!=null,L=ZC(),U=Wf(),{nonce:D,disableStyleElements:I}=_P(),V=tt(m,Je.id),$=tt(m,Je.open),q=tt(m,Je.openMethod),Y=tt(m,Je.mounted),K=tt(m,Je.popupProps),F=tt(m,Je.transitionStatus),X=tt(m,Je.triggerElement),P=tt(m,Je.positionerElement),G=tt(m,Je.listElement),Z=x.useRef(!1),ee=x.useRef(!1),de=x.useRef({}),fe=Bl(),ae=Ue(ie=>{if(!P||!g.current||!ee.current)return;if(Z.current||!T){y();return}const pe=P.style.top==="0px",Se=P.style.bottom==="0px";if(!pe&&!Se){y();return}const je=Xj(P),Be=gc(P.getBoundingClientRect().height,"y",je),Ve=mt(P),we=$t(P),Ee=we.getComputedStyle(P),ve=parseFloat(Ee.marginTop),Ce=parseFloat(Ee.marginBottom),Le=Kj(we.getComputedStyle(g.current)),Pe=Math.min(Ve.documentElement.clientHeight-ve-Ce,Le),Ie=ie.scrollTop,se=Cd(ie);let be=0,$e=null,Re=!1,ze=!1;const We=Oe=>{P.style.height=`${Oe}px`},at=(Oe,He)=>{const Xe=mc(Oe,0,Pe-Be);Xe>0&&We(Be+Xe),ie.scrollTop=He,Pe-(Be+Xe)<=Hs&&(Z.current=!0),y()},yt=pe?se-Ie:Ie,_e=Math.min(Be+yt,Pe);if(be=_e,yt<=Hs){at(yt,pe?se:0);return}if(Pe-_e>Hs)pe?ze=!0:$e=0;else if(Re=!0,Se&&Ie<se){const Oe=Be+yt-Pe;$e=Ie-(yt-Oe)}if(be=Math.ceil(be),be!==0&&We(be),ze||$e!=null){const Oe=Cd(ie),He=ze?Oe:mc($e,0,Oe);Math.abs(ie.scrollTop-He)>Hs&&(ie.scrollTop=He)}(Re||be>=Pe-Hs)&&(Z.current=!0),y()});x.useImperativeHandle(C,()=>ae,[ae]),ha({open:$,ref:g,onComplete(){$&&h?.(!0)}});const oe={open:$,transitionStatus:F,side:R,align:A};De(()=>{!P||!g.current||Object.keys(de.current).length||(de.current={top:P.style.top||"0",left:P.style.left||"0",right:P.style.right,height:P.style.height,bottom:P.style.bottom,minHeight:P.style.minHeight,maxHeight:P.style.maxHeight,marginTop:P.style.marginTop,marginBottom:P.style.marginBottom})},[g,P]),De(()=>{$||T||(ee.current=!1,Z.current=!1,bf(P,de.current))},[$,T,P,g]),De(()=>{const ie=g.current;if(!$||!X||!P||!ie||T&&!M||m.state.transitionStatus==="ending")return;if(!T){ee.current=!0,fe.request(y),ie.style.removeProperty("--transform-origin");return}const pe=jP(ie);ie.style.removeProperty("--transform-origin");try{let Se=N.current;Se?.isConnected||(Se=!Je.hasSelectedValue(m.state)&&k.current?.isConnected?k.current:null);const je=v.current,Be=$t(P),Ve=Be.getComputedStyle(P),we=Be.getComputedStyle(ie),Ee=mt(X),ve=Xj(X),Ce=Nd(X.getBoundingClientRect(),ve),Le=Nd(P.getBoundingClientRect(),ve),Pe=Ce.height,Ie=G||ie,se=Ie.scrollHeight,be=parseFloat(we.borderBottomWidth),$e=parseFloat(Ve.marginTop)||10,Re=parseFloat(Ve.marginBottom)||10,ze=parseFloat(Ve.minHeight)||100,We=Kj(we),at=5,yt=5,_e=20,Oe=Ee.documentElement.clientHeight-$e-Re,He=Ee.documentElement.clientWidth,Xe=Oe-Ce.bottom+Pe;let rt,sn=U==="rtl"?Ce.right-Le.width:Ce.left,dn=0;if(Se&&je){const pn=Nd(je.getBoundingClientRect(),ve);rt=Nd(Se.getBoundingClientRect(),ve),sn=Le.left+(U==="rtl"?pn.right-rt.right:pn.left-rt.left);const ws=pn.top-Ce.top+pn.height/2;dn=rt.top-Le.top+rt.height/2-ws}const pt=Xe+dn+Re+be;let Et=Math.min(Oe,pt);const an=Oe-$e-Re,Wt=pt-Et,Zt=He-yt;P.style.left=`${mc(sn,at,Zt-Le.width)}px`,P.style.height=`${Et}px`,P.style.maxHeight="none",P.style.marginTop=`${$e}px`,P.style.marginBottom=`${Re}px`,ie.style.height="100%";const Gt=Cd(Ie),fn=Wt>=Gt-Hs;fn&&(Et=Math.min(Oe,Le.height)-(Wt-Gt));const es=Ce.top<_e||Ce.bottom>Oe-_e||Math.ceil(Et)+Hs<Math.min(se,ze),ds=(Be.visualViewport?.scale??1)!==1&&Dr;if(es||ds){ee.current=!0,bf(P,de.current),z(!1);return}const js=Math.max(ze,Et);if(fn){const pn=Math.max(0,Oe-pt);P.style.top=Le.height>=an?"0":`${pn}px`,P.style.height=`${Et}px`,Ie.scrollTop=Cd(Ie)}else P.style.bottom="0",Ie.scrollTop=Wt;if(rt){const pn=Le.top,ws=Le.height,ba=rt.top+rt.height/2,Ps=ws>0?(ba-pn)/ws*100:50,_a=mc(Ps,0,100);ie.style.setProperty("--transform-origin",`50% ${_a}%`)}(js===Oe||Et>=We)&&(Z.current=!0),y(),E&&m.state.selectedIndex===null&&m.state.activeIndex===null&&S.current[0]!=null&&m.set("activeIndex",0),ee.current=!0}finally{pe()}},[m,$,P,X,v,k,N,g,y,T,z,fe,G,S,E,U,M]),x.useEffect(()=>{if(!T||!P||!$)return;const ie=$t(P);function pe(Se){b(!1,nt(i5,Se))}return ht(ie,"resize",pe)},[b,T,P,$]);const me={...G?{role:"presentation","aria-orientation":void 0}:{role:"listbox","aria-multiselectable":j||void 0,id:`${V}-list`},onKeyDown(ie){B&&sp.has(ie.key)&&ie.stopPropagation()},onScroll(ie){G||ae(ie.currentTarget)},...T&&{style:G?{height:"100%"}:sN}},Ae=Nt("div",t,{ref:[s,g],state:oe,stateAttributesMapping:vP,props:[K,me,Zf(F),{className:!G&&T?_x.className:void 0},p]});return r.jsxs(x.Fragment,{children:[!I&&_x.getElement(D),r.jsx(_b,{context:L,modal:!1,disabled:!Y,openInteractionType:q,returnFocus:u,restoreFocus:!0,children:Ae})]})});function Kj(e){const t=e.maxHeight||"";return t.endsWith("px")&&parseFloat(t)||1/0}function Cd(e){return a_(e.scrollHeight,e.clientHeight)}function Xj(e){return r2.getScale(e)}function gc(e,t,s){return e/s[t]}function Nd(e,t){return Oc({x:gc(e.x,"x",t),y:gc(e.y,"y",t),width:gc(e.width,"x",t),height:gc(e.height,"y",t)})}const Qj=[["transform","none"],["scale","1"],["translate","0 0"]];function jP(e){const{style:t}=e,s={};for(const[o,l]of Qj)s[o]=t.getPropertyValue(o),t.setProperty(o,l,"important");return()=>{for(const[o]of Qj){const l=s[o];l?t.setProperty(o,l):t.removeProperty(o)}}}const wP=x.forwardRef(function(t,s){const{render:o,className:l,style:c,...u}=t,{store:p,scrollHandlerRef:m}=xa(),{alignItemWithTriggerActive:g}=r_(),h=tt(p,Je.hasScrollArrows),b=tt(p,Je.openMethod),v=tt(p,Je.multiple),N={id:`${tt(p,Je.id)}-list`,role:"listbox","aria-multiselectable":v||void 0,onScroll(y){m.current?.(y.currentTarget)},...g&&{style:sN},className:h&&b!=="touch"?_x.className:void 0},j=Ue(y=>{p.set("listElement",y)});return Nt("div",t,{ref:[s,j],props:[N,u]})}),aN=x.createContext(void 0);function o_(){const e=x.useContext(aN);if(!e)throw new Error(nn(57));return e}const kP=x.memo(x.forwardRef(function(t,s){const{render:o,className:l,style:c,value:u=null,label:p,disabled:m=!1,nativeButton:g=!1,...h}=t,b=x.useRef(null),v=Gc({label:p,textRef:b,indexGuessBehavior:q2.GuessFromOrder}),{store:k,itemProps:N,setOpen:j,setValue:y,selectionRef:C,typingRef:S,valuesRef:E,multiple:R,selectedItemTextRef:A,disabled:T,readOnly:M}=xa(),z=tt(k,Je.isActive,v.index),B=tt(k,Je.open),L=tt(k,Je.isSelected,u),U=tt(k,Je.isSelectedByFocus,v.index),D=tt(k,Je.isItemEqualToValue),I=v.index,V=I!==-1,$=x.useRef(null);De(()=>{if(!V)return;const ae=E.current;return ae[I]=u,()=>{delete ae[I]}},[V,I,u,E]),De(()=>{if(!V)return;const ae=k.state.value;let oe=ae;R&&Array.isArray(ae)&&(oe=ae.length>0?ae[ae.length-1]:void 0),oe!==void 0&&wo(u,oe,D)&&(k.set("selectedIndex",I),b.current&&(A.current=b.current))},[V,I,R,D,k,u,A]);const q=x.useRef(null),Y=x.useRef("mouse"),K=x.useRef(!1),{getButtonProps:F,buttonRef:X}=Hr({disabled:m,focusableWhenDisabled:!0,native:g,composite:!0}),P={disabled:m,selected:L,highlighted:z};function G(ae){if(T||M)return;const oe=k.state.value;if(R){const me=Array.isArray(oe)?oe:[],Ae=L?tP(me,u,D):[...me,u];y(Ae,nt(El,ae))}else y(u,nt(El,ae)),j(!1,nt(El,ae))}function Z(){C.current.dragY=0}const ee={role:"option","aria-selected":L,tabIndex:B&&z?0:-1,onKeyDown(ae){q.current=ae.key,k.set("activeIndex",I),ae.key===" "&&S.current&&ae.preventDefault()},onClick(ae){const oe=ae.type==="click"&&Y.current!=="touch",me=ae.nativeEvent.pointerType,Ae=oe&&eb(ae.nativeEvent)&&(me!==void 0||z),ie=oe&&!Ae&&!K.current;K.current=!1,!(ae.type==="keydown"&&q.current===null)&&(m||ae.type==="keydown"&&q.current===" "&&S.current||ie||(q.current=null,G(ae.nativeEvent)))},onPointerEnter(ae){Y.current=ae.pointerType},onPointerMove(ae){if(ae.pointerType==="mouse"&&ae.buttons===1){const oe=C.current;oe.dragY+=ae.movementY,oe.dragY**2>=64&&(oe.allowUnselectedMouseUp=!0)}},onPointerDown(ae){Y.current=ae.pointerType,K.current=!0,Z()},onMouseUp(){if(Z(),m||Y.current==="touch"||K.current)return;const ae=!C.current.allowSelectedMouseUp&&L,oe=!C.current.allowUnselectedMouseUp&&!L;ae||oe||(K.current=!0,$.current?.click(),K.current=!1)}},de=Nt("div",t,{ref:[X,s,v.ref,$],state:P,props:[N,ee,h,F]}),fe=x.useMemo(()=>({selected:L,index:I,textRef:b,selectedByFocus:U,hasRegistered:V}),[L,I,b,U,V]);return r.jsx(aN.Provider,{value:fe,children:de})})),SP=x.forwardRef(function(t,s){const o=t.keepMounted??!1,{selected:l}=o_();return o||l?r.jsx(CP,{...t,ref:s}):null}),CP=x.memo(x.forwardRef((e,t)=>{const{render:s,className:o,style:l,keepMounted:c,...u}=e,{selected:p}=o_(),m=x.useRef(null),{transitionStatus:g,setMounted:h}=ti(p),v=Nt("span",e,{ref:[t,m],state:{selected:p,transitionStatus:g},props:[{"aria-hidden":!0,children:"✔️"},u],stateAttributesMapping:Ja});return ha({open:p,ref:m,onComplete(){p||h(!1)}}),v})),NP=x.memo(x.forwardRef(function(t,s){const{index:o,textRef:l,selectedByFocus:c,hasRegistered:u}=o_(),{firstItemTextRef:p,selectedItemTextRef:m}=xa(),{render:g,className:h,style:b,...v}=t,k=x.useCallback(j=>{j&&(u&&o===0&&(p.current=j),u&&c&&(m.current=j))},[p,m,o,c,u]);return Nt("div",t,{ref:[k,s,l],props:v})})),rN=x.forwardRef(function(t,s){const{render:o,className:l,style:c,direction:u,keepMounted:p=!1,...m}=t,g=u==="up",{store:h,popupRef:b,listRef:v,handleScrollArrowVisibility:k,scrollArrowsMountedCountRef:N}=xa(),{side:j,scrollDownArrowRef:y,scrollUpArrowRef:C}=r_(),S=g?Je.scrollUpArrowVisible:Je.scrollDownArrowVisible,E=tt(h,S),R=tt(h,Je.openMethod),A=E&&R!=="touch",T=kn(),M=g?C:y,{mounted:z,transitionStatus:B,setMounted:L}=ti(A);De(()=>(N.current+=1,h.state.hasScrollArrows||h.set("hasScrollArrows",!0),()=>{N.current=Math.max(0,N.current-1),N.current===0&&h.state.hasScrollArrows&&h.set("hasScrollArrows",!1)}),[h,N]),ha({open:A,ref:M,onComplete(){A||L(!1)}});const I=Nt("div",t,{ref:[s,M],state:{direction:u,visible:A,side:j,transitionStatus:B},props:[{"aria-hidden":!0,children:g?"▲":"▼",style:{position:"absolute"},onMouseMove($){if($.movementX===0&&$.movementY===0||T.isStarted())return;h.set("activeIndex",null);function q(){const Y=h.state.listElement??b.current;if(!Y)return;h.set("activeIndex",null),k();const K=a_(Y.scrollHeight,Y.clientHeight),F=xf(Y.scrollTop,K),X=F===(g?0:K),P=v.current;if(F!==Y.scrollTop&&(Y.scrollTop=F),P.length===0&&h.set(g?"scrollUpArrowVisible":"scrollDownArrowVisible",!X),X){T.clear();return}if(P.length>0){const G=M.current?.offsetHeight||0;Y.scrollTop=EP(P,g,F,Y.clientHeight,G,K)}T.start(40,q)}T.start(40,q)},onMouseLeave(){T.clear()}},m],stateAttributesMapping:Ja});return z||p?I:null});function EP(e,t,s,o,l,c){if(t){let h=0;const b=s+l-Hs;for(let N=0;N<e.length;N+=1){const j=e[N];if(j&&j.offsetTop>=b){h=N;break}}const v=Math.max(0,h-1),k=e[v];return v<h&&k?xf(k.offsetTop-l,c):0}let u=e.length-1;const p=s+o-l+Hs;for(let h=0;h<e.length;h+=1){const b=e[h];if(b&&b.offsetTop+b.offsetHeight>p){u=Math.max(0,h-1);break}}const m=Math.min(e.length-1,u+1),g=e[m];return m>u&&g?xf(g.offsetTop+g.offsetHeight-o+l,c):c}const RP=x.forwardRef(function(t,s){return r.jsx(rN,{...t,ref:s,direction:"down"})}),TP=x.forwardRef(function(t,s){return r.jsx(rN,{...t,ref:s,direction:"up"})}),AP=rP;function MP({className:e,...t}){return r.jsx(dP,{"data-slot":"select-value",className:St("flex flex-1 text-left",e),...t})}function OP({className:e,size:t="default",children:s,...o}){return r.jsxs(cP,{"data-slot":"select-trigger","data-size":t,className:St("flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[s,r.jsx(fP,{render:r.jsx(pa,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function zP({className:e,children:t,side:s="bottom",sideOffset:o=4,align:l="center",alignOffset:c=0,alignItemWithTrigger:u=!0,...p}){return r.jsx(mP,{children:r.jsx(hP,{side:s,sideOffset:o,align:l,alignOffset:c,alignItemWithTrigger:u,className:"isolate z-50",children:r.jsxs(yP,{"data-slot":"select-content","data-align-trigger":u,className:St("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...p,children:[r.jsx(LP,{}),r.jsx(wP,{children:t}),r.jsx(PP,{})]})})})}function DP({className:e,children:t,...s}){return r.jsxs(kP,{"data-slot":"select-item",className:St("relative flex w-full cursor-default items-center gap-2 rounded-md py-2 pr-8 pl-2.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...s,children:[r.jsx(NP,{className:"flex min-w-0 flex-1 gap-2 overflow-hidden whitespace-nowrap",children:t}),r.jsx(SP,{render:r.jsx("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:r.jsx(ho,{className:"pointer-events-none"})})]})}function LP({className:e,...t}){return r.jsx(TP,{"data-slot":"select-scroll-up-button",className:St("top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:r.jsx(Gk,{})})}function PP({className:e,...t}){return r.jsx(RP,{"data-slot":"select-scroll-down-button",className:St("bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:r.jsx(pa,{})})}function bt({value:e,onChange:t,options:s,placeholder:o="— elegir —",disabled:l,className:c,showIcon:u=!1}){return r.jsxs(AP,{value:e,onValueChange:p=>t(p??""),disabled:l,children:[r.jsx(OP,{className:Te("h-9 w-full",c),children:r.jsx(MP,{placeholder:o,children:p=>{const m=s.find(h=>h.value===p),g=u?m?.icon:void 0;return r.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[g&&r.jsx(g,{className:"size-3.5 shrink-0"}),r.jsx("span",{className:"truncate",children:m?.label??p})]})}})}),r.jsx(zP,{side:"bottom",sideOffset:6,align:"start",alignItemWithTrigger:!1,className:"w-[var(--anchor-width)] p-1.5",children:s.map(p=>{const m=p.icon;return r.jsx(DP,{value:p.value,disabled:p.disabled,children:r.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[m?r.jsx(m,{className:"size-4 shrink-0 text-muted-fg"}):null,p.description?r.jsxs("span",{className:"flex min-w-0 flex-col leading-tight",children:[r.jsx("span",{className:"truncate font-medium",children:p.label}),r.jsx("span",{className:"truncate text-[11px] text-muted-fg",children:p.description})]}):r.jsx("span",{className:"truncate",children:p.label})]})},p.value)})})]})}const Wj=320;function IP(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function BP(e){return e.agent_slug||e.actor_id||e.author||e.actor_kind||"—"}function UP({m:e}){const[t,s]=x.useState(!1),o=(e.body?.length||0)>Wj,l=!o||t?e.body:`${e.body.slice(0,Wj)}…`;return r.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsx("span",{className:"mt-0.5 shrink-0",children:e.direction==="in"?r.jsx(qk,{size:14,className:"text-blue-400"}):r.jsx(Fk,{size:14,className:"text-emerald-400"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[r.jsx("span",{className:"font-mono",children:IP(e.ts)}),r.jsx(Fe,{tone:"info",children:e.channel}),e.type&&r.jsx(Fe,{children:e.type}),r.jsx("span",{className:"font-medium text-foreground",children:BP(e)})]}),e.body&&r.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words text-xs",children:l}),o&&r.jsx("button",{type:"button",onClick:()=>s(c=>!c),className:"mt-1 text-[11px] font-medium text-sky-400 hover:underline",children:f(t?"logs.show_less":"logs.show_more")})]})]})}function HP(){const[e,t]=x.useState(!1),s=et(e?"/admin/logs?errors":null,()=>$l.logs("errors",200)),o=s.data?.entries||[];return r.jsxs("details",{className:"mb-3 rounded-lg border border-border bg-muted/20",onToggle:l=>t(l.target.open),children:[r.jsxs("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted-fg",children:[f("logs.daemon_errors"),o.length?` · ${o.length}`:""]}),r.jsxs("div",{className:"border-t border-border p-3",children:[s.isLoading&&r.jsx(ot,{}),e&&!s.isLoading&&o.length===0&&r.jsx("p",{className:"text-xs text-muted-fg",children:f("logs.no_errors")}),r.jsx("ul",{className:"space-y-1",children:o.map((l,c)=>r.jsxs("li",{className:"rounded-md bg-card px-2 py-1 text-[11px]",children:[r.jsxs("div",{className:"flex items-center gap-2 text-muted-fg",children:[typeof l.ts=="string"&&r.jsx("span",{className:"font-mono",children:new Date(l.ts).toLocaleString()}),typeof l.level=="string"&&r.jsx("span",{className:"text-destructive",children:l.level})]}),r.jsx("p",{className:"whitespace-pre-wrap break-words font-mono",children:String(l.msg??l.message??l.error??l.raw??JSON.stringify(l)).slice(0,500)})]},c))})]})]})}function VP({pid:e}){const t=!e||String(e)==="0",[s,o]=x.useState(""),[l,c]=x.useState(""),[u,p]=x.useState(""),[m,g]=x.useState(""),h=s.trim()||void 0,b=t?`/messages/global?channel=${h??""}`:`/projects/${e}/messages?channel=${h??""}`,v=et(b,()=>t?pf.global({channel:h,limit:300}):pf.project(e,{channel:h,limit:300})),k=x.useMemo(()=>[...v.data||[]].sort((y,C)=>(C.ts||"").localeCompare(y.ts||"")),[v.data]),N=x.useMemo(()=>Array.from(new Set(k.map(y=>y.type).filter(Boolean))),[k]),j=x.useMemo(()=>k.filter(y=>!(l&&y.direction!==l||u&&y.type!==u||m&&!(y.body||"").toLowerCase().includes(m.toLowerCase()))),[k,l,u,m]);return r.jsxs(Ke,{title:f("logs.title"),description:f(t?"logs.desc_global":"logs.desc_project"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ne,{placeholder:f("logs.filter_channel"),value:s,onChange:y=>o(y.target.value),className:"w-44"}),r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>v.mutate(),children:r.jsx(ua,{size:13})})]}),children:[t&&r.jsx(HP,{}),r.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[r.jsx("div",{className:"w-36",children:r.jsx(bt,{value:l,onChange:c,placeholder:f("logs.filter_dir"),options:[{value:"",label:f("logs.all_directions")},{value:"in",label:f("logs.in")},{value:"out",label:f("logs.out")}]})}),r.jsx("div",{className:"w-40",children:r.jsx(bt,{value:u,onChange:p,placeholder:f("logs.filter_type"),options:[{value:"",label:f("logs.all_types")},...N.map(y=>({value:y,label:y}))]})}),r.jsx(Ne,{placeholder:f("logs.search_text"),value:m,onChange:y=>g(y.target.value),className:"w-56"}),r.jsxs("span",{className:"text-[11px] text-muted-fg",children:[j.length," ",f("logs.count_of")," ",k.length]})]}),v.isLoading&&r.jsx(ot,{}),v.error&&r.jsx(xt,{children:f("logs.error",{msg:v.error.message})}),!v.isLoading&&!v.error&&j.length===0&&r.jsx(xt,{children:h?f("logs.no_activity_ch",{ch:h}):f("logs.no_activity")}),r.jsx("ul",{className:"space-y-1 text-sm",children:j.map((y,C)=>r.jsx(UP,{m:y},`${y.ts}-${C}`))})]})}function oN({value:e,onChange:t,options:s,placeholder:o=f("shared_ui.model_combobox_ph"),invalid:l,invalidHint:c,className:u}){const[p,m]=x.useState(!1),[g,h]=x.useState(e),b=x.useRef(null),v=x.useRef(null),[k,N]=x.useState(null);x.useEffect(()=>{h(e)},[e]),x.useLayoutEffect(()=>{if(!p)return;const E=()=>{const R=b.current;if(!R)return;const A=R.getBoundingClientRect();N({top:A.bottom+4,left:A.left,width:A.width})};return E(),window.addEventListener("scroll",E,!0),window.addEventListener("resize",E),()=>{window.removeEventListener("scroll",E,!0),window.removeEventListener("resize",E)}},[p]),x.useEffect(()=>{if(!p)return;const E=R=>{const A=R.target;b.current?.contains(A)||v.current?.contains(A)||m(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[p]);const j=g.trim().toLowerCase(),C=j&&!(g===e)?s.filter(E=>E.toLowerCase().includes(j)):s,S=E=>{t(E),h(E),m(!1)};return r.jsxs("div",{ref:b,className:Te("relative",u),children:[r.jsxs("div",{className:Te("flex items-center gap-1 rounded-lg border bg-background px-2.5 transition-colors focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",l?"border-amber-500/60":"border-border"),children:[l&&r.jsx(Ye,{content:c||f("models_ui.invalid_hint"),children:r.jsx("span",{children:r.jsx(sS,{className:"size-3.5 shrink-0 text-amber-400"})})}),r.jsx("input",{value:g,placeholder:o,onChange:E=>{h(E.target.value),t(E.target.value),m(!0)},onFocus:()=>m(!0),className:"w-full bg-transparent py-1.5 text-sm outline-none placeholder:text-muted-fg/60"}),r.jsx("button",{type:"button",tabIndex:-1,onClick:()=>m(E=>!E),className:"shrink-0 text-muted-fg hover:text-foreground",children:r.jsx(pa,{className:"size-4"})})]}),p&&C.length>0&&k&&qs.createPortal(r.jsx("ul",{ref:v,style:{position:"fixed",top:k.top,left:k.left,width:k.width},className:"z-[1000] max-h-56 overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-md ring-1 ring-foreground/10",children:C.map(E=>r.jsx("li",{children:r.jsx("button",{type:"button",onMouseDown:R=>{R.preventDefault(),S(E)},className:Te("flex w-full items-center rounded-md px-2 py-1 text-left text-sm hover:bg-accent hover:text-accent-fg",E===e&&"bg-accent/50"),children:r.jsx("span",{className:"truncate font-mono text-xs",children:E})})},E))}),document.body)]})}function Vr(){const{data:e,error:t,isLoading:s,mutate:o}=et("/admin/config",()=>$l.config.get()),l=async(c,u)=>{const p=await $l.config.patch({set:c,unset:u});return await o({config:p.config},{revalidate:!1}),p.config};return{config:e?.config||{},error:t,isLoading:s,mutate:o,patch:l}}function lN(){const{data:e,error:t,isLoading:s,mutate:o}=et("/admin/super-agent",()=>$l.superAgent());return{superAgent:e,error:t,isLoading:s,mutate:o}}const qP={anthropic:"from-orange-600 to-amber-600",openai:"from-emerald-600 to-teal-600",gemini:"from-blue-600 to-indigo-600",groq:"from-cyan-600 to-teal-600",openrouter:"from-violet-600 to-indigo-600",ollama:"from-amber-600 to-orange-600",azure:"from-blue-600 to-cyan-600",mock:"from-slate-600 to-gray-600",custom:"from-slate-600 to-gray-600"},$P={anthropic:"bg-orange-500/20 text-orange-300 border border-orange-500/40",openai:"bg-emerald-500/20 text-emerald-300 border border-emerald-500/40",gemini:"bg-blue-500/20 text-blue-300 border border-blue-500/40",groq:"bg-cyan-500/20 text-cyan-300 border border-cyan-500/40",openrouter:"bg-violet-500/20 text-violet-300 border border-violet-500/40",ollama:"bg-amber-500/20 text-amber-300 border border-amber-500/40",azure:"bg-blue-500/20 text-blue-300 border border-blue-500/40",mock:"bg-slate-500/20 text-slate-300 border border-slate-500/40",custom:"bg-slate-500/20 text-slate-300 border border-slate-500/40"},Sc=[{value:"anthropic",label:"Anthropic"},{value:"openai",label:"OpenAI-compatible"},{value:"gemini",label:"Gemini"},{value:"groq",label:"Groq"},{value:"openrouter",label:"OpenRouter"},{value:"ollama",label:"Ollama"},{value:"azure",label:"Azure OpenAI"},{value:"mock",label:"Mock (test)"},{value:"custom",label:"Custom"}];function nh(e,t){return t&&t in e?e[t]:e.custom}const _f={anthropic:ma,openai:un,gemini:TM,groq:Ll,openrouter:Hx,ollama:tS,azure:gM,mock:Xk,custom:Zl},mo={anthropic:{base_url:"",default_model:"claude-sonnet-4.6",api_key_env:"ANTHROPIC_API_KEY",known_models:["claude-opus-4.8","claude-opus-4.7","claude-opus-4.6","claude-sonnet-4.6","claude-sonnet-4.5","claude-haiku-4.5"]},openai:{base_url:"https://api.openai.com/v1",default_model:"gpt-4o-mini",api_key_env:"OPENAI_API_KEY",known_models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},gemini:{base_url:"https://generativelanguage.googleapis.com/v1beta/openai",default_model:"gemini-2.5-flash",api_key_env:"GEMINI_API_KEY",known_models:["gemini-3.5-pro","gemini-3.5-flash","gemini-3.1-pro","gemini-3.1-flash","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"]},groq:{base_url:"https://api.groq.com/openai/v1",default_model:"llama-3.3-70b-versatile",api_key_env:"GROQ_API_KEY",known_models:["llama-3.3-70b-versatile","llama-3.1-8b-instant","meta-llama/llama-4-scout-17b-16e-instruct","openai/gpt-oss-120b","openai/gpt-oss-20b","groq/compound","groq/compound-mini","qwen/qwen3-32b","whisper-large-v3-turbo"]},openrouter:{base_url:"https://openrouter.ai/api/v1",default_model:"openrouter/auto",api_key_env:"OPENROUTER_API_KEY",known_models:["openrouter/auto","openrouter/free","deepseek/deepseek-r1:free","meta-llama/llama-3.3-70b-instruct:free","google/gemini-2.0-flash-exp:free","qwen/qwen3-235b-a22b:free","anthropic/claude-sonnet-4.5","openai/gpt-4o-mini"]},ollama:{base_url:"http://127.0.0.1:11434",default_model:"gemma2:9b",api_key_env:"",known_models:[]},azure:{base_url:"",default_model:"gpt-4o-mini",api_key_env:"AZURE_OPENAI_API_KEY",known_models:["gpt-4o","gpt-4o-mini"]},mock:{base_url:"",default_model:"mock",api_key_env:"",known_models:["mock"]},custom:{base_url:"",default_model:"",api_key_env:"",known_models:[]}};function iN(e){const t=e.indexOf(":");return t<0?{provider:e,model:""}:{provider:e.slice(0,t),model:e.slice(t+1)}}function sh({value:e,onChange:t,providers:s}){const{provider:o,model:l}=iN(e),c=s.find(h=>h.slug===o),u=!!o&&!c,p=x.useMemo(()=>{const h=c?mo[c.engine]?.known_models||[]:[];return Array.from(new Set([...c?.default_model?[c.default_model]:[],...h]))},[c]),m=h=>{const b=s.find(k=>k.slug===h),v=b?.default_model||mo[b?.engine]?.default_model||"";t(v?`${h}:${v}`:`${h}:`)},g=h=>t(`${o}:${h}`);return r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsx(bt,{value:o,onChange:m,placeholder:u?f("router_panel.provider_not_found",{name:o}):f("router_panel.provider_ph"),options:s.map(h=>({value:h.slug,label:h.slug,icon:_f[h.engine]}))}),r.jsx(oN,{value:l,onChange:g,options:p,invalid:u,invalidHint:f("router_panel.provider_not_configured",{name:o})})]})}function FP(){const e=lt(),{superAgent:t,isLoading:s,mutate:o}=lN(),{config:l,patch:c}=Vr(),[u,p]=x.useState(""),[m,g]=x.useState([]),[h,b]=x.useState(""),[v,k]=x.useState(null),[N,j]=x.useState(!1),[y,C]=x.useState({model:"",fallback:[]});x.useEffect(()=>{if(!t)return;const L=t.model_fallback?.models||[],U=Array.isArray(L)?L:[];p(t.model||""),g(U),C({model:t.model||"",fallback:U})},[t]);const S=x.useMemo(()=>{const L=l.engines||{};return Object.entries(L).map(([U,D])=>({slug:U,engine:D?.engine||U,default_model:D?.default_model||mo[D?.engine||U]?.default_model}))},[l.engines]),E=L=>{const{provider:U}=iN(L);return S.some(D=>D.slug===U)};if(s||!t)return r.jsx(ot,{});const R=u!==y.model||JSON.stringify(m)!==JSON.stringify(y.fallback),A=async()=>{j(!0);try{await c({"super_agent.model":u,"super_agent.model_fallback.enabled":m.length>0,"super_agent.model_fallback.models":m}),e.success(f("router_panel.saved_toast")),C({model:u,fallback:m}),o()}catch(L){e.error(L.message)}finally{j(!1)}},T=()=>{const L=h.trim().replace(/:$/,"");!L||!L.includes(":")||m.includes(L)||(g([...m,L]),b(""))},M=(L,U)=>{const D=[...m];D[L]=U,g(D)},z=L=>{g(m.filter((U,D)=>D!==L)),v===L&&k(null)},B=(L,U)=>{const D=L+U;if(D<0||D>=m.length)return;const I=[...m];[I[L],I[D]]=[I[D],I[L]],g(I)};return r.jsx(Ke,{title:f("router_panel.title"),description:f("router_panel.description"),children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/20 p-3",children:[r.jsxs(Fe,{tone:"success",children:[r.jsx(Hx,{size:11})," ",f("router_panel.badge_default")]}),r.jsx("span",{className:`font-mono text-xs ${!E(u)&&u?"text-amber-400":""}`,children:u||"—"}),m.map(L=>r.jsxs("span",{className:"flex items-center gap-2 text-muted-fg",children:[r.jsx($k,{size:12}),r.jsx("span",{className:`font-mono text-xs ${E(L)?"":"text-amber-400"}`,children:L})]},L))]}),S.length===0?r.jsx("p",{className:"text-xs text-muted-fg",children:f("router_panel.no_providers")}):r.jsx(le,{label:f("router_panel.active_model_label"),hint:f("router_panel.active_model_hint"),children:r.jsx(sh,{value:u,onChange:p,providers:S})}),r.jsxs("div",{className:"rounded-lg border border-border bg-muted/20 p-3",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("div",{className:"text-sm font-medium",children:f("router_panel.fallback_title")}),r.jsx("div",{className:"text-xs text-muted-fg",children:f("router_panel.fallback_desc")})]}),r.jsxs("ul",{className:"mb-3 space-y-1",children:[m.map((L,U)=>{const D=!E(L),I=v===U;return r.jsx("li",{className:"rounded-md bg-card px-2 py-1.5 text-xs",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"w-6 text-muted-fg",children:["#",U+1]}),I?r.jsx("div",{className:"flex-1",children:r.jsx(sh,{value:L,onChange:V=>M(U,V),providers:S})}):r.jsxs("button",{type:"button",onClick:()=>k(U),className:"flex flex-1 items-center gap-1.5 text-left",children:[D&&r.jsx(sS,{size:12,className:"text-amber-400"}),r.jsx("span",{className:`font-mono ${D?"text-amber-400":""}`,children:L})]}),I?r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>k(null),children:f("router_panel.done")}):r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>k(U),children:r.jsx(Eo,{size:12})}),r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>B(U,-1),disabled:U===0,children:"↑"}),r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>B(U,1),disabled:U===m.length-1,children:"↓"}),r.jsx(ce,{size:"sm",variant:"destructive",onClick:()=>z(U),children:r.jsx(Zn,{size:12})})]})},`${U}-${L}`)}),m.length===0&&r.jsx("li",{className:"text-xs text-muted-fg",children:f("router_panel.fallback_empty")})]}),S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"text-xs text-muted-fg",children:f("router_panel.add_to_chain")}),r.jsx(sh,{value:h,onChange:b,providers:S}),r.jsxs(ce,{size:"sm",variant:"secondary",onClick:T,disabled:!h.includes(":")||h.endsWith(":"),children:[r.jsx(tn,{size:13})," ",f("router_panel.add_to_chain")]})]})]}),r.jsx(ce,{variant:"primary",loading:N,disabled:!R,onClick:A,children:f(R?"router_panel.save":"router_panel.saved")})]})})}function GP({provider:e,onEdit:t,onDelete:s,onToggle:o}){const l=nh(qP,e.engine),c=nh($P,e.engine),u=nh(_f,e.engine),p=Sc.find(b=>b.value===e.engine)?.label||e.engine,m=typeof e.api_key=="string"&&e.api_key.length>0,g=jo(e.api_key),h=e.is_active!==!1;return r.jsxs("div",{className:"group flex h-full cursor-pointer flex-col gap-3 rounded-xl border border-border bg-card p-4 transition-colors hover:border-muted-fg/50",onClick:t,children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("div",{className:Te("flex size-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br",l),children:r.jsx(u,{className:"size-5 text-white"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("h3",{className:"truncate text-sm font-semibold",children:e.name||e.slug}),r.jsx("p",{className:"truncate font-mono text-[10px] text-muted-fg",children:e.slug}),r.jsxs("span",{className:Te("mt-1 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium",c),children:[r.jsx(u,{className:"size-3"})," ",p]})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[r.jsx(Ye,{content:f(h?"providers_modal.toggle_active":"providers_modal.toggle_inactive"),children:r.jsxs("button",{type:"button",onClick:b=>{b.stopPropagation(),o()},className:Te("flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-medium transition-colors",h?"border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/10":"border-border text-muted-fg hover:text-foreground"),children:[r.jsx("span",{className:Te("size-1.5 rounded-full",h?"bg-emerald-400":"bg-muted-fg/40")}),f(h?"providers_card.active":"providers_card.off")]})}),r.jsx(Ye,{content:f("providers_modal.delete"),children:r.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),s()},className:"rounded-md p-1 text-muted-fg hover:bg-destructive/10 hover:text-destructive",children:r.jsx(Zn,{className:"size-3.5"})})})]})]}),r.jsxs("div",{className:"mt-auto space-y-1 text-xs",children:[r.jsx(tc,{label:f("providers_card.model"),value:e.default_model||"—",mono:!0}),e.base_url&&r.jsx(tc,{label:f("providers_card.base_url"),value:e.base_url,mono:!0,truncate:!0}),r.jsx(tc,{label:f("providers_card.api_key"),value:m?g?`…${g}`:f("providers_card.key_set"):"—",mono:!!g}),e.default_temperature!==void 0&&r.jsx(tc,{label:f("providers_card.temp"),value:e.default_temperature.toFixed(1)}),e.pricing?.input_per_million!==void 0&&r.jsx(tc,{label:f("providers_card.price_io"),value:`${e.pricing.input_per_million??0} / ${e.pricing.output_per_million??0}`})]})]})}function tc({label:e,value:t,mono:s,truncate:o}){return r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-muted-fg",children:e}),r.jsx("span",{className:Te("text-foreground",s&&"font-mono",o&&"max-w-[180px] truncate"),children:t})]})}const Zj={name:"",slug:"",engine:"anthropic",base_url:"",api_key_value:"",default_model:"",default_temperature:.7,default_max_tokens:4096,is_active:!0,context_limit_tokens:2e5,model_context_limits_json:"",p_input:"",p_output:"",p_cache_read:"",p_cache_write:""},YP=["anthropic","openai","gemini","groq","openrouter","ollama","custom"];function nc(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ed(e){if(e==null)return"";const t=Number(e);return Number.isFinite(t)?String(t):""}function KP(e){return{name:e.name||e.slug,slug:e.slug,engine:e.engine||"custom",base_url:e.base_url||"",api_key_value:"",default_model:e.default_model||"",default_temperature:e.default_temperature??.7,default_max_tokens:e.default_max_tokens??4096,is_active:e.is_active!==!1,context_limit_tokens:e.context_limit_tokens??2e5,model_context_limits_json:e.model_context_limits?JSON.stringify(e.model_context_limits,null,2):"",p_input:Ed(e.pricing?.input_per_million),p_output:Ed(e.pricing?.output_per_million),p_cache_read:Ed(e.pricing?.cache_read_per_million),p_cache_write:Ed(e.pricing?.cache_write_per_million)}}function XP({open:e,initial:t,existingSlugs:s,onClose:o,onSave:l}){const c=!!t,[u,p]=x.useState(Zj),[m,g]=x.useState(!1),[h,b]=x.useState(null),[v,k]=x.useState([]),[N,j]=x.useState(!1),[y,C]=x.useState(null),[S,E]=x.useState(!1),[R,A]=x.useState("");x.useEffect(()=>{if(!e)return;const F=t?KP(t):Zj;p(F),b(null),C(null),E(!1);const X=mo[F.engine];k(X?.known_models||[])},[e,t]);const T=F=>p(X=>({...X,...F})),M=F=>{const X=mo[F];T({engine:F,name:F==="custom"?u.name:Sc.find(P=>P.value===F)?.label||F,slug:F==="custom"?u.slug:F,base_url:X.base_url,default_model:X.default_model}),k(X.known_models),C(null)},z=F=>{const X=mo[F];T({engine:F,base_url:u.base_url||X.base_url,default_model:u.default_model||X.default_model}),k(X.known_models)},B=async()=>{j(!0),C(null);try{const F=await mf.models({engine:u.engine,slug:u.slug||nc(u.name),base_url:u.base_url||void 0,api_key:u.api_key_value||void 0});if(F.error){C(F.error);return}k(F.models),F.models.length===0&&C(f("providers_modal.err_no_models"))}catch(F){C(F.message||f("providers_modal.err_list_models"))}finally{j(!1)}},L=x.useMemo(()=>u.default_model&&!v.includes(u.default_model)?[u.default_model,...v]:v,[v,u.default_model]),U=()=>{const F=(u.slug||nc(u.name)).trim();if(!F)return b(f("providers_modal.err_slug_required")),null;if(!c&&s.includes(F))return b(f("providers_modal.err_slug_exists",{slug:F})),null;let X;if(u.model_context_limits_json.trim())try{const Z=JSON.parse(u.model_context_limits_json);if(!Z||typeof Z!="object"||Array.isArray(Z))throw new Error;X=Z}catch{return b(f("providers_modal.err_model_limits_json")),null}const G=[u.p_input,u.p_output,u.p_cache_read,u.p_cache_write].map(Z=>Z.trim()).some(Boolean)?{input_per_million:Number(u.p_input||0),output_per_million:Number(u.p_output||0),cache_read_per_million:Number(u.p_cache_read||0),cache_write_per_million:Number(u.p_cache_write||0)}:void 0;return{provider:{slug:F,name:u.name.trim()||F,engine:u.engine,base_url:u.base_url.trim()||void 0,default_model:u.default_model.trim()||void 0,default_temperature:u.default_temperature,default_max_tokens:u.default_max_tokens,is_active:u.is_active,context_limit_tokens:u.context_limit_tokens||void 0,model_context_limits:X,pricing:G},modelLimits:X}},D=()=>{const F=U();if(!F)return;const{provider:X}=F,P={name:X.name,engine:X.engine,is_active:X.is_active!==!1,default_temperature:X.default_temperature,default_max_tokens:X.default_max_tokens};X.base_url&&(P.base_url=X.base_url),X.default_model&&(P.default_model=X.default_model),X.context_limit_tokens&&(P.context_limit_tokens=X.context_limit_tokens),X.model_context_limits&&(P.model_context_limits=X.model_context_limits),X.pricing&&(P.pricing=X.pricing),u.api_key_value.trim()&&(P.api_key=u.api_key_value.trim()),A(JSON.stringify(P,null,2)),b(null),E(!0)},I=async()=>{g(!0),b(null);try{if(S){const X=(u.slug||nc(u.name)).trim();if(!X){b(f("providers_modal.err_slug_required_form"));return}let P;try{P=JSON.parse(R)}catch{b(f("providers_modal.err_json_invalid"));return}if(!P||typeof P!="object"||Array.isArray(P)){b(f("providers_modal.err_json_object"));return}const G=P;if(!G.engine||typeof G.engine!="string"){b(f("providers_modal.err_engine_missing"));return}const Z={slug:X,name:typeof G.name=="string"?G.name:X,engine:String(G.engine),base_url:typeof G.base_url=="string"?G.base_url:void 0,default_model:typeof G.default_model=="string"?G.default_model:void 0,is_active:G.is_active!==!1};await l({provider:Z,raw:G,originalSlug:t?.slug}),o();return}const F=U();if(!F)return;await l({provider:F.provider,apiKeyValue:u.api_key_value.trim()||void 0,originalSlug:t?.slug}),o()}catch(F){b(F.message||f("providers_modal.err_save"))}finally{g(!1)}},V=c&&is(t?.api_key),$=jo(t?.api_key),q=V?f("providers_modal.api_key_set",{suffix:$??""}):"sk-…",Y=u.engine==="ollama",K=mo[u.engine]?.api_key_env;return r.jsx(On,{open:e,onClose:o,title:c?f("providers_modal.edit_title",{name:t?.name||t?.slug||""}):f("providers_modal.new_title"),description:f("providers_modal.description"),size:"lg",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:o,disabled:m,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:I,loading:m,children:f(c?"common.save":"common.create")})]}),children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[c?r.jsx("span",{}):r.jsx("div",{className:"flex flex-wrap gap-1.5",children:YP.map(F=>{const X=_f[F],P=F==="custom"?f("providers_modal.custom"):Sc.find(Z=>Z.value===F)?.label||F,G=u.engine===F;return r.jsxs("button",{type:"button",onClick:()=>M(F),className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${G?"border-emerald-500/50 bg-emerald-500/10 text-emerald-400":"border-border text-muted-fg hover:border-muted-fg/60 hover:text-foreground"}`,children:[r.jsx(X,{className:"size-3.5"})," ",P]},F)})}),r.jsxs("button",{type:"button",onClick:()=>S?E(!1):D(),className:`flex shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs transition-colors ${S?"border-sky-500/50 bg-sky-500/10 text-sky-400":"border-border text-muted-fg hover:text-foreground"}`,children:[r.jsx(cM,{className:"size-3.5"})," ",f(S?"providers_modal.form_mode":"providers_modal.json_mode")]})]}),S?r.jsxs("div",{className:"space-y-2",children:[r.jsx(le,{label:f("providers_modal.json_label"),hint:f("providers_modal.json_hint",{slug:u.slug||nc(u.name)||"<slug>"}),children:r.jsx(Mn,{rows:14,className:"font-mono text-xs",value:R,onChange:F=>A(F.target.value),spellCheck:!1})}),r.jsx("p",{className:"text-[11px] text-muted-fg",children:f("providers_modal.json_help")})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("providers_modal.name_label"),children:r.jsx(Ne,{value:u.name,onChange:F=>T({name:F.target.value,slug:c?u.slug:nc(F.target.value)}),placeholder:f("providers_modal.name_ph")})}),r.jsx(le,{label:f("providers_modal.engine_label"),children:r.jsx(bt,{value:u.engine,onChange:F=>z(F),options:Sc.map(F=>({value:F.value,label:F.label,icon:_f[F.value]}))})})]}),r.jsx(le,{label:f("providers_modal.base_url_label"),hint:f("providers_modal.base_url_hint"),children:r.jsx(Ne,{value:u.base_url,onChange:F=>T({base_url:F.target.value}),placeholder:f("providers_modal.base_url_ph")})}),!Y&&r.jsx(le,{label:f("providers_modal.api_key_label"),hint:V?f("providers_modal.api_key_hint_existing"):K?f("providers_modal.api_key_hint_env",{env:K}):f("providers_modal.api_key_hint"),children:r.jsx(Ne,{type:"password",autoComplete:"new-password",value:u.api_key_value,onChange:F=>T({api_key_value:F.target.value}),placeholder:q})}),r.jsx(le,{label:f("providers_modal.model_label"),children:r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(oN,{value:u.default_model,onChange:F=>T({default_model:F}),options:L,className:"flex-1"}),r.jsx(Ye,{content:f("providers_modal.list_models_hint"),children:r.jsxs(ce,{size:"sm",variant:"secondary",onClick:B,disabled:N,"aria-label":f("providers_modal.list_models_hint"),children:[N?r.jsx(Af,{className:"size-3.5 animate-spin"}):r.jsx(ua,{className:"size-3.5"}),f("providers_modal.load_models")]})})]}),y&&r.jsx("p",{className:"text-[11px] text-amber-400",children:y})]})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("providers_modal.max_tokens_label"),children:r.jsx(Ne,{type:"number",min:256,step:256,value:u.default_max_tokens,onChange:F=>T({default_max_tokens:parseInt(F.target.value)||4096})})}),r.jsx(le,{label:f("providers_modal.temperature_label",{value:u.default_temperature.toFixed(1)}),children:r.jsx("input",{type:"range",min:0,max:2,step:.1,value:u.default_temperature,onChange:F=>T({default_temperature:parseFloat(F.target.value)}),className:"mt-2 w-full accent-foreground"})})]}),r.jsxs("details",{className:"rounded-md border border-border bg-muted/20 p-3",children:[r.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted-fg",children:f("providers_modal.pricing_summary")}),r.jsxs("div",{className:"mt-3 space-y-3",children:[r.jsx(le,{label:f("providers_modal.context_limit_label"),children:r.jsx(Ne,{type:"number",min:0,step:1024,value:u.context_limit_tokens,onChange:F=>T({context_limit_tokens:parseInt(F.target.value)||0})})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("providers_modal.price_input"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_input,onChange:F=>T({p_input:F.target.value}),placeholder:"0.15"})}),r.jsx(le,{label:f("providers_modal.price_output"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_output,onChange:F=>T({p_output:F.target.value}),placeholder:"0.60"})}),r.jsx(le,{label:f("providers_modal.price_cache_read"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_cache_read,onChange:F=>T({p_cache_read:F.target.value}),placeholder:"0.03"})}),r.jsx(le,{label:f("providers_modal.price_cache_write"),children:r.jsx(Ne,{type:"number",min:0,step:1e-4,value:u.p_cache_write,onChange:F=>T({p_cache_write:F.target.value}),placeholder:"0.00"})})]}),r.jsx(le,{label:f("providers_modal.model_limits_label"),hint:'{"gpt-4o-mini":128000}',children:r.jsx(Mn,{rows:3,className:"font-mono text-xs",value:u.model_context_limits_json,onChange:F=>T({model_context_limits_json:F.target.value})})})]})]}),r.jsx(Ft,{checked:u.is_active,onChange:F=>T({is_active:F}),label:f("providers_modal.active_label")})]}),h&&r.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:h})]})})}const QP=new Set(Sc.map(e=>e.value));function WP(e,t){const s=typeof t.engine=="string"&&t.engine||(QP.has(e)?e:"custom");return{slug:e,name:typeof t.name=="string"?t.name:void 0,engine:s,base_url:typeof t.base_url=="string"?t.base_url:void 0,api_key:typeof t.api_key=="string"?t.api_key:void 0,default_model:typeof t.default_model=="string"?t.default_model:void 0,default_temperature:typeof t.default_temperature=="number"?t.default_temperature:void 0,default_max_tokens:typeof t.default_max_tokens=="number"?t.default_max_tokens:void 0,is_active:typeof t.is_active=="boolean"?t.is_active:void 0,context_limit_tokens:typeof t.context_limit_tokens=="number"?t.context_limit_tokens:void 0,model_context_limits:t.model_context_limits||void 0,pricing:t.pricing||void 0}}function ZP(){const e=lt(),{config:t,isLoading:s,patch:o,mutate:l}=Vr(),[c,u]=x.useState(!1),[p,m]=x.useState(null);if(s)return r.jsx(ot,{});const g=t.engines||{},h=Object.entries(g).map(([C,S])=>WP(C,S||{})),b=h.map(C=>C.slug),v=()=>{m(null),u(!0)},k=C=>{m(C),u(!0)},N=async({provider:C,apiKeyValue:S,raw:E})=>{if(E){await o({[`engines.${C.slug}`]:E}),e.success(f("engines_panel.saved_json")),l();return}const R=`engines.${C.slug}`,A={[`${R}.name`]:C.name,[`${R}.engine`]:C.engine,[`${R}.is_active`]:C.is_active!==!1,[`${R}.default_temperature`]:C.default_temperature,[`${R}.default_max_tokens`]:C.default_max_tokens},T=[],M=(z,B)=>{B===void 0||B===""?T.push(`${R}.${z}`):A[`${R}.${z}`]=B};M("base_url",C.base_url),M("default_model",C.default_model),M("context_limit_tokens",C.context_limit_tokens),M("pricing",C.pricing),M("model_context_limits",C.model_context_limits),S&&(A[`${R}.api_key`]=S),await o(A,T),e.success(f("engines_panel.saved")),l()},j=async C=>{try{await o({[`engines.${C.slug}.is_active`]:C.is_active===!1}),l()}catch(S){e.error(S.message)}},y=async C=>{if(confirm(f("engines_panel.delete_confirm",{name:C.name||C.slug})))try{await o(void 0,[`engines.${C.slug}`]),e.success(f("engines_panel.deleted")),l()}catch(S){e.error(S.message)}};return r.jsxs(Ke,{title:f("engines_panel.title"),description:f("engines_panel.description"),action:r.jsxs(ce,{size:"sm",variant:"primary",onClick:v,children:[r.jsx(tn,{size:14})," ",f("engines_panel.new_btn")]}),children:[h.length===0?r.jsx(xt,{children:f("engines_panel.empty")}):r.jsxs("div",{className:"grid grid-cols-1 items-stretch gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[h.map(C=>r.jsx(GP,{provider:C,onEdit:()=>k(C),onDelete:()=>y(C),onToggle:()=>j(C)},C.slug)),r.jsxs("button",{type:"button",onClick:v,className:"flex min-h-[120px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border text-muted-fg transition-colors hover:border-muted-fg/60 hover:text-foreground",children:[r.jsx(tn,{size:20}),r.jsx("span",{className:"text-sm font-medium",children:f("engines_panel.add_card")})]})]}),r.jsx(XP,{open:c,initial:p,existingSlugs:b,onClose:()=>{u(!1),m(null)},onSave:N})]})}function cN(){return r.jsxs("div",{className:"space-y-6",children:[r.jsx(FP,{}),r.jsx(ZP,{})]})}function JP(){const e=lt(),[t,s]=x.useState(!1),l=et(t?"/agents/vault?include_removed=1":"/agents/vault",()=>rn.vault({includeRemoved:t})),c=l.data||[],[u,p]=x.useState(null),m=async h=>{const b=h.source!=="user",v=b?f("base.defaults_tombstone_msg",{slug:h.slug}):f("base.defaults_delete_msg",{slug:h.slug});if(confirm(v))try{await rn.vaultRemove(h.slug),e.success(f(b?"base.defaults_hidden":"base.defaults_deleted")),l.mutate()}catch(k){e.error(k.message)}},g=async h=>{try{await rn.vaultRestore(h),e.success(f("base.defaults_restored")),l.mutate()}catch(b){e.error(b.message)}};return r.jsxs(Ke,{title:f("base.defaults_title"),description:f("base.defaults_desc"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ft,{checked:t,onChange:s,label:f("base.defaults_show_removed")}),r.jsxs(ce,{size:"sm",onClick:()=>p("new"),children:[r.jsx(tn,{size:14})," ",f("base.defaults_new")]})]}),children:[l.isLoading&&r.jsx(ot,{}),!l.isLoading&&c.length===0&&r.jsx(xt,{children:f("base.defaults_empty")}),r.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:c.map(h=>{const b=t&&h.tombstoned;return r.jsxs("div",{className:`flex flex-col gap-2 rounded-xl border bg-card p-4 ${b?"border-dashed border-border opacity-60":"border-border"}`,children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[r.jsx("div",{className:"flex size-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-slate-600 to-gray-600",children:h.is_master?r.jsx(Ga,{className:"size-4 text-white"}):r.jsx(un,{className:"size-4 text-white"})}),r.jsx("span",{className:"truncate text-sm font-semibold",children:h.slug}),r.jsx(e6,{source:h.source})]}),r.jsx("div",{className:"flex shrink-0 items-center gap-0.5",children:b?r.jsx(ah,{label:f("base.defaults_restore"),onClick:()=>g(h.slug),variant:"secondary",children:r.jsx(Fx,{size:13})}):r.jsxs(r.Fragment,{children:[r.jsx(ah,{label:f("base.defaults_edit"),onClick:()=>p(h),variant:"ghost",children:r.jsx(Eo,{size:13})}),r.jsx(ah,{label:h.source==="user"?f("base.defaults_delete"):f("base.defaults_hide"),onClick:()=>m(h),variant:"ghost-destructive",children:r.jsx(Zn,{size:13})})]})})]}),h.model?r.jsx(Fe,{tone:"info",children:h.model}):r.jsx("span",{className:"text-[10px] text-muted-fg",children:f("agents_ui.model_router_default")}),h.description&&r.jsx("p",{className:"line-clamp-3 text-xs text-muted-fg",children:h.description}),r.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.role&&r.jsx(Fe,{children:h.role}),h.skills?.map(v=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(ma,{size:9})," ",v]},v)),h.tools?.map(v=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(Zl,{size:9})," ",v]},v))]})]},h.slug)})}),u!==null&&r.jsx(t6,{agent:u==="new"?null:u,onClose:()=>p(null),onSaved:()=>{p(null),l.mutate()}})]})}function e6({source:e}){return e==="user"?r.jsx(Fe,{tone:"success",children:f("agents_ui.source_user")}):e==="user-override"?r.jsx(Fe,{tone:"warning",children:f("agents_ui.source_override")}):r.jsx(Fe,{tone:"muted",children:f("agents_ui.source_bundled")})}function ah({label:e,onClick:t,variant:s="ghost",children:o}){const l="inline-flex size-7 items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",c={ghost:"text-muted-fg hover:bg-accent hover:text-accent-fg","ghost-destructive":"text-muted-fg hover:bg-destructive/15 hover:text-destructive",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80"};return r.jsxs(zb,{children:[r.jsx(Db,{render:r.jsx("button",{type:"button",onClick:t,"aria-label":e,className:`${l} ${c[s]}`,children:o})}),r.jsx(Lb,{children:e})]})}function t6({agent:e,onClose:t,onSaved:s}){const o=lt(),[l,c]=x.useState(!1),u=!e,[p,m]=x.useState(e?.slug??""),[g,h]=x.useState(e?.role??""),[b,v]=x.useState(e?.model??""),[k,N]=x.useState(e?.description??""),[j,y]=x.useState(e?.language??"es"),[C,S]=x.useState((e?.skills??[]).join(", ")),[E,R]=x.useState((e?.tools??[]).join(", ")),[A,T]=x.useState(!!e?.is_master),[M,z]=x.useState(e?.body??""),B=async()=>{const L={role:g||void 0,model:b||void 0,description:k||void 0,language:j||void 0,skills:C,tools:E,is_master:A};c(!0);try{if(u){if(!/^[a-z][a-z0-9_-]*$/.test(p))throw new Error(f("base.defaults_slug_invalid"));await rn.vaultCreate(p,L,M),o.success(f("base.defaults_created",{slug:p}))}else await rn.vaultPatch(e.slug,{fields:L,body:M}),o.success(f("base.defaults_saved",{slug:e.slug}));s()}catch(U){o.error(U.message)}finally{c(!1)}};return r.jsx(On,{open:!0,onClose:t,title:u?f("base.defaults_new_title"):f("base.defaults_edit_title",{slug:e.slug}),description:u?f("base.defaults_new_desc"):e.source==="bundled"?f("base.defaults_bundled_desc"):f("base.defaults_user_desc"),size:"lg",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:l,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:B,loading:l,children:f("common.save")})]}),children:r.jsxs("div",{className:"space-y-3",children:[u&&r.jsx(le,{label:"slug",hint:f("agents_ui.slug_kebab_hint"),children:r.jsx(Ne,{autoFocus:!0,value:p,onChange:L=>m(L.target.value),placeholder:"reviewer"})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:"role",children:r.jsx(Ne,{value:g,onChange:L=>h(L.target.value),placeholder:"Code reviewer"})}),r.jsx(le,{label:"model",children:r.jsx(Ne,{value:b,onChange:L=>v(L.target.value),placeholder:"openrouter:..."})}),r.jsx(le,{label:"language",children:r.jsx(Ne,{value:j,onChange:L=>y(L.target.value),placeholder:"es"})}),r.jsx(le,{label:"is_master",children:r.jsx("div",{className:"flex h-9 items-center",children:r.jsx(Ft,{checked:A,onChange:T,label:f("base.defaults_master_label")})})})]}),r.jsx(le,{label:"description",children:r.jsx(Ne,{value:k,onChange:L=>N(L.target.value)})}),r.jsx(le,{label:"skills",hint:f("agents_ui.comma_separated"),children:r.jsx(Ne,{value:C,onChange:L=>S(L.target.value),placeholder:"code-review, git"})}),r.jsx(le,{label:"tools",hint:f("agents_ui.comma_separated"),children:r.jsx(Ne,{value:E,onChange:L=>R(L.target.value),placeholder:"read, write, run"})}),r.jsx(le,{label:"body",hint:f("agents_ui.body_hint"),children:r.jsx(Mn,{value:M,onChange:L=>z(L.target.value),rows:10,placeholder:"# Mission\\n..."})})]})})}const n6=20,Jj=[10,20,50,100];function l_({key:e,fetchPage:t,resetKey:s,initialPageSize:o=n6,swr:l}){const[c,u]=x.useState(1),[p,m]=x.useState(o);x.useEffect(()=>{u(1)},[s]);const g=(c-1)*p,h=et(e==null?null:[e,p,g],()=>t(p,g),{keepPreviousData:!0,...l}),b=h.data?.total??0,v=Math.max(1,Math.ceil(b/p)),k=Math.min(c,v);x.useEffect(()=>{c!==k&&u(k)},[c,k]);const N=b===0?0:g,j=Math.min(g+p,b);return{items:h.data?.items??[],isLoading:h.isLoading,error:h.error,mutate:h.mutate,page:k,pageCount:v,total:b,start:N,end:j,pageSize:p,setPage:u,setPageSize:y=>{m(y),u(1)}}}function s6({page:e,pageCount:t,total:s,start:o,end:l,pageSize:c,onPage:u,onPageSize:p}){return s<=Jj[0]?null:r.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-3 text-xs text-muted-fg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"tabular-nums",children:f("common.pager_range",{from:o+1,to:l,total:s})}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{children:f("common.pager_per_page")}),r.jsx("div",{className:"w-[4.5rem]",children:r.jsx(bt,{value:String(c),onChange:m=>p(Number(m)),options:Jj.map(m=>({value:String(m),label:String(m)}))})})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(ce,{size:"sm",variant:"ghost",disabled:e<=1,onClick:()=>u(e-1),"aria-label":f("common.pager_prev"),children:r.jsx(uM,{size:14})}),r.jsx("span",{className:"px-1 tabular-nums",children:f("common.pager_page",{page:e,total:t})}),r.jsx(ce,{size:"sm",variant:"ghost",disabled:e>=t,onClick:()=>u(e+1),"aria-label":f("common.pager_next"),children:r.jsx(Wl,{size:14})})]})]})}function i_({paged:e,fullHeight:t,className:s,children:o}){const l=r.jsx(s6,{page:e.page,pageCount:e.pageCount,total:e.total,start:e.start,end:e.end,pageSize:e.pageSize,onPage:e.setPage,onPageSize:e.setPageSize});return t?r.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[r.jsx("div",{className:Te("min-h-0 flex-1 overflow-y-auto",s),children:o}),r.jsx("div",{className:"shrink-0",children:l})]}):r.jsxs("div",{className:s,children:[o,l]})}const a6={apx:"success",claude:"info",codex:"warning"};function r6(){const e=lt(),t=op(),[s,o]=x.useState(""),[l,c]=x.useState(""),[u,p]=x.useState(""),[m,g]=x.useState(!1);x.useEffect(()=>{const y=setTimeout(()=>p(l.trim()),350);return()=>clearTimeout(y)},[l]);const h=l_({key:`/sessions?engine=${s}&q=${u}&deep=${m?1:0}`,fetchPage:(y,C)=>HD.page({engine:s||void 0,q:u||void 0,deep:m,limit:y,offset:C}),resetKey:`${s}|${u}|${m?1:0}`}),b=()=>{c(""),p(""),o(""),g(!1)},v=async y=>{try{await navigator.clipboard.writeText(`apx session resume ${y.id} --continue`),e.success(f("base.sessions_cmd_copied"))}catch{e.error(f("base.sessions_copy_failed"))}},k=y=>{const C=`Continue this session: ${y.id} (engine: ${y.engine}${y.title?`, title: "${y.title}"`:""}${y.cwd?`, folder: ${y.cwd}`:""}). With these instructions: `;window.dispatchEvent(new CustomEvent("apx:roby-prompt",{detail:{prompt:C}}))},N=async y=>{if(!y.cwd){e.error(f("base.sessions_no_folder"));return}try{await wC.exec({kind:"open_path",target:y.cwd})}catch(C){e.error(f("base.sessions_folder_failed",{msg:C.message}))}},j=async y=>{const C=y.path||y.cwd;if(!C){e.error(f("base.sessions_no_path"));return}try{await navigator.clipboard.writeText(C),e.success(f("base.sessions_path_copied"))}catch{e.error(f("base.sessions_copy_failed"))}};return r.jsxs(Ke,{fullHeight:!0,title:f("base.sessions_title"),description:f("base.sessions_desc"),action:r.jsx(Ye,{content:f("base.sessions_refresh"),children:r.jsx(ce,{size:"sm",variant:"secondary",onClick:()=>h.mutate(),children:r.jsx(ua,{size:13})})}),children:[r.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(_c,{size:14,className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-fg"}),r.jsx(Ne,{className:"pl-8",placeholder:f("base.sessions_search_ph"),value:l,onChange:y=>c(y.target.value)})]}),r.jsx(Ye,{content:f("base.sessions_deep_tip"),children:r.jsx(ce,{size:"sm",variant:m?"primary":"secondary",onClick:()=>g(y=>!y),children:f("base.sessions_deep")})}),r.jsx("div",{className:"w-36",children:r.jsx(bt,{value:s,onChange:o,options:[{value:"",label:f("base.sessions_all")},{value:"apx",label:"apx"},{value:"claude",label:"claude"},{value:"codex",label:"codex"}]})}),r.jsx(Ye,{content:f("base.sessions_clear"),children:r.jsx(ce,{size:"sm",variant:"ghost",onClick:b,children:r.jsx(Ys,{size:14})})})]}),h.isLoading&&r.jsx(ot,{}),h.error&&r.jsx(xt,{children:f("base.sessions_error",{msg:h.error.message})}),!h.isLoading&&!h.error&&h.total===0&&r.jsx(xt,{children:u?f("base.sessions_no_match",{q:u}):f("base.sessions_empty")}),r.jsx(i_,{paged:h,fullHeight:!0,children:r.jsx("ul",{className:"space-y-1 text-sm",children:h.items.map((y,C)=>r.jsxs("li",{className:"group flex items-center gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsx(Fe,{tone:a6[y.engine]||"muted",children:y.engine}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"truncate",children:y.title||y.id}),r.jsxs("div",{className:"flex items-center gap-2 font-mono text-[10px] text-muted-fg",children:[r.jsx("span",{className:"shrink-0",children:y.id}),y.cwd&&r.jsxs("span",{className:"truncate",children:["· ",y.cwd]})]})]}),y.mtime>0&&r.jsx("span",{className:"shrink-0 text-[11px] text-muted-fg",children:new Date(y.mtime).toLocaleString()}),r.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 opacity-60 transition-opacity group-hover:opacity-100",children:[r.jsx(Ye,{content:f("base.sessions_act_cmd"),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_cmd"),onClick:()=>v(y),children:r.jsx(Ya,{size:13})})}),r.jsx(Ye,{content:f("base.sessions_act_ask",{name:t}),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_ask",{name:t}),onClick:()=>k(y),children:r.jsx(un,{size:13})})}),r.jsx(Ye,{content:f("base.sessions_act_folder"),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_folder"),onClick:()=>N(y),children:r.jsx(Rf,{size:13})})}),r.jsx(Ye,{content:f("base.sessions_act_path"),children:r.jsx(ce,{size:"sm",variant:"ghost","aria-label":f("base.sessions_act_path"),onClick:()=>j(y),children:r.jsx(Ec,{size:13})})})]})]},`${y.engine}-${y.id}-${C}`))})})]})}function o6(){const e=Wn(),[t,s]=x.useState("open"),o=l_({key:`/tasks?state=${t}`,fetchPage:(l,c)=>Nr.globalPage({state:t,limit:l,offset:c}),resetKey:t});return r.jsxs(Ke,{fullHeight:!0,title:f("project.global_tasks.title"),description:f("project.global_tasks.subtitle"),action:r.jsx("div",{className:"flex gap-1",children:["open","done","dropped","all"].map(l=>r.jsx(ce,{size:"sm",variant:t===l?"primary":"ghost",onClick:()=>s(l),children:l},l))}),children:[o.isLoading&&r.jsx(ot,{}),!o.isLoading&&o.total===0&&r.jsx(xt,{children:f("project.global_tasks.empty")}),r.jsx(i_,{paged:o,fullHeight:!0,children:r.jsx("ul",{className:"space-y-2 text-sm",children:o.items.map(l=>r.jsxs("li",{className:"flex items-start gap-3 rounded-md border border-border bg-muted/30 px-3 py-2",children:[r.jsx("button",{type:"button",onClick:()=>e(`/p/${l.project_id}/tasks`),title:f("project.global_tasks.go_project"),children:r.jsx(Fe,{tone:"info",children:(l.project_name||"").split("/").pop()||l.project_id})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"font-medium",children:l.title}),r.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-fg",children:[r.jsx("span",{children:l.state}),l.agent&&r.jsxs(Fe,{tone:"muted",children:["@",l.agent]}),l.tags?.map(c=>r.jsxs("span",{children:["#",c]},c)),l.due&&r.jsxs("span",{children:[f("project.global_tasks.due")," ",l.due]})]})]})]},`${l.project_id}-${l.id}`))})})]})}const uN=x.createContext(void 0);function c_(){const e=x.useContext(uN);if(e===void 0)throw new Error(nn(64));return e}let l6=(function(e){return e.activationDirection="data-activation-direction",e.orientation="data-orientation",e})({});const up={tabActivationDirection:e=>({[l6.activationDirection]:e})},i6=x.forwardRef(function(t,s){const{className:o,defaultValue:l=0,onValueChange:c,orientation:u="horizontal",render:p,value:m,style:g,...h}=t,b=t.defaultValue!==void 0,v=x.useRef([]),[k,N]=x.useState(()=>new Map),[j,y]=Vl({controlled:m,default:l,name:"Tabs",state:"value"}),C=m!==void 0,[S,E]=x.useState(()=>new Map),R=x.useRef(void 0),A=x.useCallback(me=>{if(me===void 0)return null;for(const[Ae,ie]of S.entries())if(ie!=null&&me===(ie.value??ie.index))return Ae;return null},[S]),[T,M]=x.useState(()=>({previousValue:j,tabActivationDirection:"none"})),{previousValue:z,tabActivationDirection:B}=T;let L=B,U=!1;z!==j&&(L=ew(z,j,u,S),U=z!=null&&j!=null&&A(j)==null);const D=U?z:j,I=z!==D||B!==L;De(()=>{I&&M({previousValue:D,tabActivationDirection:L})},[D,I,L]);const V=Ue((me,Ae)=>{const ie=ew(j,me,u,S);Ae.activationDirection=ie,c?.(me,Ae),!Ae.isCanceled&&y(me)}),$=Ue((me,Ae)=>{c?.(me,nt(Ae,void 0,void 0,{activationDirection:"none"}))}),q=Ue((me,Ae)=>{N(ie=>{if(ie.get(me)===Ae)return ie;const pe=new Map(ie);return pe.set(me,Ae),pe})}),Y=Ue((me,Ae)=>{N(ie=>{if(!ie.has(me)||ie.get(me)!==Ae)return ie;const pe=new Map(ie);return pe.delete(me),pe})}),K=x.useCallback(me=>k.get(me),[k]),F=x.useCallback(me=>{for(const Ae of S.values())if(me===Ae?.value)return Ae?.id},[S]),X=x.useMemo(()=>({getTabElementBySelectedValue:A,getTabIdByPanelValue:F,getTabPanelIdByValue:K,onValueChange:V,orientation:u,registerMountedTabPanel:q,setTabMap:E,unregisterMountedTabPanel:Y,tabActivationDirection:L,value:j}),[A,F,K,V,u,q,E,Y,L,j]),P=x.useMemo(()=>{for(const me of S.values())if(me!=null&&me.value===j)return me},[S,j]),G=x.useMemo(()=>{for(const me of S.values())if(me!=null&&!me.disabled)return me.value},[S]),Z=x.useRef(!b),ee=x.useRef(l),de=x.useRef(b),fe=x.useRef(!1);De(()=>{if(C)return;function me(Se,je){y(Se),M(Be=>Be.previousValue===Se&&Be.tabActivationDirection==="none"?Be:{previousValue:Se,tabActivationDirection:"none"}),$(Se,je),Z.current=!1}if(S.size===0){fe.current&&j!==null&&!R.current?.isConnected&&me(null,q1);return}fe.current=!0,R.current=S.keys().next().value;const Ae=P?.disabled,ie=P==null&&j!==null;if(!Ae&&j===ee.current&&(de.current=!1),de.current&&Ae&&j===ee.current)return;const pe=Z.current;if(Ae||ie){const Se=G??null;if(j===Se){Z.current=!1;return}let je=q1;pe?je=$1:Ae&&(je=vS),me(Se,je);return}pe&&P!=null&&($(j,$1),Z.current=!1)},[G,C,$,P,y,S,j]);const oe=Nt("div",t,{state:{orientation:u,tabActivationDirection:L},ref:s,props:h,stateAttributesMapping:up});return r.jsx(uN.Provider,{value:X,children:r.jsx(ap,{elementsRef:v,children:oe})})});function ew(e,t,s,o){if(e==null||t==null)return"none";let l=null,c=null;for(const[m,g]of o.entries()){if(g==null)continue;const h=g.value??g.index;if(e===h&&(l=m),t===h&&(c=m),l!=null&&c!=null)break}if(l==null||c==null)return l!==c&&(typeof e=="number"||typeof e=="string")&&typeof e==typeof t?s==="horizontal"?t>e?"right":"left":t>e?"down":"up":"none";const u=l.getBoundingClientRect(),p=c.getBoundingClientRect();if(s==="horizontal"){if(p.left<u.left)return"left";if(p.left>u.left)return"right"}else{if(p.top<u.top)return"up";if(p.top>u.top)return"down"}return"none"}const dN="data-composite-item-active",fN=x.createContext(void 0);function c6(){const e=x.useContext(fN);if(e===void 0)throw new Error(nn(65));return e}const u6=x.forwardRef(function(t,s){const{className:o,disabled:l=!1,render:c,value:u,id:p,nativeButton:m=!0,style:g,...h}=t,{value:b,getTabPanelIdByValue:v,orientation:k,tabActivationDirection:N}=c_(),{activateOnFocus:j,highlightedTabIndex:y,onTabActivation:C,registerTabResizeObserverElement:S,setHighlightedTabIndex:E,tabsListElement:R}=c6(),A=Ks(p),T=x.useMemo(()=>({disabled:l,id:A,value:u}),[l,A,u]),{compositeProps:M,compositeRef:z,index:B}=sC({metadata:T}),L=u===b,U=x.useRef(!1),D=x.useRef(null);De(()=>{const Z=D.current;if(Z)return S(Z)},[S]),De(()=>{if(U.current){U.current=!1;return}if(!(L&&B>-1&&y!==B))return;const Z=R;if(Z!=null){const ee=qn(mt(Z));if(ee&&Qe(Z,ee))return}l||E(B)},[L,B,y,E,l,R]);const{getButtonProps:I,buttonRef:V}=Hr({disabled:l,native:m,focusableWhenDisabled:!0}),$=v(u),q=x.useRef(!1),Y=x.useRef(!1);function K(Z){L||l||C(u,nt(fa,Z.nativeEvent,void 0,{activationDirection:"none"}))}function F(Z){L||(B>-1&&!l&&E(B),!l&&j&&(!q.current||q.current&&Y.current)&&C(u,nt(fa,Z.nativeEvent,void 0,{activationDirection:"none"})))}function X(Z){if(L||l)return;q.current=!0;function ee(){q.current=!1,Y.current=!1}(!Z.button||Z.button===0)&&(Y.current=!0,mt(Z.currentTarget).addEventListener("pointerup",ee,{once:!0}))}return Nt("button",t,{state:{disabled:l,active:L,orientation:k,tabActivationDirection:N},ref:[s,V,z,D],props:[M,{role:"tab","aria-controls":$,"aria-selected":L,id:A,onClick:K,onFocus:F,onPointerDown:X,[dN]:L?"":void 0,onKeyDownCapture(){U.current=!0}},h,I],stateAttributesMapping:up})});let d6=(function(e){return e.index="data-index",e.activationDirection="data-activation-direction",e.orientation="data-orientation",e.hidden="data-hidden",e[e.startingStyle=yo.startingStyle]="startingStyle",e[e.endingStyle=yo.endingStyle]="endingStyle",e})({});const f6={...up,...Ja},p6=x.forwardRef(function(t,s){const{className:o,value:l,render:c,keepMounted:u=!1,style:p,...m}=t,{value:g,getTabIdByPanelValue:h,orientation:b,tabActivationDirection:v,registerMountedTabPanel:k,unregisterMountedTabPanel:N}=c_(),j=Ks(),y=x.useMemo(()=>({id:j,value:l}),[j,l]),{ref:C,index:S}=Gc({metadata:y}),E=l===g,{mounted:R,transitionStatus:A,setMounted:T}=ti(E),M=!R,z=h(l),B={hidden:M,orientation:b,tabActivationDirection:v,transitionStatus:A},L=x.useRef(null),U=Nt("div",t,{state:B,ref:[s,C,L],props:[{"aria-labelledby":z,hidden:M,id:j,role:"tabpanel",tabIndex:E?0:-1,inert:Jf(!E),[d6.index]:S},m],stateAttributesMapping:f6});return ha({open:E,ref:L,onComplete(){E||T(!1)}}),De(()=>{if(!(M&&!u)&&j!=null)return k(l,j),()=>{N(l,j)}},[M,u,l,j,k,N]),u||R?U:null}),m6=[];function g6(e){const{loopFocus:t=!0,orientation:s="both",grid:o,onLoop:l,direction:c,highlightedIndex:u,onHighlightedIndexChange:p,rootRef:m,enableHomeAndEndKeys:g=!1,stopEventPropagation:h=!1,disabledIndices:b,modifierKeys:v=m6}=e,[k,N]=x.useState(0),j=o!=null,y=x.useRef(null),C=Xa(y,m),S=x.useRef([]),E=x.useRef(!1),R=u??k,A=Ue((L,U=!1)=>{if((p??N)(L),U){const D=S.current[L];Nj(y.current,D,c,s)}}),T=Ue(L=>{if(L.size===0||E.current)return;E.current=!0;const U=Array.from(L.keys()),D=U.find(V=>V?.hasAttribute(dN))??null,I=D?U.indexOf(D):-1;if(I!==-1)A(I);else if(tf(U,R,b)){const V=qa(U,{disabledIndices:b});vc(U,V)||A(V)}Nj(y.current,D,c,s)});De(()=>{if(b==null||u!=null||!E.current)return;const L=S.current;if(tf(L,R,b)){const U=qa(L,{disabledIndices:b});vc(L,U)||A(U)}},[b,u,R,S,A]);const M=Ue((L,U,D)=>l?l(L,U,D,S):D),z=Ue(L=>{const U=g?sp:K2;if(!U.has(L.key)||h6(L,v)||!y.current)return;const I=c==="rtl",V=I?uf:df,$={horizontal:V,vertical:wc,both:V}[s],q=I?df:uf,Y={horizontal:q,vertical:jc,both:q}[s],K=Un(L.nativeEvent);if(K!=null&&Cj(K)&&!rC(K)){const de=K.selectionStart,fe=K.selectionEnd,ae=K.value??"";if(de==null||L.shiftKey||de!==fe||L.key!==Y&&de<ae.length||L.key!==$&&de>0)return}let F=R;const X=Bd(S,b),P=tx(S,b);o!=null&&(F=o({disabledIndices:b,elementsRef:S,event:L,highlightedIndex:R,loopFocus:t,maxIndex:P,minIndex:X,onLoop:M,orientation:s,rtl:I}));const G={horizontal:[V],vertical:[wc],both:[V,wc]}[s],Z={horizontal:[q],vertical:[jc],both:[q,jc]}[s],ee=j?U:{horizontal:g?pz:G2,vertical:g?mz:Y2,both:U}[s];g&&(L.key===tp?F=X:L.key===np&&(F=P)),F===R&&(G.includes(L.key)||Z.includes(L.key))&&(t&&F===P&&G.includes(L.key)?(F=X,l&&(F=l(L,R,F,S))):t&&F===X&&Z.includes(L.key)?(F=P,l&&(F=l(L,R,F,S))):F=qa(S.current,{startingIndex:F,decrement:Z.includes(L.key),disabledIndices:b})),F!==R&&!vc(S.current,F)&&(h&&L.stopPropagation(),ee.has(L.key)&&L.preventDefault(),A(F,!0),queueMicrotask(()=>{S.current[F]?.focus()}))});return{props:{ref:C,onFocus(L){const U=y.current,D=Un(L.nativeEvent);!U||D==null||!Cj(D)||D.setSelectionRange(0,D.value.length??0)},onKeyDown:z},highlightedIndex:R,onHighlightedIndexChange:A,elementsRef:S,disabledIndices:b,onMapChange:T,relayKeyboardEvent:z}}function h6(e,t){for(const s of _z.values())if(!t.includes(s)&&e.getModifierState(s))return!0;return!1}function x6(e){const{render:t,className:s,style:o,refs:l=Ka,props:c=Ka,state:u=qt,stateAttributesMapping:p,highlightedIndex:m,onHighlightedIndexChange:g,orientation:h,grid:b,loopFocus:v,onLoop:k,enableHomeAndEndKeys:N,onMapChange:j,stopEventPropagation:y=!0,rootRef:C,disabledIndices:S,modifierKeys:E,highlightItemOnHover:R=!1,tag:A="div",...T}=e,M=Wf(),{props:z,highlightedIndex:B,onHighlightedIndexChange:L,elementsRef:U,onMapChange:D,relayKeyboardEvent:I}=g6({grid:b,loopFocus:v,onLoop:k,orientation:h,highlightedIndex:m,onHighlightedIndexChange:g,rootRef:C,stopEventPropagation:y,enableHomeAndEndKeys:N,direction:M,disabledIndices:S,modifierKeys:E}),V=Nt(A,e,{state:u,ref:l,props:[z,...c,T],stateAttributesMapping:p}),$=x.useMemo(()=>({highlightedIndex:B,onHighlightedIndexChange:L,highlightItemOnHover:R,relayKeyboardEvent:I}),[B,L,R,I]);return r.jsx(B2.Provider,{value:$,children:r.jsx(ap,{elementsRef:U,onMapChange:q=>{j?.(q),D(q)},children:V})})}const b6=x.forwardRef(function(t,s){const{activateOnFocus:o=!1,className:l,loopFocus:c=!0,render:u,style:p,...m}=t,{onValueChange:g,orientation:h,value:b,setTabMap:v,tabActivationDirection:k}=c_(),[N,j]=x.useState(0),[y,C]=x.useState(null),S=x.useRef(new Set),E=x.useRef(new Set),R=x.useRef(null);De(()=>{if(typeof ResizeObserver>"u")return;const U=new ResizeObserver(()=>{S.current.forEach(D=>{D()})});return R.current=U,y&&U.observe(y),E.current.forEach(D=>{U.observe(D)}),()=>{U.disconnect(),R.current=null}},[y]);const A=Ue(U=>(S.current.add(U),()=>{S.current.delete(U)})),T=Ue(U=>(E.current.add(U),R.current?.observe(U),()=>{E.current.delete(U),R.current?.unobserve(U)})),M=Ue((U,D)=>{U!==b&&g(U,D)}),z={orientation:h,tabActivationDirection:k},B={"aria-orientation":h==="vertical"?"vertical":void 0,role:"tablist"},L=x.useMemo(()=>({activateOnFocus:o,highlightedTabIndex:N,registerIndicatorUpdateListener:A,registerTabResizeObserverElement:T,onTabActivation:M,setHighlightedTabIndex:j,tabsListElement:y}),[o,N,A,T,M,j,y]);return r.jsx(fN.Provider,{value:L,children:r.jsx(x6,{render:u,className:l,style:p,state:z,refs:[s,C],props:[B,m],stateAttributesMapping:up,highlightedIndex:N,enableHomeAndEndKeys:!0,loopFocus:c,orientation:h,onHighlightedIndexChange:j,onMapChange:v,disabledIndices:Ka})})});function dp({className:e,...t}){return r.jsx(i6,{"data-slot":"tabs",className:St("flex flex-col gap-4",e),...t})}const _6=Wb("inline-flex h-9 w-fit items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground data-[variant=line]:h-8 data-[variant=line]:gap-1 data-[variant=line]:rounded-none data-[variant=line]:bg-transparent data-[variant=line]:p-0",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function fp({className:e,variant:t="default",...s}){return r.jsx(b6,{"data-slot":"tabs-list","data-variant":t,className:St(_6({variant:t}),e),...s})}function ra({className:e,...t}){return r.jsx(u6,{"data-slot":"tabs-trigger",className:St("inline-flex h-7 items-center justify-center gap-1.5 rounded-md border border-transparent px-3 py-1 text-sm font-medium whitespace-nowrap text-muted-fg transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-active:bg-background data-active:text-foreground data-active:shadow-sm dark:data-active:border-input dark:data-active:bg-input/30 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function Ds({className:e,...t}){return r.jsx(p6,{"data-slot":"tabs-content",className:St("text-sm outline-none",e),...t})}function tw(e,t){let s=e;for(const o of t.split(".")){if(!s||typeof s!="object"||Array.isArray(s))return;s=s[o]}return s}function u_(e,t=""){const s={};for(const[o,l]of Object.entries(e)){const c=t?`${t}.${o}`:o;l&&typeof l=="object"&&!Array.isArray(l)?Object.assign(s,u_(l,c)):s[c]=l}return s}function v6(e){const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON debe ser objeto.");return t}function vx({sections:e,source:t,placeholderSource:s,jsonTitle:o,jsonDescription:l,saveLabel:c=f("common.save"),onSaveFields:u,onSaveJson:p,busy:m}){const g=e[0]?.key||"json",[h,b]=x.useState({}),[v,k]=x.useState(""),[N,j]=x.useState("");x.useEffect(()=>{const E={};for(const R of e.flatMap(A=>A.fields))E[R.path]=tw(t,R.path)??"";b(E),k(JSON.stringify(t||{},null,2)),j("")},[t,e]);const y=x.useMemo(()=>new Set(e.flatMap(E=>E.fields.map(R=>R.path))),[e]),C=async()=>{const E={},R=[];for(const A of e.flatMap(T=>T.fields)){const T=h[A.path];if(!is(T)){if(T===""||T===void 0||T===null){R.push(A.path);continue}if(A.kind==="number"){const M=Number(T);Number.isFinite(M)&&(E[A.path]=M)}else E[A.path]=T}}await u(E,R.filter(A=>y.has(A)))},S=async()=>{j("");try{await p(v6(v))}catch(E){j(E.message)}};return r.jsxs(dp,{defaultValue:g,className:"space-y-4",children:[r.jsxs(fp,{className:"flex flex-wrap",children:[e.map(E=>r.jsx(ra,{value:E.key,children:E.label},E.key)),r.jsx(ra,{value:"json",children:"JSON"})]}),e.map(E=>r.jsx(Ds,{value:E.key,children:r.jsxs("div",{className:"space-y-4",children:[E.description&&r.jsx("p",{className:"text-sm text-muted-fg",children:E.description}),r.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:E.fields.map(R=>r.jsx(y6,{field:R,value:h[R.path],inherited:tw(s,R.path),onChange:A=>b(T=>({...T,[R.path]:A}))},R.path))}),r.jsx(ce,{variant:"primary",loading:m,onClick:C,children:c})]})},E.key)),r.jsx(Ds,{value:"json",children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium",children:o}),l&&r.jsx("p",{className:"text-xs text-muted-fg",children:l})]}),r.jsx(Mn,{rows:18,className:"font-mono text-xs",value:v,onChange:E=>k(E.target.value)}),N&&r.jsx("p",{className:"text-xs text-destructive",children:N}),r.jsx(ce,{variant:"primary",loading:m,onClick:S,children:f("settings_ui.save_json")})]})})]})}function y6({field:e,value:t,inherited:s,onChange:o}){const l=e.placeholder||nw(s)||(is(t)?Ar(t):""),c=e.hint||(s!==void 0?`Heredado: ${nw(s)}`:void 0);return e.kind==="boolean"?r.jsx("div",{className:"flex items-end pb-1",children:r.jsx(Ft,{checked:t===!0,onChange:o,label:e.label})}):r.jsx(le,{label:e.label,hint:c,children:e.kind==="select"?r.jsx(bt,{value:String(t||""),onChange:o,placeholder:l||"(sin override)",options:[{value:"",label:l||"(sin override)"},...(e.options||[]).map(u=>({value:String(u.value),label:u.label}))]}):e.kind==="textarea"?r.jsx(Mn,{rows:4,value:String(t||""),placeholder:l,onChange:u=>o(u.target.value)}):r.jsx(Ne,{type:e.kind==="password"?"password":e.kind==="number"?"number":"text",value:String(is(t)?"":t||""),placeholder:e.kind==="password"&&is(t)?Ar(t):e.kind==="password"&&is(s)?Ar(s):l,onChange:u=>o(u.target.value)})})}function nw(e){return e==null||e===""?"":is(e)?Ar(e):Array.isArray(e)?e.join(", "):typeof e=="object"?JSON.stringify(e):String(e)}function j6(){return[{key:"routing",label:f("settings_ui.cfg_overrides_label"),description:f("settings_ui.cfg_overrides_desc"),fields:[{path:"route_to_agent",label:f("settings_ui.cfg_route_to_agent"),placeholder:"master"},{path:"super_agent.model",label:f("settings_ui.cfg_super_agent_model")},{path:"super_agent.permission_mode",label:f("settings_ui.cfg_permission_mode"),kind:"select",options:Yx.map(e=>({value:e,label:e}))},{path:"super_agent.system",label:f("settings_ui.cfg_extra_prompt"),kind:"textarea"}]},{key:"telegram",label:f("settings_ui.cfg_telegram_label"),fields:[{path:"telegram.route_to_agent",label:f("settings_ui.cfg_route_to_agent")},{path:"telegram.chat_id",label:f("settings_ui.cfg_chat_id")},{path:"telegram.bot_token",label:f("settings_ui.cfg_bot_token"),kind:"password"},{path:"telegram.respond_with_engine",label:f("settings_ui.cfg_respond_with_engine"),kind:"boolean"}]},{key:"engines",label:f("settings_ui.cfg_engines_label"),fields:[{path:"engines.ollama.base_url",label:f("settings_ui.cfg_ollama_url")},{path:"engines.anthropic.api_key",label:f("settings_ui.cfg_anthropic_key"),kind:"password"},{path:"engines.openai.api_key",label:f("settings_ui.cfg_openai_key"),kind:"password"},{path:"engines.groq.api_key",label:f("settings_ui.cfg_groq_key"),kind:"password"},{path:"engines.openrouter.api_key",label:f("settings_ui.cfg_openrouter_key"),kind:"password"},{path:"engines.gemini.api_key",label:f("settings_ui.cfg_gemini_key"),kind:"password"}]}]}function w6(){return[{key:"identity",label:f("settings_ui.cfg_project_label"),description:f("settings_ui.cfg_project_desc"),fields:[{path:"name",label:f("settings_ui.cfg_name")},{path:"version",label:f("settings_ui.cfg_version")},{path:"apf",label:f("settings_ui.cfg_apc_spec")},{path:"apx",label:f("settings_ui.cfg_apx_install")},{path:"apx_id",label:f("settings_ui.cfg_apx_storage_id")}]}]}function k6({pid:e}){const t=lt(),s=Wn(),{project:o,mutate:l}=Xb(e),c=et(`/projects/${e}/config`,()=>ls.config.show(e)),u=String(e)==="0";if(c.isLoading)return r.jsx(ot,{});if(!c.data)return r.jsx(xt,{children:f("project.config.no_data")});const p=async g=>{await ls.apcProject.put(e,g),t.success(f("project.config.save_project")),c.mutate()},m=async g=>{await ls.config.put(e,g),t.success(f("project.config.save_override")),c.mutate()};return r.jsxs("div",{className:"space-y-6",children:[r.jsx(Ke,{title:f("project.config.section_title"),description:f("project.config.section_desc"),children:r.jsxs(dp,{defaultValue:"override",className:"space-y-4",children:[r.jsxs(fp,{children:[r.jsx(ra,{value:"override",children:"Override"}),r.jsx(ra,{value:"project",children:"APC project"}),r.jsx(ra,{value:"effective",children:"Effective"})]}),r.jsx(Ds,{value:"override",children:r.jsx(vx,{sections:j6(),source:c.data.project_only,placeholderSource:c.data.effective,jsonTitle:c.data.project_config_path,jsonDescription:".apc/config.json. Overrides del proyecto.",onSaveFields:async(g,h)=>{await ls.config.set(e,g),h.length&&await ls.config.unset(e,h),t.success(f("project.config.save_fields_success")),c.mutate()},onSaveJson:m})}),r.jsx(Ds,{value:"project",children:r.jsx(vx,{sections:w6(),source:c.data.apc_project||{},jsonTitle:c.data.project_json_path,jsonDescription:".apc/project.json. Metadata APC portable.",onSaveFields:async(g,h)=>{await ls.apcProject.set(e,C6(g),h),t.success(f("project.config.save_meta_success")),c.mutate()},onSaveJson:p})}),r.jsx(Ds,{value:"effective",children:r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-muted-fg",children:f("project.config.effective_read")}),r.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-muted/40 p-3 text-xs",children:JSON.stringify(c.data.effective,null,2)})]})})]})}),!u&&o?r.jsx(S6,{pid:e,label:o.name||o.path,onRebuilt:()=>c.mutate(),onUnregistered:()=>{l(),s("/")}}):null]})}function S6({pid:e,label:t,onRebuilt:s,onUnregistered:o}){const l=lt(),[c,u]=x.useState(null),[p,m]=x.useState(null),g=async()=>{u("rebuild");try{await ls.rebuild(e),l.success(f("project.rebuild_done")),s()}catch(b){l.error(b.message)}finally{u(null),m(null)}},h=async()=>{u("unregister");try{await ls.remove(e),l.success(f("project.unregistered")),o()}catch(b){l.error(b.message)}finally{u(null),m(null)}};return r.jsxs(r.Fragment,{children:[r.jsx(Ke,{title:f("project.danger.title"),description:f("project.danger.subtitle"),children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border bg-muted/30 px-3 py-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-sm font-medium",children:f("project.rebuild")}),r.jsx("div",{className:"text-xs text-muted-fg",children:f("project.danger.rebuild_desc")})]}),r.jsxs(ce,{size:"sm",variant:"secondary",onClick:()=>m("rebuild"),children:[r.jsx(ua,{size:13})," ",f("project.rebuild")]})]}),r.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-red-500/40 bg-red-500/5 px-3 py-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-sm font-medium",children:f("admin.unregister")}),r.jsx("div",{className:"text-xs text-muted-fg",children:f("project.danger.unregister_desc")})]}),r.jsxs(ce,{size:"sm",variant:"destructive",onClick:()=>m("unregister"),children:[r.jsx(Zn,{size:13})," ",f("admin.unregister")]})]})]})}),r.jsx(On,{open:p==="rebuild",onClose:()=>c?null:m(null),title:f("project.danger.rebuild_confirm_title"),description:f("project.danger.rebuild_confirm_desc",{label:t}),size:"sm",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:g,loading:c==="rebuild",children:f("project.rebuild")})]}),children:r.jsx("p",{className:"text-sm text-muted-fg",children:f("project.danger.rebuild_long")})}),r.jsx(On,{open:p==="unregister",onClose:()=>c?null:m(null),title:f("project.danger.unregister_confirm_title"),description:f("project.unregister_confirm",{label:t}),size:"sm",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:()=>m(null),disabled:c!==null,children:f("common.cancel")}),r.jsx(ce,{variant:"destructive",onClick:h,loading:c==="unregister",children:f("admin.unregister")})]}),children:r.jsx("p",{className:"text-sm text-muted-fg",children:f("project.danger.unregister_long")})})]})}function C6(e){const t={};for(const[s,o]of Object.entries(u_(e)))is(o)||(t[s]=o);return t}const N6=["","es","en","pt","fr","it","de"],sw=e=>e.split(",").map(t=>t.trim()).filter(Boolean);function pN(e){return e.is_master?{gradient:"from-violet-600 to-indigo-600",Icon:Ga}:{gradient:"from-slate-600 to-gray-600",Icon:un}}function E6(e){const t=e.filter(u=>u.is_master),s=t.length===1?t[0]:null,o=u=>u.parent?u.parent:s&&!u.is_master&&u.slug!==s.slug?s.slug:null,l=new Map,c=[];for(const u of e){const p=o(u);p&&e.some(m=>m.slug===p)?(l.has(p)||l.set(p,[]),l.get(p).push(u)):c.push(u)}return{roots:c,childrenByParent:l}}function R6({pid:e}){const t=Wn();lt();const s=et(`/projects/${e}/agents`,()=>rn.list(e)),[o,l]=x.useState("hierarchy"),[c,u]=x.useState(!1),[p,m]=x.useState(!1),g=s.data||[],h=N=>t(`/p/${e}/agents/${N}`),b=N=>t(N?`/p/${e}/chat?agent=${N}`:`/p/${e}/chat`),{roots:v,childrenByParent:k}=x.useMemo(()=>E6(g),[g]);return r.jsxs(Ke,{title:f("project.agents.title"),description:f("project.agents.subtitle_full"),action:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex rounded-lg border border-border p-0.5",children:[r.jsxs("button",{onClick:()=>l("hierarchy"),className:Te("flex items-center gap-1 rounded-md px-2 py-1 text-xs",o==="hierarchy"?"bg-accent text-accent-fg":"text-muted-fg"),children:[r.jsx(Hx,{size:13})," ",f("project.agents.hierarchy")]}),r.jsxs("button",{onClick:()=>l("list"),className:Te("flex items-center gap-1 rounded-md px-2 py-1 text-xs",o==="list"?"bg-accent text-accent-fg":"text-muted-fg"),children:[r.jsx(HM,{size:13})," ",f("project.agents.list_view")]})]}),r.jsxs(ce,{size:"sm",variant:"ghost",onClick:()=>m(!0),children:[r.jsx(ZM,{size:13})," ",f("project.agents.import")]}),r.jsxs(ce,{size:"sm",variant:"secondary",onClick:()=>b(),children:[r.jsx(Gs,{size:13})," ",f("project.agents.chat")]}),r.jsxs(ce,{size:"sm",variant:"primary","data-testid":"agent-new",onClick:()=>u(!0),children:[r.jsx(tn,{size:14})," ",f("project.agents.new")]})]}),children:[s.isLoading&&r.jsx(ot,{}),!s.isLoading&&g.length===0&&r.jsx(xt,{children:f("project.agents.empty_text")}),!s.isLoading&&g.length>0&&(o==="hierarchy"?r.jsx(A6,{roots:v,childrenByParent:k,onOpen:h,onChat:b}):r.jsx(M6,{agents:g,onOpen:h,onChat:b})),r.jsx(O6,{open:c,pid:e,agents:g,onClose:()=>u(!1),onCreated:()=>{u(!1),s.mutate()}}),r.jsx(T6,{open:p,pid:e,existing:g.map(N=>N.slug),onClose:()=>m(!1),onImported:()=>s.mutate()})]})}function T6({open:e,onClose:t,onImported:s,pid:o,existing:l}){const c=lt(),u=et(e?"/agents/vault":null,()=>rn.vault()),[p,m]=x.useState(""),g=u.data||[],h=async b=>{m(b);try{await rn.import(o,b),c.success(f("project.agents.import_success",{slug:b})),s()}catch(v){c.error(v.message)}finally{m("")}};return r.jsxs(On,{open:e,onClose:t,title:f("project.agents.import_title"),description:f("project.agents.import_desc"),size:"lg",footer:r.jsx(ce,{variant:"ghost",onClick:t,children:f("common.close")}),children:[u.isLoading&&r.jsx(ot,{}),!u.isLoading&&g.length===0&&r.jsx(xt,{children:f("project.agents.import_empty")}),r.jsx("ul",{className:"space-y-2",children:g.map(b=>{const v=l.includes(b.slug);return r.jsxs("li",{className:"flex items-center gap-3 rounded-lg border border-border bg-muted/30 p-3",children:[r.jsx(un,{size:16,className:"shrink-0 text-muted-fg"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium",children:b.slug}),b.is_master&&r.jsxs(Fe,{tone:"success",children:[r.jsx(Ga,{size:9})," ",f("project.agents.orchestrator")]}),b.model&&r.jsx(Fe,{tone:"info",children:b.model})]}),b.description&&r.jsx("p",{className:"truncate text-xs text-muted-fg",children:b.description})]}),r.jsx(ce,{size:"sm",variant:"primary",disabled:v||p===b.slug,loading:p===b.slug,onClick:()=>h(b.slug),children:f(v?"project.agents.import_already":"project.agents.import_btn")})]},b.slug)})})]})}function A6({roots:e,childrenByParent:t,onOpen:s,onChat:o}){return r.jsx("div",{className:"space-y-8",children:e.map(l=>{const c=t.get(l.slug)||[];return r.jsxs("div",{className:"flex flex-col items-center",children:[r.jsx(rh,{agent:l,onOpen:s,onChat:o,wide:!0}),c.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"h-5 w-px bg-border"}),r.jsx("div",{className:"flex flex-wrap items-start justify-center gap-4 border-t border-border pt-5",children:c.map(u=>r.jsxs("div",{className:"flex flex-col items-center",children:[r.jsx(rh,{agent:u,onOpen:s,onChat:o}),(t.get(u.slug)||[]).length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"h-4 w-px bg-border"}),r.jsx("div",{className:"flex flex-wrap justify-center gap-3 border-t border-border pt-4",children:(t.get(u.slug)||[]).map(p=>r.jsx(rh,{agent:p,onOpen:s,onChat:o,compact:!0},p.slug))})]})]},u.slug))})]})]},l.slug)})})}function rh({agent:e,onOpen:t,onChat:s,wide:o,compact:l}){const{gradient:c,Icon:u}=pN(e);return r.jsxs("div",{"data-testid":`agent-card-${e.slug}`,className:Te("cursor-pointer rounded-xl border border-border bg-card p-3 transition-colors hover:border-muted-fg/50",o?"w-64":l?"w-44":"w-52"),onClick:()=>t(e.slug),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:Te("flex size-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br",c),children:r.jsx(u,{className:"size-4 text-white"})}),r.jsx("span",{className:"truncate text-sm font-semibold",children:e.slug})]}),r.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.is_master&&r.jsxs(Fe,{tone:"success",children:[r.jsx(Ga,{size:9})," ",f("project.agents.orchestrator")]}),e.role&&r.jsx(Fe,{children:e.role}),e.model&&!l&&r.jsx(Fe,{tone:"info",children:e.model})]}),r.jsxs("div",{className:"mt-2 flex items-center gap-3 border-t border-border pt-2 text-xs text-muted-fg",onClick:p=>p.stopPropagation(),children:[r.jsxs("button",{onClick:()=>t(e.slug),className:"flex items-center gap-1 hover:text-foreground",children:[r.jsx(Ef,{size:12})," ",f("project.agents.view")]}),r.jsxs("button",{onClick:()=>s(e.slug),className:"flex items-center gap-1 text-emerald-500 hover:text-emerald-400",children:[r.jsx(Gs,{size:12})," ",f("project.agents.chat")]})]})]})}function M6({agents:e,onOpen:t,onChat:s}){const o=[...e].sort((l,c)=>+!!c.is_master-+!!l.is_master||l.slug.localeCompare(c.slug));return r.jsx("div",{className:"space-y-2",children:o.map(l=>{const{gradient:c,Icon:u}=pN(l);return r.jsxs("div",{"data-testid":`agent-card-${l.slug}`,className:"flex cursor-pointer items-center gap-4 rounded-xl border border-border bg-muted/30 p-3 hover:border-muted-fg/50",onClick:()=>t(l.slug),children:[r.jsx("div",{className:Te("flex size-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br",c),children:r.jsx(u,{className:"size-4 text-white"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx("span",{className:"text-sm font-semibold",children:l.slug}),l.is_master&&r.jsxs(Fe,{tone:"success",children:[r.jsx(Ga,{size:10})," ",f("project.agents.orchestrator")]}),l.role&&r.jsx(Fe,{children:l.role}),l.model&&r.jsx(Fe,{tone:"info",children:l.model}),l.parent&&r.jsxs("span",{className:"text-[10px] text-violet-400",children:["↳ ",l.parent]})]}),l.description&&r.jsx("p",{className:"mt-1 truncate text-xs text-muted-fg",children:l.description}),r.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[l.skills?.map(p=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(ma,{size:9})," ",p]},p)),l.tools?.map(p=>r.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] text-muted-fg",children:[r.jsx(Zl,{size:9})," ",p]},p))]})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3 text-xs text-muted-fg",onClick:p=>p.stopPropagation(),children:[r.jsxs("button",{onClick:()=>t(l.slug),className:"flex items-center gap-1 hover:text-foreground",children:[r.jsx(Ef,{size:12})," ",f("project.agents.view")]}),r.jsxs("button",{onClick:()=>s(l.slug),className:"flex items-center gap-1 text-emerald-500 hover:text-emerald-400",children:[r.jsx(Gs,{size:12})," ",f("project.agents.chat")]})]})]},l.slug)})})}function O6({open:e,onClose:t,onCreated:s,pid:o,agents:l}){const c=lt(),[u,p]=x.useState(""),[m,g]=x.useState(""),[h,b]=x.useState(""),[v,k]=x.useState(""),[N,j]=x.useState(""),[y,C]=x.useState(""),[S,E]=x.useState(""),[R,A]=x.useState(!1),[T,M]=x.useState(""),[z,B]=x.useState(!1),L=()=>{p(""),g(""),b(""),k(""),j(""),C(""),E(""),A(!1),M("")},U=async()=>{if(!/^[a-z][a-z0-9_-]*$/.test(u)){c.error(f("project.agents.slug_invalid"));return}B(!0);try{await rn.create(o,{slug:u,role:m||void 0,model:h||void 0,language:v||void 0,description:N||void 0,skills:sw(y),tools:sw(S),is_master:R,parent:T||void 0}),c.success(f("project.agents.create_success",{slug:u})),s(),L()}catch(D){c.error(D?.message||f("project.agents.create_error"))}finally{B(!1)}};return r.jsx(On,{open:e,onClose:t,title:f("project.agents.new_title"),description:f("project.agents.new_desc"),size:"lg",footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:z,children:f("common.cancel")}),r.jsx(ce,{variant:"primary","data-testid":"agent-create-submit",onClick:U,loading:z,children:f("common.create")})]}),children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("project.agents.slug_label"),children:r.jsx(Ne,{autoFocus:!0,"data-testid":"agent-slug",value:u,onChange:D=>p(D.target.value),placeholder:f("project.agents.slug_ph")})}),r.jsx(le,{label:f("project.agents.role_label"),children:r.jsx(Ne,{value:m,onChange:D=>g(D.target.value),placeholder:f("project.agents.role_ph")})})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("project.agents.model_label"),hint:f("project.agents.model_hint"),children:r.jsx(Ne,{value:h,onChange:D=>b(D.target.value)})}),r.jsx(le,{label:f("project.agents.lang_label"),children:r.jsx(bt,{value:v,onChange:k,options:N6.map(D=>({value:D,label:D||"—"}))})})]}),r.jsx(le,{label:f("project.agents.desc_label"),children:r.jsx(Mn,{rows:2,value:N,onChange:D=>j(D.target.value),placeholder:f("project.agents.desc_ph")})}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsx(le,{label:f("project.agents.skills_label"),children:r.jsx(Ne,{value:y,onChange:D=>C(D.target.value),placeholder:f("project.agents.skills_ph")})}),r.jsx(le,{label:f("project.agents.tools_label"),children:r.jsx(Ne,{value:S,onChange:D=>E(D.target.value),placeholder:f("project.agents.tools_ph")})})]}),r.jsxs("div",{className:"grid grid-cols-2 items-end gap-3",children:[r.jsx(le,{label:f("project.agents.parent_label"),hint:f("project.agents.parent_hint"),children:r.jsx(bt,{value:T,onChange:M,placeholder:f("project.agents.none_parent"),options:[{value:"",label:f("project.agents.none_parent")},...l.filter(D=>D.slug!==u).map(D=>({value:D.slug,label:D.slug}))]})}),r.jsx(Ft,{checked:R,onChange:A,label:f("project.agents.master_label")})]})]})})}function Rd(e){return e.split(`
623
623
  `).map(t=>t.trim()).filter(Boolean)}function Lc(){return{exec_agent:{label:f("agents_ui.kind_exec_agent"),desc:f("agents_ui.kind_exec_agent_desc"),icon:un},super_agent:{label:f("agents_ui.kind_super_agent"),desc:f("agents_ui.kind_super_agent_desc"),icon:Ga},telegram:{label:f("agents_ui.kind_telegram"),desc:f("agents_ui.kind_telegram_desc"),icon:Gs},shell:{label:f("agents_ui.kind_shell"),desc:f("agents_ui.kind_shell_desc"),icon:Ya},heartbeat:{label:f("agents_ui.kind_heartbeat"),desc:f("agents_ui.kind_heartbeat_desc"),icon:Dl}}}function z6(e){const t=Lc();return Object.keys(t).filter(s=>s!=="heartbeat"||e==="heartbeat").map(s=>({value:s,label:t[s].label,description:t[s].desc,icon:t[s].icon}))}function d_(e){if(!e)return"—";if(e.startsWith("every:")){const t=e.slice(6),s=t.match(/^(\d+)(s|m|h|d)$/);if(s){const o=s[1],l={s:f("agents_ui.unit_seconds"),m:f("agents_ui.unit_minutes"),h:f("agents_ui.unit_hours"),d:f("agents_ui.unit_days")}[s[2]]||s[2];return f("agents_ui.every_n_unit",{n:o,unit:l})}return f("agents_ui.every_v",{v:t})}return e.startsWith("once:")?`once · ${new Date(e.slice(5)).toLocaleString()}`:e.startsWith("cron ")?`cron · ${e.slice(5)}`:e}function D6(){return[{label:f("agents_ui.preset_every_10m"),value:"every:10m"},{label:f("agents_ui.preset_hourly"),value:"every:1h"},{label:f("agents_ui.preset_daily_9am"),value:"cron 0 9 * * *"},{label:f("agents_ui.preset_weekdays_9am"),value:"cron 0 9 * * 1-5"}]}function mN(){return[{v:"{{pre_output}}",where:"prompt",desc:f("agents_ui.var_pre_output_prompt")},{v:"$APX_LLM_OUTPUT",where:"post",desc:f("agents_ui.var_llm_output")},{v:"$APX_STATUS",where:"post",desc:f("agents_ui.var_status")},{v:"$APX_SKIPPED",where:"post",desc:f("agents_ui.var_skipped")},{v:"$APX_PRE_OUTPUT",where:"post",desc:f("agents_ui.var_pre_output")},{v:"$APX_PRE_OUTPUT_FILE",where:"post",desc:f("agents_ui.var_pre_output_file")},{v:"$APX_PRE_EXIT",where:"post",desc:f("agents_ui.var_pre_exit")},{v:"$APX_ROUTINE",where:"pre/post",desc:f("agents_ui.var_routine")}]}function sc(e){return mN().filter(t=>e==="pre"?t.where.includes("pre"):e==="prompt"?t.where==="prompt":t.where==="post"||t.where==="pre/post")}function L6({routines:e,selectedName:t,onSelect:s}){return r.jsxs("aside",{className:"flex h-full min-h-0 flex-col border-r border-border",children:[r.jsx("div",{className:"shrink-0 px-3 py-2.5 text-[11px] font-semibold uppercase tracking-wide text-muted-fg",children:f("project.routines.list_title")}),r.jsx("ul",{className:"min-h-0 flex-1 space-y-1 overflow-y-auto p-2 pt-0",children:e.map(o=>{const l=Lc()[o.kind],c=l?.icon||Ll,u=o.name===t;return r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>s(o.name),"aria-current":u,className:Te("w-full rounded-lg border px-2.5 py-2 text-left transition-colors",u?"border-primary/50 bg-primary/10":"border-transparent hover:border-border hover:bg-accent/40"),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:Te("flex size-6 shrink-0 items-center justify-center rounded-md",o.enabled?"bg-emerald-500/15 text-emerald-400":"bg-muted text-muted-fg"),children:r.jsx(c,{size:13})}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:o.name}),!o.enabled&&r.jsx("span",{className:"shrink-0 text-[10px] text-muted-fg",children:f("project.routines.paused")}),r.jsx(Qc,{ok:o.last_status==="ok"?!0:o.last_status==="error"?!1:null})]}),r.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 pl-8 text-[10px] text-muted-fg",children:[r.jsx("span",{className:"truncate",children:l?.label||o.kind}),r.jsxs("span",{className:"shrink-0",children:["⏱ ",d_(o.schedule)]})]})]})},o.name)})})]})}function P6({title:e,body:t,mono:s}){return r.jsxs("div",{className:"space-y-1",children:[r.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-fg",children:e}),r.jsx("div",{className:Te("max-h-44 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border bg-muted/20 px-3 py-2 text-xs",s&&"font-mono"),children:t.trim()?t:r.jsx("span",{className:"text-muted-fg",children:f("project.routines.block_empty")})})]})}function gN(e){const t=e.meta||{};return t.skipped?"skipped":t.status==="error"?"error":"ok"}function hN(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function xN({st:e}){return e==="ok"?r.jsx(ho,{size:13,className:"shrink-0 text-emerald-500"}):e==="error"?r.jsx(Ys,{size:13,className:"shrink-0 text-destructive"}):r.jsx(oM,{size:13,className:"shrink-0 text-amber-500"})}function bN(e){return f(e==="ok"?"project.routines.status_ok":e==="error"?"project.routines.status_error":"project.routines.status_skipped")}function oh({title:e,children:t}){return r.jsxs("div",{className:"space-y-1",children:[r.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-fg",children:e}),t]})}const lh="whitespace-pre-wrap break-words rounded-lg border border-border bg-muted/20 px-3 py-2 font-mono text-[11px]";function I6({m:e,onClose:t}){const s=gN(e),o=e.meta||{},l=o.result||{},c=o.flow||null,u=String(l.reply??l.text??l.stdout??""),p=String(l.error??l.stderr??""),m=String(l.note??""),g=r.jsx("span",{className:"text-muted-fg",children:f("project.routines.block_empty")});return r.jsxs("div",{className:"flex min-h-0 flex-col border-l border-border",children:[r.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 px-4 py-2",children:[r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx(xN,{st:s}),r.jsx("span",{className:Te("font-medium",s==="ok"&&"text-emerald-500",s==="error"&&"text-destructive",s==="skipped"&&"text-amber-500"),children:bN(s)}),r.jsx("span",{className:"font-mono text-muted-fg",children:hN(e.ts)})]}),r.jsx("button",{type:"button",onClick:t,"aria-label":f("project.routines.runs_close"),className:"rounded-md p-1 text-muted-fg hover:bg-muted hover:text-foreground",children:r.jsx(Ys,{size:14})})]}),r.jsxs("div",{className:"min-h-0 flex-1 space-y-3 overflow-y-auto px-4 pb-4 text-xs",children:[e.body&&r.jsx("div",{className:"text-muted-fg",children:e.body}),c?.pre&&r.jsx(oh,{title:f("project.routines.block_pre"),children:c.pre.output?.trim()?r.jsx("pre",{className:lh,children:c.pre.output}):g}),r.jsx(oh,{title:f("project.routines.runs_output"),children:u?r.jsx("pre",{className:lh,children:u}):p?r.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-lg bg-destructive/10 px-3 py-2 font-mono text-[11px] text-destructive",children:p}):m?r.jsx("div",{className:"text-muted-fg",children:m}):g}),c?.post&&c.post.length>0&&r.jsx(oh,{title:f("project.routines.block_post"),children:r.jsx("div",{className:"space-y-1.5",children:c.post.map((h,b)=>r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"font-mono text-[10px] text-muted-fg",children:["$ ",h.cmd," ",r.jsxs("span",{className:"opacity-70",children:["· exit ",h.exit]})]}),(h.stdout||h.stderr)&&r.jsx("pre",{className:lh,children:h.stdout||h.stderr})]},b))})})]})]})}function B6({pid:e,name:t,running:s}){const o=et(`/projects/${e}/routines/${t}/runs`,async()=>(await pf.project(e,{channel:"routine",limit:200})).filter(g=>g.meta?.routine===t&&(g.actor_id==="apx:routine"||g.type==="system"))),l=(o.data||[]).slice(0,50),[c,u]=x.useState(null),p=c&&l.find(m=>m.ts===c)||null;return r.jsxs("div",{className:"flex min-h-0 flex-1 flex-col border-t border-border",children:[r.jsx("div",{className:"shrink-0 px-4 pb-1.5 pt-3 text-[11px] font-semibold uppercase tracking-wide text-muted-fg",children:f("project.routines.runs_title")}),r.jsxs("div",{className:Te("grid min-h-0 flex-1 overflow-hidden",p?"grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]":"grid-cols-1"),children:[r.jsxs("div",{className:"min-h-0 overflow-y-auto px-4 pb-4",children:[o.isLoading&&r.jsx(ot,{}),!o.isLoading&&l.length===0&&r.jsx("div",{className:"text-xs text-muted-fg",children:f("project.routines.runs_empty")}),r.jsxs("ul",{className:"space-y-1",children:[s&&r.jsx("li",{children:r.jsxs("div",{className:"flex w-full items-center gap-2 rounded-md border border-primary/40 bg-primary/5 px-3 py-1.5 text-xs",children:[r.jsx(vs,{size:12}),r.jsx("span",{className:"text-muted-fg",children:f("project.routines.running")})]})}),l.map((m,g)=>{const h=gN(m),b=c===m.ts;return r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>u(b?null:m.ts),"aria-current":b,className:Te("flex w-full items-center gap-2 rounded-md border px-3 py-1.5 text-left text-xs transition-colors",b?"border-primary/50 bg-primary/10":"border-border bg-muted/30 hover:border-muted-fg/40"),children:[r.jsx(xN,{st:h}),r.jsx("span",{className:"font-mono text-muted-fg",children:hN(m.ts)}),r.jsx("span",{className:Te("font-medium",h==="ok"&&"text-emerald-500",h==="error"&&"text-destructive",h==="skipped"&&"text-amber-500"),children:bN(h)})]})},`${m.ts}-${g}`)})]})]}),p&&r.jsx(I6,{m:p,onClose:()=>u(null)})]})]})}function U6({pid:e,routine:t,onEdit:s,onRun:o,onToggle:l,onDelete:c,running:u}){const p=Lc()[t.kind],m=p?.icon||Ll,g=t.spec||{},h=t.pre_commands||[],b=t.post_commands||[],v=[];return h.length&&v.push({title:f("project.routines.block_pre"),body:h.join(`
624
624
  `),mono:!0}),t.kind==="exec_agent"||t.kind==="super_agent"?v.push({title:f("project.routines.block_prompt"),body:String(g.prompt||"")}):t.kind==="telegram"?v.push({title:f("project.routines.block_text"),body:String(g.text||"")}):t.kind==="shell"?v.push({title:f("project.routines.block_command"),body:String(g.command||""),mono:!0}):t.kind==="heartbeat"&&v.push({title:f("project.routines.block_text"),body:String(g.message||"")}),b.length&&v.push({title:f("project.routines.block_post"),body:b.join(`
625
625
  `),mono:!0}),r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[r.jsxs("div",{className:"min-h-0 shrink space-y-4 overflow-y-auto p-4",children:[r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[r.jsx("span",{className:Te("flex size-7 shrink-0 items-center justify-center rounded-lg",t.enabled?"bg-emerald-500/15 text-emerald-400":"bg-muted text-muted-fg"),children:r.jsx(m,{size:14})}),r.jsx("h3",{className:"truncate text-base font-semibold",children:t.name}),r.jsx(Fe,{tone:t.kind==="shell"?"warning":"info",children:p?.label||t.kind})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[r.jsx(Ft,{checked:t.enabled,onChange:l}),r.jsx(Ye,{content:f("common.run"),children:r.jsx(ce,{size:"sm",variant:"secondary",onClick:o,loading:u,children:r.jsx($x,{size:13})})}),r.jsx(Ye,{content:f("project.routines.edit_hint"),children:r.jsxs(ce,{size:"sm",variant:"secondary",onClick:s,children:[r.jsx(Eo,{size:13})," ",f("project.routines.edit_btn")]})}),r.jsx(Ye,{content:f("common.delete"),children:r.jsx(ce,{size:"sm",variant:"destructive",onClick:c,children:r.jsx(Zn,{size:13})})})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-fg",children:[r.jsxs("span",{children:["⏱ ",d_(t.schedule)]}),t.next_run_at&&r.jsxs("span",{children:[f("project.routines.next_run")," ",new Date(t.next_run_at).toLocaleString()]}),t.last_run_at&&r.jsxs("span",{children:[f("project.routines.last_run")," ",new Date(t.last_run_at).toLocaleString()]}),r.jsxs("span",{className:Te(t.last_status==="ok"&&"text-emerald-500",t.last_status==="error"&&"text-destructive"),children:[f("agents_ui.last_label")," ",t.last_status||"—"]})]}),t.last_error&&r.jsx("div",{className:"rounded-md bg-destructive/10 px-2 py-1 text-xs text-destructive",children:t.last_error}),r.jsx("div",{className:"space-y-3",children:v.map(k=>r.jsx(P6,{title:k.title,body:k.body,mono:k.mono},k.title))})]}),r.jsx(B6,{pid:e,name:t.name,running:u})]})}function _l({label:e,hint:t,value:s,onChange:o,vars:l,rows:c=3,mono:u,placeholder:p}){const m=x.useRef(null),g=h=>{const b=m.current?.querySelector("textarea");if(!b){o(s?`${s}${h}`:h);return}const v=b.selectionStart??s.length,k=b.selectionEnd??s.length,N=s.slice(0,v)+h+s.slice(k);o(N),requestAnimationFrame(()=>{b.focus();const j=v+h.length;b.setSelectionRange(j,j)})};return r.jsxs("div",{className:"space-y-1",children:[r.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:e}),t&&r.jsx("div",{className:"text-[11px] text-muted-foreground/70",children:t}),r.jsxs("div",{ref:m,className:"space-y-1.5",children:[r.jsx(Mn,{rows:c,className:Te(u&&"font-mono text-xs"),value:s,onChange:h=>o(h.target.value),placeholder:p}),l.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1",children:l.map(h=>r.jsx("button",{type:"button",onClick:()=>g(h.v),className:"inline-flex items-center rounded-md border border-border bg-card px-1.5 py-0.5 font-mono text-[10px] text-muted-fg transition-colors hover:border-muted-fg/50 hover:text-foreground",children:h.v},h.v))})]})]})}function H6(){return r.jsxs("div",{className:"rounded-lg border border-border bg-muted/10 p-3",children:[r.jsx("div",{className:"mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-fg",children:f("project.routines.vars_title")}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:mN().map(e=>r.jsx(Ye,{content:r.jsx("span",{className:"block max-w-[240px] whitespace-normal leading-snug",children:e.desc}),children:r.jsxs("span",{className:"inline-flex cursor-help items-center gap-1 rounded-md border border-border bg-card px-1.5 py-0.5 font-mono text-[10px]",children:[e.v,r.jsxs("span",{className:"not-italic text-muted-fg",children:["· ",e.where]})]})},e.v))})]})}function V6({draft:e,onClose:t,onSaved:s,pid:o}){const l=lt(),c=et(e?`/projects/${o}/agents`:null,()=>rn.list(o)),[u,p]=x.useState(!1),[m,g]=x.useState(""),[h,b]=x.useState("super_agent"),[v,k]=x.useState("every:10m"),[N,j]=x.useState(!0),[y,C]=x.useState(""),[S,E]=x.useState(""),[R,A]=x.useState("default"),[T,M]=x.useState(""),[z,B]=x.useState(""),[L,U]=x.useState(""),[D,I]=x.useState("heartbeat"),[V,$]=x.useState(""),[q,Y]=x.useState(""),[K,F]=x.useState(""),X=et(e&&h==="telegram"?"/telegram/channels":null,()=>An.channels.list());x.useEffect(()=>{if(!e)return;const ie=e.spec&&typeof e.spec=="object"?e.spec:{};g(e.name||""),b(e.kind||"super_agent"),k(e.schedule||"every:10m"),j(e.enabled??!0),C(ie.agent||""),E(ie.prompt||""),A(ie.channel||"default"),M(ie.chat_id?String(ie.chat_id):""),B(ie.text||""),U(ie.command||""),I(ie.channel||"heartbeat"),$(ie.message||""),Y((e.pre_commands||[]).join(`
@@ -648,4 +648,4 @@ Minimum version required to store current data is: `+U+`.
648
648
  `).map((b,v)=>r.jsxs("tr",{className:"hover:bg-accent/20",children:[r.jsx("td",{className:"w-12 select-none border-r border-border/30 px-3 py-0 text-right align-top text-[10px] text-muted-foreground/40","aria-hidden":"true",children:v+1}),r.jsx("td",{className:"px-4 py-0 align-top text-foreground/90 whitespace-pre",children:b||" "})]},v))})})})]})}function xU({pid:e,className:t,initCmd:s,onClose:o}){const[l,c]=x.useState([]),[u,p]=x.useState(""),[m,g]=x.useState(!1),[h,b]=x.useState([]),[v,k]=x.useState(-1),N=x.useRef(null),j=x.useRef(null);x.useEffect(()=>{N.current?.scrollIntoView({behavior:"smooth"})},[l]),x.useEffect(()=>{s&&(p(s),setTimeout(()=>j.current?.focus(),50))},[s]);const y=async S=>{const E=S.trim();if(E){b(R=>[E,...R.slice(0,49)]),k(-1),c(R=>[...R,{type:"cmd",text:`$ ${E}`}]),g(!0);try{const R=await ge.post("/run",{cmd:E,project:e});R.stdout&&c(A=>[...A,{type:"out",text:R.stdout}]),R.stderr&&c(A=>[...A,{type:"err",text:R.stderr}])}catch(R){c(A=>[...A,{type:"err",text:String(R.message)}])}finally{g(!1)}}},C=S=>{if(S.key==="Enter")y(u),p("");else if(S.key==="ArrowUp"){S.preventDefault();const E=Math.min(v+1,h.length-1);k(E),p(h[E]??"")}else if(S.key==="ArrowDown"){S.preventDefault();const E=Math.max(v-1,-1);k(E),p(E===-1?"":h[E]??"")}};return r.jsxs("div",{className:Te("flex h-full min-h-0 flex-col bg-card/60",t),"data-testid":"code-terminal",children:[r.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-1",children:[r.jsx(Ya,{className:"size-3 text-muted-foreground"}),r.jsx("span",{className:"flex-1 text-[11px] text-muted-foreground",children:"Terminal"}),r.jsx(Ye,{content:f("code_module.terminal_clear"),children:r.jsx("button",{type:"button",onClick:()=>c([]),className:"rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground",children:r.jsx(_M,{className:"size-3"})})}),r.jsx(Ye,{content:f("code_module.terminal_close"),children:r.jsx("button",{type:"button",onClick:()=>o?.(),className:"rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground",children:r.jsx(Ys,{className:"size-3"})})})]}),r.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-1 font-mono text-[11px] leading-snug cursor-text",onClick:()=>j.current?.focus(),children:[l.map((S,E)=>r.jsx("div",{className:Te("whitespace-pre-wrap break-all",S.type==="cmd"&&"text-emerald-400",S.type==="err"&&"text-rose-400",S.type==="out"&&"text-foreground/90"),children:S.text},E)),r.jsx("div",{ref:N})]}),r.jsxs("div",{className:"flex shrink-0 items-center border-t border-border px-3 py-1",children:[r.jsx("span",{className:"mr-2 text-[11px] text-emerald-400 font-mono",children:"$"}),r.jsx("input",{ref:j,value:u,onChange:S=>p(S.target.value),onKeyDown:C,disabled:m,placeholder:m?"ejecutando…":"comando…",className:"flex-1 bg-transparent font-mono text-[11px] text-foreground outline-none placeholder:text-muted-foreground/50 disabled:opacity-50",spellCheck:!1,autoComplete:"off"})]})]})}const cc="super-agent";function Bh(){return r.jsx(E_,{className:"relative z-10 w-px shrink-0 cursor-col-resize bg-border transition-colors hover:bg-primary/50 active:bg-primary/70"})}function bU(){return r.jsx(E_,{className:"relative z-10 h-px shrink-0 cursor-row-resize bg-border transition-colors hover:bg-primary/50 active:bg-primary/70"})}function _U(){const e=lt(),t=et("/projects",()=>ls.list()),s=x.useMemo(()=>t.data||[],[t.data]),[o,l]=x.useState(""),[c,u]=x.useState(null),[p,m]=x.useState(cc),[g,h]=x.useState([]),[b,v]=x.useState(""),[k,N]=x.useState(!1),[j,y]=x.useState(!0),[C,S]=x.useState(!0),[E,R]=x.useState(!1),[A,T]=x.useState(""),[M,z]=x.useState(!1),B=x.useRef(null),[L,U]=x.useState([]),[D,I]=x.useState("chat"),V=x.useCallback(_e=>{R(!0),T(_e)},[]);x.useEffect(()=>{!o&&s.length&&l(String(s[0].id))},[o,s]);const $=et(o?["code-sessions",o]:null,()=>Ba.sessions.list(o)),q=et(o?["agents",o]:null,()=>rn.list(o)),Y=et(o&&c?["code-session",o,c]:null,()=>Ba.sessions.get(o,c)),K=et(o&&c?["code-changes",o,c]:null,()=>Ba.changes(o,c));x.useEffect(()=>{const _e=$.data||[];!c&&_e.length&&u(_e[0].id),c&&_e.length&&!_e.some(Oe=>Oe.id===c)&&u(_e[0]?.id??null)},[$.data,c]),x.useEffect(()=>{Y.data&&m(Y.data.agentSlug||cc)},[Y.data]),x.useEffect(()=>{k||(Y.data?h(Y.data.messages||[]):c||h([]))},[Y.data,c,k]),x.useEffect(()=>()=>B.current?.abort(),[]);const F=Y.data,X=F?.mode==="plan"?"plan":"build",P=F?.model||"",G=_e=>{_e===o||k||(l(_e),u(null),h([]))},Z=_e=>{k||_e===c||(u(_e),h([]))},ee=async()=>{if(!(!o||k))try{const _e=await Ba.sessions.create(o,{title:f("code_module.untitled"),agentSlug:p!==cc?p:null});await $.mutate(),u(_e.id),h([])}catch(_e){e.error(_e.message)}},de=async(_e,Oe)=>{const He=window.prompt(f("code_module.rename"),Oe);if(!(!He||He===Oe))try{await Ba.sessions.update(o,_e,{title:He}),await $.mutate(),_e===c&&await Y.mutate()}catch(Xe){e.error(Xe.message)}},fe=async _e=>{if(!k&&window.confirm(f("code_module.delete_confirm")))try{await Ba.sessions.remove(o,_e),_e===c&&(u(null),h([])),await $.mutate()}catch(Oe){e.error(Oe.message)}},ae=async _e=>{if(m(_e),!!c)try{await Ba.sessions.update(o,c,{agentSlug:_e!==cc?_e:null}),await Promise.all([Y.mutate(),$.mutate()])}catch(Oe){e.error(Oe.message)}},oe=x.useCallback(async _e=>{if(c)try{await Ba.sessions.update(o,c,_e),await Promise.all([Y.mutate(),$.mutate()])}catch(Oe){e.error(Oe.message)}},[o,c,Y,$,e]),me=()=>{B.current?.abort(),N(!1)},Ae=_e=>h(Oe=>{const He=[...Oe],Xe=He[He.length-1];return Xe&&Xe.role==="assistant"&&(He[He.length-1]=_e(Xe)),He}),ie=async _e=>{const Oe=(_e??b).trim();if(!Oe||k||!o||!c)return;const He=new Date().toISOString();h(sn=>[...sn,{role:"user",parts:[{kind:"text",text:Oe}],ts:He},{role:"assistant",parts:[],ts:He,pending:!0}]),v(""),N(!0);const Xe=new AbortController;B.current=Xe;const rt=sn=>{if(sn.type==="error"){e.error(sn.error||f("modules_ui.code_stream_error"));return}Ae(dn=>g_(dn,sn))};try{await Ba.stream(o,c,{prompt:Oe},rt,Xe.signal),Ae(sn=>({...sn,pending:!1}))}catch(sn){Xe.signal.aborted?Ae(dn=>({...dn,pending:!1,parts:[...dn.parts,{kind:"text",text:f("code_module.stopped")}]})):(e.error(sn.message),h(dn=>dn.filter((pt,Et)=>Et!==dn.length-1)))}finally{B.current===Xe&&(B.current=null),N(!1),Y.mutate(),$.mutate(),K.mutate()}},pe=async _e=>{try{await navigator.clipboard.writeText(_e),e.info(f("modules_ui.code_copied"))}catch{}},Se=x.useCallback(_e=>{I(_e),U(Oe=>Oe.some(He=>He.path===_e)?Oe:[...Oe,{path:_e,content:"",loading:!0}]),ge.post("/run",{cmd:`cat "${_e}"`,project:o}).then(Oe=>{const He=Oe.stdout||Oe.stderr||f("modules_ui.code_file_empty");U(Xe=>Xe.map(rt=>rt.path===_e?{...rt,content:He,loading:!1}:rt))}).catch(Oe=>{U(He=>He.map(Xe=>Xe.path===_e?{...Xe,content:f("modules_ui.code_file_error",{msg:Oe.message}),loading:!1}:Xe))})},[o]),je=x.useCallback(_e=>{U(Oe=>Oe.filter(He=>He.path!==_e)),I(Oe=>Oe===_e?"chat":Oe)},[]),Be=x.useCallback(_e=>{const Oe=`artifacts/${_e}`;I(Oe),U(He=>He.some(Xe=>Xe.path===Oe)?He:[...He,{path:Oe,content:"",loading:!0,artifactName:_e}]),Ml.read(o,_e).then(He=>{U(Xe=>Xe.map(rt=>rt.path===Oe?{...rt,content:He.content,loading:!1}:rt))}).catch(He=>{U(Xe=>Xe.map(rt=>rt.path===Oe?{...rt,content:f("modules_ui.code_file_error",{msg:He.message}),loading:!1}:rt))})},[o]),Ve=x.useCallback(async(_e,Oe)=>{const He=L.find(Xe=>Xe.path===_e);if(He?.artifactName)try{await Ml.write(o,He.artifactName,Oe),U(Xe=>Xe.map(rt=>rt.path===_e?{...rt,content:Oe}:rt)),e.info(f("modules_ui.code_saved"))}catch(Xe){e.error(Xe.message)}},[L,o,e]),we=!t.isLoading&&s.length>0,Ee=x.useMemo(()=>{const _e=[{value:cc,label:f("modules_ui.code_super_agent"),icon:un,description:f("modules_ui.code_super_agent_desc")}],Oe=(q.data||[]).map(He=>({value:He.slug,label:He.slug,icon:un,description:He.description||He.role||void 0}));return[..._e,...Oe]},[q.data]),ve=x.useMemo(()=>g,[g]),Ce=x.useMemo(()=>$.data?.find(_e=>_e.id===c)?.title||"",[$.data,c]),Le=x.useMemo(()=>s.find(_e=>String(_e.id)===o),[s,o]);XL(Ce);const[Pe,Ie]=x.useState(null),se=k?null:CN(g),be=se&&se.turnKey!==Pe,$e=_e=>{ie(_e)},Re=x.useCallback(()=>y(_e=>!_e),[]),ze=x.useCallback(()=>z(_e=>!_e),[]),We=x.useCallback(()=>R(_e=>!_e),[]),at=x.useCallback(()=>S(_e=>!_e),[]),yt=x.useMemo(()=>c?r.jsx("div",{className:"flex items-center gap-0.5",children:[{Icon:eS,open:j,toggle:Re,title:f("modules_ui.code_panel_sessions")},{Icon:Wk,open:M,toggle:ze,title:f("modules_ui.code_panel_tree")},{Icon:Ya,open:E,toggle:We,title:f("modules_ui.code_panel_terminal")},{Icon:$M,open:C,toggle:at,title:f("modules_ui.code_panel_context")}].map(({Icon:_e,open:Oe,toggle:He,title:Xe})=>r.jsx(Ye,{content:Xe,children:r.jsx("button",{type:"button",onClick:He,"data-active":Oe,className:"rounded p-1 text-muted-fg transition-colors hover:bg-accent hover:text-accent-fg data-[active=true]:bg-accent data-[active=true]:text-accent-fg",children:r.jsx(_e,{className:"size-3.5"})})},Xe))}):null,[c,j,M,E,C,Re,ze,We,at]);return WL(yt),r.jsx("div",{className:"flex h-full min-h-0 flex-col","data-testid":"screen-code",children:t.isLoading?r.jsx(ot,{}):we?r.jsxs(Tx,{orientation:"vertical",id:"code-layout-v",className:"min-h-0 flex-1",children:[r.jsx(uo,{id:"top",defaultSize:E?"55%":"100%",minSize:"20%",children:r.jsxs(Tx,{orientation:"horizontal",id:"code-layout",className:"h-full",children:[j&&r.jsxs(r.Fragment,{children:[r.jsx(uo,{id:"left",defaultSize:"14%",minSize:"8%",children:r.jsxs("aside",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"shrink-0 border-b border-border p-2",children:r.jsx(WB,{projects:s,value:o,onChange:G,disabled:k})}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(ZB,{sessions:$.data||[],activeId:c,busy:k,onSelect:Z,onCreate:ee,onRename:de,onDelete:fe})}),r.jsx("div",{className:"shrink-0 border-t border-border p-2",children:r.jsx(bt,{value:p,onChange:ae,options:Ee,disabled:k,showIcon:!0})})]})}),r.jsx(Bh,{})]}),M&&r.jsxs(r.Fragment,{children:[r.jsx(uo,{id:"tree",defaultSize:"13%",minSize:"8%",children:r.jsx("div",{className:"h-full",children:r.jsx(gU,{pid:o,projectPath:Le?.path,onOpenFile:Se})})}),r.jsx(Bh,{})]}),r.jsx(uo,{id:"main",defaultSize:"50%",minSize:"20%",children:r.jsxs("div",{className:"flex h-full flex-col",children:[L.length>0&&r.jsxs("div",{className:"flex shrink-0 items-center gap-0 overflow-x-auto border-b border-border",children:[r.jsxs("button",{type:"button",onClick:()=>I("chat"),"data-active":D==="chat",className:"flex shrink-0 items-center gap-1.5 border-r border-border px-3 py-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/40 data-[active=true]:text-foreground",children:[r.jsx(Vx,{className:"size-3 shrink-0"}),f("modules_ui.code_chat_tab")]}),L.map(_e=>{const Oe=_e.path.split("/").pop()??_e.path,He=D===_e.path;return r.jsxs("div",{"data-active":He,className:"group flex shrink-0 items-center gap-1 border-r border-border px-2 py-2 text-[11px] text-muted-foreground transition-colors hover:bg-accent/40 data-[active=true]:text-foreground",children:[r.jsx(Ye,{content:_e.path,children:r.jsx("button",{type:"button",onClick:()=>I(_e.path),className:"min-w-0 max-w-[140px] truncate font-mono",children:Oe})}),r.jsx(Ye,{content:f("code_module.close"),children:r.jsx("button",{type:"button",onClick:()=>je(_e.path),className:"shrink-0 rounded p-0.5 opacity-60 hover:bg-accent hover:opacity-100",children:r.jsx(Ys,{className:"size-2.5"})})})]},_e.path)})]}),D==="chat"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto","data-testid":"code-transcript",children:c?g.length?r.jsx(h_,{msgs:g,onCopy:pe}):r.jsx("div",{className:"grid h-full place-items-center p-6",children:r.jsx(xt,{children:f("code_module.empty_chat")})}):r.jsx("div",{className:"grid h-full place-items-center p-6",children:r.jsx(xt,{children:f("code_module.pick_project")})})}),be&&se&&r.jsx(SN,{turnKey:se.turnKey,questions:se.questions,onSubmit:$e,onDismiss:()=>Ie(se.turnKey),disabled:k})]}):r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:(()=>{const _e=L.find(Oe=>Oe.path===D);return _e?r.jsx(hU,{path:_e.path,content:_e.content,loading:_e.loading,onSave:_e.artifactName?Oe=>Ve(_e.path,Oe):void 0}):null})()}),r.jsx("div",{className:"shrink-0 border-t border-border p-2","data-testid":"code-input",children:r.jsx(eU,{value:b,onValueChange:v,onSubmit:()=>void ie(),onStop:me,busy:k,disabled:!c,mode:X,onModeChange:_e=>void oe({mode:_e}),model:P,onModelChange:_e=>void oe({model:_e||null})})})]})}),C&&r.jsxs(r.Fragment,{children:[r.jsx(Bh,{}),r.jsx(uo,{id:"right",defaultSize:"22%",minSize:"15%",children:r.jsx("aside",{className:"flex h-full flex-col",children:r.jsx(pU,{pid:o,turns:ve,changes:K.data,changesLoading:K.isLoading,onRefreshChanges:()=>void K.mutate(),session:Y.data?{title:Y.data.title,mode:Y.data.mode,createdAt:Y.data.createdAt,updatedAt:Y.data.updatedAt,agentSlug:Y.data.agentSlug??null}:null,onRunInTerminal:V,onEditArtifact:Be})})})]})]})}),E&&o&&r.jsxs(r.Fragment,{children:[r.jsx(bU,{}),r.jsx(uo,{id:"terminal",defaultSize:"45%",minSize:"10%",maxSize:"80%",children:r.jsx(xU,{pid:o,initCmd:A,onClose:We,className:"h-full"})})]})]}):r.jsx("div",{className:"grid flex-1 place-items-center",children:r.jsx(xt,{children:f("code_module.no_projects")})})})}function vU({open:e,onClose:t}){const{mutate:s}=vC(),o=Wn(),l=lt(),[c,u]=x.useState(""),[p,m]=x.useState(!1),[g,h]=x.useState(""),[b,v]=x.useState([]),[k,N]=x.useState(null),[j,y]=x.useState(""),[C,S]=x.useState(!1),[E,R]=x.useState(!1),A=async(z,B=!1)=>{S(!0),y("");try{const L=await Ij.dirs(z||"~");h(L.path),u(L.path),N(L.parent),v(L.entries)}catch(L){const U=L.message;y(U),B||l.error(U)}finally{S(!1)}};x.useEffect(()=>{e||(u(""),m(!1),h(""),v([]),N(null),y(""))},[e]);const T=async()=>{S(!0);try{const z=await Ij.pickDir(f("add_project.picker_prompt"));if("cancelled"in z)return;u(z.path);return}catch{m(!0),await A(c||"~")}finally{S(!1)}},M=async()=>{const z=c.trim();if(!z){l.error(f("add_project.path_required"));return}R(!0);try{const B=await ls.register(z);l.success(f("add_project.registered",{id:B.id})),await s("/projects"),t(),o(`/p/${B.id}`)}catch(B){l.error(B.message)}finally{R(!1)}};return r.jsx(On,{open:e,onClose:t,title:f("add_project.title"),description:f("add_project.subtitle"),footer:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",onClick:t,disabled:E,children:f("common.cancel")}),r.jsx(ce,{variant:"primary",onClick:M,loading:E,children:f("add_project.register")})]}),children:r.jsxs("div",{className:"space-y-3",children:[r.jsx(le,{label:f("add_project.path_label"),hint:f("add_project.path_hint"),children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Ne,{autoFocus:!0,placeholder:f("add_project.path_placeholder"),value:c,onChange:z=>u(z.target.value),onKeyDown:z=>{z.key==="Enter"&&M()}}),r.jsxs(ce,{onClick:T,disabled:C,children:[r.jsx(_c,{size:14})," ",f("add_project.search_btn")]})]})}),p&&r.jsxs("div",{className:"rounded-md border border-border bg-muted/20",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[r.jsx("span",{className:"truncate font-mono text-xs text-muted-fg",children:g||c||"~"}),r.jsxs("div",{className:"flex gap-1",children:[r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>A("~"),disabled:C,children:r.jsx(DM,{size:13})}),r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>k&&A(k),disabled:!k||C,children:".."}),r.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>m(!1),disabled:C,children:r.jsx(Ys,{size:13})})]})]}),r.jsxs("div",{className:"max-h-64 overflow-y-auto p-2",children:[C&&r.jsx(ot,{}),!C&&j&&r.jsx(xt,{children:f("add_project.browser_unavailable")}),!C&&!j&&b.length===0&&r.jsx(xt,{children:f("add_project.no_folders")}),!C&&!j&&b.map(z=>r.jsxs("button",{type:"button",onClick:()=>A(z),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent",children:[r.jsx(Rf,{size:14,className:"text-muted-fg"}),r.jsx("span",{className:"truncate",children:z.split("/").pop()}),r.jsx("span",{className:"ml-auto truncate font-mono text-[10px] text-muted-fg",children:z})]},z))]})]})]})})}function yU({onPaired:e}){const[t,s]=x.useState(""),[o,l]=x.useState(jU()),[c,u]=x.useState(!1),[p,m]=x.useState(null);async function g(){const h=t.trim();if(!h){m(f("pairing.err_required"));return}u(!0),m(null);try{const b=await Fl.confirm({pairing_id:h,label:o.trim()||void 0});fo(b.token);try{localStorage.setItem(Tn.token,b.token)}catch{}e()}catch(b){m(wU(b)),u(!1)}}return r.jsx("div",{className:"flex min-h-[100dvh] w-full items-center justify-center overflow-y-auto bg-background p-4 text-foreground",children:r.jsxs("div",{className:"my-auto w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-sm",children:[r.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[r.jsx("div",{className:"grid size-10 place-items-center rounded-lg bg-primary/10 text-primary",children:r.jsx(qh,{size:20})}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-base font-semibold",children:f("pairing.title")}),r.jsx("p",{className:"text-xs text-muted-fg",children:f("pairing.subtitle")})]})]}),r.jsxs("ol",{className:"mb-5 space-y-1.5 rounded-lg bg-muted/50 p-3 text-xs text-muted-fg",children:[r.jsx("li",{className:"font-medium text-foreground",children:f("pairing.steps_title")}),r.jsxs("li",{children:["1. ",f("pairing.step_1")]}),r.jsxs("li",{children:["2. ",f("pairing.step_2")]}),r.jsxs("li",{children:["3. ",f("pairing.step_3")]})]}),r.jsxs("form",{className:"space-y-3",onSubmit:h=>{h.preventDefault(),g()},children:[r.jsx(le,{label:f("pairing.code_label"),children:r.jsx(Ne,{value:t,onChange:h=>s(h.target.value),placeholder:f("pairing.code_ph"),spellCheck:!1,autoComplete:"off"})}),r.jsx(le,{label:f("pairing.label_label"),hint:f("pairing.revoke_hint"),children:r.jsx(Ne,{value:o,onChange:h=>l(h.target.value),placeholder:f("pairing.label_ph")})}),p&&r.jsx("p",{className:"rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:p}),r.jsx(ce,{type:"submit",variant:"primary",size:"md",loading:c,className:"w-full justify-center",children:f(c?"pairing.linking":"pairing.submit")})]})]})})}function jU(){const e=navigator.userAgent;return/iPhone|iPad/.test(e)?"iPhone":/Android/.test(e)?"Android":/Mac/.test(e)?"Mac":/Windows/.test(e)?"Windows PC":/Linux/.test(e)?"Linux":"browser"}function wU(e){if(e instanceof Kc){if(e.status===410)return f("pairing.err_expired");if(e.status===404||e.status===409)return f("pairing.err_unknown")}return f("pairing.err_generic")}function kU({...e}){return r.jsx(zC,{"data-slot":"sheet",...e})}function SU({...e}){return r.jsx(OC,{"data-slot":"sheet-portal",...e})}function CU({className:e,...t}){return r.jsx(RC,{"data-slot":"sheet-overlay",className:St("fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",e),...t})}function NU({className:e,children:t,side:s="right",showCloseButton:o=!0,...l}){return r.jsxs(SU,{children:[r.jsx(CU,{}),r.jsxs(MC,{"data-slot":"sheet-content","data-side":s,className:St("fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",e),...l,children:[t,o&&r.jsxs(cp,{"data-slot":"sheet-close",render:r.jsx(Wa,{variant:"ghost",className:"absolute top-3 right-3",size:"icon-sm"}),children:[r.jsx(Ys,{}),r.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function EU({className:e,...t}){return r.jsx("div",{"data-slot":"sheet-header",className:St("flex flex-col gap-0.5 p-4",e),...t})}function RU({className:e,...t}){return r.jsx(DC,{"data-slot":"sheet-title",className:St("font-heading text-base font-medium text-foreground",e),...t})}function TU({className:e,...t}){return r.jsx(TC,{"data-slot":"sheet-description",className:St("text-sm text-muted-foreground",e),...t})}function AU({value:e,projectPath:t,onPick:s}){const o=MU(e),l=o?OU(e):"",{data:c}=et(o?["/skills",t||""]:null,()=>fc.list(t)),u=c?.skills||[],p=x.useMemo(()=>{const m=l.toLowerCase();return m?u.filter(g=>g.slug.toLowerCase().includes(m)).slice(0,8):u.slice(0,8)},[u,l]);return!o||p.length===0?null:r.jsxs("div",{className:"rounded-xl border border-border bg-popover/95 text-sm shadow-md backdrop-blur",children:[r.jsx("ul",{role:"listbox",className:"max-h-64 overflow-y-auto py-1",children:p.map(m=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>s(m.slug),className:"flex w-full items-start gap-2 px-3 py-1.5 text-left hover:bg-accent hover:text-accent-foreground",children:[r.jsxs("code",{className:"rounded bg-muted px-1.5 py-0.5 text-[11px]",children:["/",m.slug]}),r.jsx("span",{className:"truncate text-xs text-muted-foreground",children:m.description})]})},m.slug))}),r.jsx("div",{className:"border-t border-border px-3 py-1.5 text-[10px] text-muted-foreground",children:"Type a name to filter · click to insert · the skill body will be loaded for this turn."})]})}function MU(e){return!!e.match(/^\s*\/([A-Za-z0-9_-]*)$/)}function OU(e){const t=e.match(/^\s*\/([A-Za-z0-9_-]*)$/);return t?t[1]:""}function zU(){try{const e=localStorage.getItem(Tn.robyChat);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>s&&Array.isArray(s.parts)&&!s.pending):[]}catch{return[]}}function DU({open:e,onOpenChange:t}){const s=op(),o=lt(),[l,c]=x.useState(zU),[u,p]=x.useState(""),[m,g]=x.useState(!1),[h,b]=x.useState(""),v=x.useRef(null);x.useEffect(()=>{const S=l.filter(E=>!E.pending);try{S.length?localStorage.setItem(Tn.robyChat,JSON.stringify(S)):localStorage.removeItem(Tn.robyChat)}catch{}},[l]);const k=()=>{if(!m){c([]),p("");try{localStorage.removeItem(Tn.robyChat)}catch{}}};x.useEffect(()=>()=>v.current?.abort(),[]),x.useEffect(()=>{const S=E=>{const R=E.detail?.prompt;typeof R=="string"&&(t(!0),p(R))};return window.addEventListener("apx:roby-prompt",S),()=>window.removeEventListener("apx:roby-prompt",S)},[t]);const N=()=>{v.current?.abort(),g(!1)},j=S=>c(E=>{const R=[...E],A=R[R.length-1];return A?.role==="assistant"&&(R[R.length-1]=S(A)),R}),y=async()=>{const S=u.trim();if(!S||m)return;const E=new Date().toISOString(),R=l.filter(z=>!z.pending).map(z=>({role:z.role,content:jx(z)}));c(z=>[...z,{role:"user",parts:[{kind:"text",text:S}],ts:E},{role:"assistant",parts:[],ts:E,pending:!0}]),p(""),g(!0);const A=new AbortController;v.current=A;let T=!1;const M=z=>{if(z?.type==="error"){T=!0,o.error(z.error||"error"),c(B=>{const L=[...B],U=L[L.length-1];return U?.role==="assistant"&&U.pending&&L.pop(),L});return}j(B=>g_(B,z))};try{await jC.stream(0,{prompt:S,previousMessages:R,model:h||void 0,channel:"web_sidebar"},M,A.signal),j(z=>({...z,pending:!1}))}catch(z){A.signal.aborted?j(B=>({...B,pending:!1,parts:[...B.parts,{kind:"text",text:f("project.chat.stopped_marker")}]})):T||(o.error(z.message),c(B=>{const L=[...B],U=L[L.length-1];return U?.role==="assistant"&&U.pending&&L.pop(),L}))}finally{v.current===A&&(v.current=null),g(!1)}},C=async S=>{try{await navigator.clipboard.writeText(S),o.info(f("project.chat.copied"))}catch{}};return r.jsx(kU,{open:e,onOpenChange:t,children:r.jsxs(NU,{side:"right",className:"flex w-full flex-col gap-0 p-0 sm:max-w-xl data-[side=right]:sm:max-w-xl",children:[r.jsxs(EU,{className:"pr-12",children:[r.jsxs(RU,{className:"flex items-center gap-2",children:[r.jsx(un,{size:18})," ",f("superagent.title",{persona:s}),r.jsx("span",{className:"text-xs font-normal text-muted-fg",children:f("superagent.badge")})]}),r.jsx(TU,{children:f("superagent.desc")})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:l.length===0?r.jsx("p",{className:"mt-6 text-center text-sm text-muted-fg",children:f("superagent.empty",{persona:s})}):r.jsx(h_,{msgs:l,onCopy:C})}),r.jsx(kN,{msgs:l}),r.jsxs("div",{className:"border-t border-border p-3",children:[r.jsx("div",{className:"mb-1.5",children:r.jsx(AU,{value:u,onPick:S=>p(`/${S} `)})}),r.jsx(p_,{value:u,onValueChange:p,onSubmit:()=>void y(),onStop:N,busy:m,placeholder:f("superagent.placeholder"),footer:r.jsx(m_,{value:h,onChange:b,disabled:m})}),r.jsx("div",{className:"mt-1.5 flex justify-end",children:r.jsxs(Wa,{size:"xs",variant:"ghost",onClick:k,disabled:m||l.length===0,children:[r.jsx(tn,{className:"size-3"})," ",f("superagent.new_chat")]})})]})]})})}function LU(){const e=navigator.userAgent;return/iPhone|iPad/.test(e)?"iPhone":/Android/.test(e)?"Android":/Mac/.test(e)?"Mac":/Windows/.test(e)?"Windows PC":/Linux/.test(e)?"Linux":"browser"}function PU(){const[e,t]=x.useState({status:"loading"}),[s,o]=x.useState(0),l=x.useCallback(()=>{t({status:"loading"}),o(c=>c+1)},[]);return x.useEffect(()=>{let c=!1;return(async()=>{try{const h=await fetch("/health");if(!h.ok)throw new Error(`HTTP ${h.status}`)}catch(h){c||t({status:"error",reason:String(h)});return}const u=window.location.hash.replace(/^#/,""),p=new URLSearchParams(u),m=p.get("pair");if(m){history.replaceState(null,"",window.location.pathname+window.location.search);try{const h=await Fl.confirm({pairing_id:m,label:LU(),kind:"web"});fo(h.token);try{localStorage.setItem(Tn.token,h.token)}catch{}c||t({status:"ok"});return}catch{}}const g=p.get("token");if(g){fo(g);try{localStorage.setItem(Tn.token,g)}catch{}history.replaceState(null,"",window.location.pathname+window.location.search)}else try{const h=localStorage.getItem(Tn.token);h&&fo(h)}catch{}try{const h=await fetch("/admin/web-token");if(h.ok){const b=await h.json();if(b?.token){fo(b.token);try{localStorage.setItem(Tn.token,b.token)}catch{}}}}catch{}if(!Yb()){c||t({status:"unpaired"});return}try{await ge.get("/projects"),c||t({status:"ok"})}catch(h){if(h instanceof Kc&&(h.status===401||h.status===403)){fo(null);try{localStorage.removeItem(Tn.token)}catch{}c||t({status:"unpaired"})}else c||t({status:"error",reason:String(h)})}})(),()=>{c=!0}},[s]),{...e,reload:l}}function IU(){const e=PU();return e.status==="loading"?r.jsx(hk,{text:f("daemon.connecting")}):e.status==="error"?r.jsx(hk,{mood:"sad",text:f("daemon.unreachable"),sub:`${f("daemon.unreachable_hint")}
649
649
 
650
650
  ${e.reason}`}):e.status==="unpaired"?r.jsx(yU,{onPaired:e.reload}):r.jsx(UL,{children:r.jsx(J4,{delay:0,children:r.jsx(BU,{})})})}function BU(){const e=Wn(),t=Qn(),[s,o]=Nf(),{theme:l,toggle:c}=Kx(),u=s.get("action")==="add-project",[p,m]=x.useState(!1),g=()=>{const b=new URLSearchParams(s);b.delete("action"),o(b,{replace:!0})},h=()=>{const b=new URLSearchParams(s);b.set("action","add-project"),o(b)};return r.jsx(FL,{children:r.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-background text-foreground","data-testid":"app-shell",children:[r.jsx(ZD,{onSelect:b=>e(b),onOpenRoby:()=>m(!0),onOpenAddProject:h}),r.jsxs("main",{className:"m-2 ml-0 flex min-w-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-card shadow-sm",children:[r.jsx(UU,{onToggleTheme:c,isDark:l==="dark",pathname:t.pathname}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsxs(Pk,{children:[r.jsx(Qt,{path:"/",element:r.jsx($L,{})}),r.jsx(Qt,{path:"/settings/*",element:r.jsx(uB,{})}),r.jsx(Qt,{path:"/m/desktop/*",element:r.jsx(pB,{})}),r.jsx(Qt,{path:"/m/code/*",element:r.jsx(_U,{})}),r.jsx(Qt,{path:"/p/:pid/*",element:r.jsx(O8,{})}),r.jsx(Qt,{path:"*",element:r.jsx(FU,{})})]})})]}),r.jsx(vU,{open:u,onClose:g}),r.jsx(DU,{open:p,onOpenChange:m})]})})}function UU({onToggleTheme:e,isDark:t,pathname:s}){const{projects:o}=Xc(),l=KL(),c=s.split("/").filter(Boolean),u=c[0]==="p"?o.find(N=>String(N.id)===c[1]):void 0,p=c[0]==="settings"?qU(c[1]):c[0]==="p"?$U(c[2]):"",m=c[0]==="p"&&c[1]==="0",g=u?.name||u?.path?.split("/").pop()||f("nav.project"),h=s==="/"?f("topbar.breadcrumb_root"):c[0]==="settings"?[f("topbar.breadcrumb_root"),f("nav.settings"),p].filter(Boolean).join(" › "):c[0]==="m"?[f("topbar.breadcrumb_root"),VU(c[1]),l].filter(Boolean).join(" › "):c[0]==="p"?m?[f("topbar.breadcrumb_root"),f("topbar.breadcrumb_base"),p].filter(Boolean).join(" › "):[f("topbar.breadcrumb_root"),f("topbar.breadcrumb_projects"),g,p].filter(Boolean).join(" › "):f("topbar.breadcrumb_root"),b=s==="/"?"":c[0]==="settings"?f("settings.subtitle"):c[0]==="p"?m?f("base.subtitle"):u?`${kC(u.kind)} · ${u.path}`:"":"",v=GL(),k=QL();return r.jsxs("header",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/50 px-3",children:[v&&r.jsx(uD,{collapsed:v.collapsed,onToggle:v.toggle}),r.jsxs("span",{className:"min-w-0 flex-1 truncate text-[11px] tracking-wide text-muted-fg",children:[h,b&&r.jsxs("span",{className:"text-muted-fg/50",children:[" · ",b]})]}),k,r.jsx(HU,{}),r.jsx(Ye,{content:f(t?"topbar.light":"topbar.dark"),children:r.jsx("button",{type:"button","data-testid":"theme-toggle",onClick:e,className:"shrink-0 rounded-md p-1.5 text-muted-fg hover:bg-accent hover:text-accent-fg",children:t?r.jsx(QM,{size:14}):r.jsx(VM,{size:14})})})]})}function HU(){const e=qb(),t=s=>{s!==e&&(cC(s),window.location.reload())};return r.jsxs(oC,{children:[r.jsxs(lC,{"data-testid":"lang-menu",title:f("topbar.lang_toggle"),className:"flex shrink-0 items-center gap-1 rounded-md p-1.5 text-muted-fg hover:bg-accent hover:text-accent-fg",children:[r.jsx(PM,{size:14}),r.jsx("span",{className:"text-[11px] font-medium uppercase",children:e})]}),r.jsx(iC,{align:"end",children:r.jsx(nD,{value:e,onValueChange:s=>t(s),children:uC.map(s=>r.jsx(sD,{value:s.value,children:s.label},s.value))})})]})}function VU(e){switch(e){case"desktop":return f("nav.modules.desktop");case"code":return f("nav.modules.code");default:return e||""}}function qU(e){switch(e){case"super-agent":return f("settings.tabs.super_agent");case"engines":return f("settings.tabs.engines");case"telegram":return f("settings.tabs.telegram");case"devices":return f("settings.tabs.devices");case"voice":return f("nav.modules.voice");case"deck":return f("nav.modules.deck");case"desktop":return f("nav.modules.desktop");case"appearance":return f("settings.appearance");case"config":case"advanced":return f("settings.tabs.advanced");case"identity":default:return e||""}}function $U(e){switch(e){case"chat":return f("project.nav.chat");case"telegram":return f("project.nav.telegram");case"agents":return f("project.nav.agents");case"routines":return f("project.nav.routines");case"tasks":return f("project.nav.tasks");case"mcps":return f("project.nav.mcps");case"config":return f("project.nav.config");case"workspaces":return f("base.workspaces_title");case"models":return f("settings.tabs.engines");case"agent-defaults":return f("base.defaults_title");case"sessions":return f("base.sessions_title");case"logs":return f("project.nav.logs");case"memories":return f("project.nav.memories");default:return""}}function hk({text:e,sub:t,mood:s="happy"}){return r.jsx("div",{className:"grid h-screen w-screen place-items-center bg-background text-foreground",children:r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsx(KC,{mood:s,className:"mb-4 text-xs"}),r.jsx("div",{className:"text-foreground",children:e}),t&&r.jsx("pre",{className:"mt-2 max-w-xl whitespace-pre-wrap text-sm text-muted-fg",children:t})]})})}function FU(){const e=Wn();return r.jsx(XC,{testId:"screen-not-found",mood:"confused",title:f("not_found.title"),titleClassName:"text-7xl",message:f("not_found.message"),action:r.jsx(Wa,{variant:"outline",onClick:()=>e("/"),children:f("not_found.home")})})}jT.createRoot(document.getElementById("root")).render(r.jsx(Uc.StrictMode,{children:r.jsx(GA,{children:r.jsx(s3,{children:r.jsx(IU,{})})})}));
651
- //# sourceMappingURL=index-Cy355-jV.js.map
651
+ //# sourceMappingURL=index-DJpij6dQ.js.map