From 8cc6ac0f1890c0c1021efcd6b34452c5ad8584cb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 18:14:46 +0000 Subject: [PATCH 01/16] fix(studio,tasks): make template agents chat, thread and run as tasks out of the box A freshly scaffolded project (`agentomatic new` + `init --template basic|full`) could not chat from Studio: - No store is configured by default, so every thread route answered `400 Thread storage not configured`. Studio's "New Chat" creates a thread before the first message, so no conversation could ever start. The platform now falls back to a bounded in-memory store (1000 threads, LRU-evicted) when no store / MEMORY connection / database URL is configured (`AGENTOMATIC_EPHEMERAL_THREADS=0` disables it). A configured-but-broken database still refuses the fallback. - Studio runs never loaded thread history nor saved the turn, so a chatbot answered every Studio message as if it were the first and reopened threads were empty. Studio runs now use the same memory handling as `/chat`. - The basic/full templates sent the model one string and ignored `state.messages`; they now send a real system message plus the turns. - Sync graph nodes (every template's blocking `llm.invoke`) ran inline on the event loop, so an async task submission only returned once the model had answered and polling/SSE/health checks stalled meanwhile. Sync nodes now run in a worker thread; `report_stage_sync` forwards progress back to the loop. - The per-request prompt override was an instance attribute, so concurrent runs (and concurrently scored optimizer candidates) could read or clear each other's prompt. It is now context-local. - `build_invoke_state` no longer mutates the caller's payload (a task's stored `input.metadata` was rewritten by the run). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- CLAUDE.md | 1 + docs/guide/configuration.md | 1 + docs/guide/platform-features.md | 11 +- src/agentomatic/agents/base.py | 32 ++- src/agentomatic/agents/graph.py | 44 +++- src/agentomatic/async_utils.py | 49 +++- src/agentomatic/cli/agent_guide.py | 1 + src/agentomatic/cli/project.py | 1 + src/agentomatic/cli/templates.py | 21 +- src/agentomatic/core/agent_invoke.py | 10 +- src/agentomatic/core/platform.py | 75 ++++-- src/agentomatic/storage/memory.py | 24 +- src/agentomatic/studio/router.py | 127 ++++++++- src/agentomatic/tasks/progress.py | 24 +- tests/test_no_unhandled_500s.py | 48 +++- tests/test_sync_node_offload.py | 188 ++++++++++++++ tests/test_template_chat_threads_tasks.py | 301 ++++++++++++++++++++++ 17 files changed, 895 insertions(+), 63 deletions(-) create mode 100644 tests/test_sync_node_offload.py create mode 100644 tests/test_template_chat_threads_tasks.py diff --git a/CLAUDE.md b/CLAUDE.md index a5571843..a5c83695 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -145,6 +145,7 @@ into the image/compose that drive the same `main.py`. | `AGENTOMATIC_ENABLE_CONTROL_PLANE` / `AGENTOMATIC_CONTROL_TOKEN` | Control plane | | `AGENTOMATIC_ENABLE_RATE_LIMIT` | Rate limiting | | `AGENTOMATIC_LOGS_HISTORY` | Persist per-agent invoke/chat/stream history (default off) | +| `AGENTOMATIC_EPHEMERAL_THREADS` | With no store/DB configured, keep chat threads in a bounded in-memory store (default on; `0` disables — thread routes then answer 400) | | `AGENTOMATIC_ALLOW_LOGSLLM_ANALYSIS` | Enable LLM analysis over those logs (default off) | | `AGENTOMATIC_INGESTION_ROOT` | Confine ingestion source/output paths to this dir (default: cwd) | | `AGENTOMATIC_TASK_EVENT_LOG` | Task-event replay backend: `memory` (default), `none` to disable, or a registered provider | diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 082d8351..47fbc808 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -189,6 +189,7 @@ directory, host, port, and stack values passed to `agentomatic run`. | `AGENTOMATIC_ENABLE_CONTROL_PLANE` / `AGENTOMATIC_CONTROL_TOKEN` | control plane | `true` / empty in generated `main.py`; `false` in CLI fallback | Mount control-plane routes and protect mutations | | `AGENTOMATIC_ENABLE_RATE_LIMIT` / `AGENTOMATIC_RATE_LIMIT_TRUST_PROXY_HEADERS` | rate limiting | `false` / `false` | Enable the limiter; trust forwarded client IPs only behind a trusted proxy | | `AGENTOMATIC_LOGS_HISTORY` / `DATABASE_URL` | invocation history / storage | `false` / empty | Persist logs and threads using an async SQLAlchemy URL | +| `AGENTOMATIC_EPHEMERAL_THREADS` | thread-store fallback | `true` | With no `store=`, MEMORY connection or database URL, keep conversation threads in a bounded in-memory store (1000 threads, lost on restart) so Studio chat and `/chat` history work out of the box. `0` disables it — thread routes then answer `400 Thread storage not configured` | | `AGENTOMATIC_ARTIFACT_ROOT` | `artifact_root` | `.local/artifacts` | Versioned plugin/model artifact bundles | | `AGENTOMATIC_PLUGIN_AUTORELOAD` | `plugin_autoreload` | `false` | Watch the promoted artifact version and reload plugins safely | | `AGENTOMATIC_PLUGIN_AUTORELOAD_INTERVAL` | `plugin_autoreload_interval` | `5` | Seconds between artifact-pointer checks | diff --git a/docs/guide/platform-features.md b/docs/guide/platform-features.md index ea961d10..57d624a2 100644 --- a/docs/guide/platform-features.md +++ b/docs/guide/platform-features.md @@ -487,13 +487,22 @@ By default the chain advances only on configured triggers (`timeout`, ## 🧠 12. Conversation Memory & Session Management -Agentomatic provides **automatic conversation memory** for all deployed agents. When a thread store is configured, every `/chat` and `/invoke` call automatically: +Agentomatic provides **automatic conversation memory** for all deployed agents. When a thread store is configured, every `/chat`, `/invoke` and Studio chat run automatically: 1. **Loads prior conversation history** into the agent's `messages` state 2. **Invokes the agent** with that state 3. **Persists** both user and assistant messages to the store 4. **Summarises** older messages when the conversation grows long +!!! note "No store configured? Threads still work" + A freshly scaffolded project configures no database. Instead of failing + every thread route with `400 Thread storage not configured` (which made + Studio's *New Chat* unusable), the platform falls back to a bounded + in-memory store — capped at 1000 threads, oldest evicted first, lost on + restart — and logs a warning. Configure `store=SQLAlchemyStore(...)`, a + `MEMORY` connection, or `DATABASE_URL` / `AGENTOMATIC_DB_URL` for durable + history; set `AGENTOMATIC_EPHEMERAL_THREADS=0` to disable the fallback. + !!! warning "Your agent has to *read* `messages` — loading it is not enough" The platform fills `state["messages"]` and reports `history_loaded`. Whether the model ever sees those turns is the agent's decision. An diff --git a/src/agentomatic/agents/base.py b/src/agentomatic/agents/base.py index da2a515c..d1be953c 100644 --- a/src/agentomatic/agents/base.py +++ b/src/agentomatic/agents/base.py @@ -55,6 +55,7 @@ def state_to_output(self, state): import time from abc import ABC, abstractmethod from collections.abc import Sequence +from contextvars import ContextVar from pathlib import Path from typing import Any, Generic @@ -75,6 +76,14 @@ def state_to_output(self, state): TraceEvent, ) +# Per-request system-prompt overrides, keyed by agent ``id()``. A ContextVar +# rather than an instance attribute: concurrent requests (and the optimizer +# scoring several candidate prompts at once) share one agent instance, and an +# attribute let one run read — or clear — another run's prompt mid-flight. +_REQUEST_PROMPTS: ContextVar[dict[int, str]] = ContextVar( + "agentomatic_request_prompts", default={} +) + class BaseGraphAgent(ABC, Generic[StateT]): """Abstract base class for class-owned graph agents. @@ -126,10 +135,6 @@ def __init__(self) -> None: self.stop_training: bool = False self._fit_optimize_options: dict[str, Any] | None = None - # Per-request system prompt override (set during transform / atransform / - # streaming so node methods can call ``resolve_system_prompt()``). - self._request_system_prompt: str | None = None - # Evaluation self.evaluation_history: list[EvaluationReport] = [] @@ -140,6 +145,25 @@ def __init__(self) -> None: # Prompt resolution (optimize / fit / stacks) # ================================================================== + @property + def _request_system_prompt(self) -> str | None: + """Per-request prompt override of the run in the current context. + + Set during ``transform`` / ``atransform`` / streaming so node methods + can call :meth:`resolve_system_prompt`. Context-local, so concurrent + runs on one instance never see each other's override. + """ + return _REQUEST_PROMPTS.get().get(id(self)) + + @_request_system_prompt.setter + def _request_system_prompt(self, value: str | None) -> None: + prompts = dict(_REQUEST_PROMPTS.get()) + if value is None: + prompts.pop(id(self), None) + else: + prompts[id(self)] = value + _REQUEST_PROMPTS.set(prompts) + @staticmethod def _extract_prompt_override(input_data: dict[str, Any] | None) -> str | None: """Pull ``system_prompt_override`` from request payload layers.""" diff --git a/src/agentomatic/agents/graph.py b/src/agentomatic/agents/graph.py index 8b82ad45..de8a7554 100644 --- a/src/agentomatic/agents/graph.py +++ b/src/agentomatic/agents/graph.py @@ -41,6 +41,31 @@ def _run_coro_sync(coro: Any) -> Any: return run_sync(coro) +async def _acall_node(node: GraphNode[Any], state: Any) -> Any: + """Run one node from an async execution path. + + Async handlers are awaited on the loop. Sync handlers run in a worker + thread: template nodes make blocking LLM calls (``llm.invoke``), and + running those inline froze the whole server — task submission, polling, + SSE progress and health checks — until the model answered. + + Args: + node: Node to execute. + state: Current graph state. + + Returns: + The handler's return value (``None`` means "state mutated in place"). + """ + if inspect.iscoroutinefunction(node.handler): + return await node.handler(state) + from agentomatic.async_utils import run_in_worker_thread + + result = await run_in_worker_thread(node, state) + if inspect.iscoroutine(result): + result = await result + return result + + # --------------------------------------------------------------------------- # Graph Node # --------------------------------------------------------------------------- @@ -241,8 +266,8 @@ def invoke(self, state: StateT) -> StateT: async def ainvoke(self, state: StateT) -> StateT: """Execute the graph asynchronously. - Async node handlers are awaited; sync handlers are - called directly. + Async node handlers are awaited; sync handlers run in a worker + thread so blocking calls (LLM, HTTP) do not stall the event loop. Args: state: Initial state. @@ -263,10 +288,7 @@ async def ainvoke(self, state: StateT) -> StateT: try: logger.debug(f"🔄 Executing node: {current_node_name}") - if inspect.iscoroutinefunction(node.handler): - result = await node.handler(state) - else: - result = node(state) + result = await _acall_node(node, state) if result is not None: state = result trace.finish(status="success") @@ -336,10 +358,7 @@ def _state_to_dict(s: Any) -> dict[str, Any]: try: logger.debug(f"🔄 Executing node: {current_node_name}") - if inspect.iscoroutinefunction(node.handler): - result = await node.handler(state) - else: - result = node(state) + result = await _acall_node(node, state) if result is not None: state = result trace.finish(status="success") @@ -436,10 +455,7 @@ def _state_to_dict(s: Any) -> dict[str, Any]: } try: - if inspect.iscoroutinefunction(node.handler): - result = await node.handler(state) - else: - result = node(state) + result = await _acall_node(node, state) if result is not None: state = result trace.finish(status="success") diff --git a/src/agentomatic/async_utils.py b/src/agentomatic/async_utils.py index 2954c434..edc23af0 100644 --- a/src/agentomatic/async_utils.py +++ b/src/agentomatic/async_utils.py @@ -15,13 +15,21 @@ import asyncio import concurrent.futures import threading -from collections.abc import Coroutine +from collections.abc import Callable, Coroutine +from contextvars import ContextVar from typing import Any, TypeVar T = TypeVar("T") _local = threading.local() +# Event loop that handed the current worker-thread call off via +# :func:`run_in_worker_thread`. Lets sync code running in that thread (a graph +# node, say) schedule work back onto the loop that is serving the request. +_owner_loop: ContextVar[asyncio.AbstractEventLoop | None] = ContextVar( + "agentomatic_owner_loop", default=None +) + def _thread_loop() -> asyncio.AbstractEventLoop: """Return (or create) the persistent event loop for the current thread.""" @@ -57,3 +65,42 @@ def _runner(c: Coroutine[Any, Any, T]) -> T: with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: return pool.submit(_runner, coro).result() + + +async def run_in_worker_thread(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T: + """Run a blocking callable in a worker thread without stalling the loop. + + Sync graph nodes routinely make blocking LLM / HTTP calls. Running them + inline on the event loop froze every other request for the duration — + an "async" task submission only returned once the model had answered, + and task polling, SSE progress and health checks all stalled with it. + + The call runs under a copy of the caller's context (``asyncio.to_thread`` + semantics), so ContextVars such as the task-progress context stay + visible, and :func:`owner_loop` reports the loop that offloaded it. + + Args: + fn: Blocking callable. + *args: Positional arguments for ``fn``. + **kwargs: Keyword arguments for ``fn``. + + Returns: + Whatever ``fn`` returns. + """ + loop = asyncio.get_running_loop() + + def _call() -> T: + _owner_loop.set(loop) + return fn(*args, **kwargs) + + return await asyncio.to_thread(_call) + + +def owner_loop() -> asyncio.AbstractEventLoop | None: + """Return the loop that offloaded the current worker-thread call, if any. + + Returns: + The loop captured by :func:`run_in_worker_thread`, or ``None`` when + the caller was not started through it. + """ + return _owner_loop.get() diff --git a/src/agentomatic/cli/agent_guide.py b/src/agentomatic/cli/agent_guide.py index 345a4056..bcc56f8a 100644 --- a/src/agentomatic/cli/agent_guide.py +++ b/src/agentomatic/cli/agent_guide.py @@ -189,6 +189,7 @@ def state_to_output(self, state: HelloState) -> dict[str, Any]: | `AGENTOMATIC_ENABLE_CONTROL_PLANE` / `AGENTOMATIC_CONTROL_TOKEN` | Control plane | | `AGENTOMATIC_ENABLE_RATE_LIMIT` | Rate limiting | | `AGENTOMATIC_LOGS_HISTORY` | Persist per-agent invoke/chat/stream history (default off) | +| `AGENTOMATIC_EPHEMERAL_THREADS` | With no store/DB configured, keep chat threads in a bounded in-memory store (default on; `0` disables — thread routes then answer 400) | | `AGENTOMATIC_ALLOW_LOGSLLM_ANALYSIS` | Enable LLM analysis over those logs (default off) | | `AGENTOMATIC_INGESTION_ROOT` | Confine ingestion source/output paths to this dir (default: cwd) | | `AGENTOMATIC_TASK_EVENT_LOG` | Task-event replay backend: `memory` (default), `none` to disable, or a registered provider | diff --git a/src/agentomatic/cli/project.py b/src/agentomatic/cli/project.py index e310497e..64fc5dfd 100644 --- a/src/agentomatic/cli/project.py +++ b/src/agentomatic/cli/project.py @@ -270,6 +270,7 @@ def _env_example() -> str: # AGENTOMATIC_ENABLE_CONTROL_PLANE=0 # needs AGENTOMATIC_CONTROL_TOKEN # AGENTOMATIC_ENABLE_RATE_LIMIT=0 # AGENTOMATIC_LOGS_HISTORY=0 # persist invoke/chat/stream history +# AGENTOMATIC_EPHEMERAL_THREADS=1 # no DB? keep chat threads in memory (0 = off) # AGENTOMATIC_ALLOW_LOGSLLM_ANALYSIS=0 # LLM analysis over those logs # AGENTOMATIC_PLUGIN_AUTORELOAD=0 # reload plugins when artifact current changes # AGENTOMATIC_PLUGIN_AUTORELOAD_INTERVAL=5 diff --git a/src/agentomatic/cli/templates.py b/src/agentomatic/cli/templates.py index 98dadf9a..d27d048f 100644 --- a/src/agentomatic/cli/templates.py +++ b/src/agentomatic/cli/templates.py @@ -218,6 +218,7 @@ def state_to_output(self, state: {title}State) -> dict[str, Any]: class {title}State: """Agent state — per-run transient data.""" request: str = "" + messages: list[Any] = field(default_factory=list) context: list[str] = field(default_factory=list) output: dict[str, Any] = field(default_factory=dict) @@ -253,14 +254,21 @@ def build_graph(self): g.set_finish_point("process") return g.compile() + def _turns(self, state: {title}State) -> list[Any]: + """Build the chat messages for the model: system prompt, then the turns. + + ``/chat`` and Studio chat load the thread into ``state.messages``, + ending with the current turn, so the agent answers in context. A + one-shot call (``/invoke``, tasks, ``fit``) has just the request. + """ + turns = state.messages or [{{"role": "user", "content": state.request}}] + return [{{"role": "system", "content": self._system_prompt()}}, *turns] + def process(self, state: {title}State) -> {title}State: - prompt = self._system_prompt() state.context = [f"Processed: {{state.request}}"] if self.llm is not None: try: - result = self.llm.invoke( - f"{{prompt}}\\n\\nUser: {{state.request}}" - ) + result = self.llm.invoke(self._turns(state)) text = getattr(result, "content", None) or str(result) except Exception as exc: # noqa: BLE001 text = f"Result for: {{state.request}} (llm error: {{exc}})" @@ -273,7 +281,10 @@ def process(self, state: {title}State) -> {title}State: return state def input_to_state(self, input_data: dict[str, Any]) -> {title}State: - return {title}State(request=input_data.get("current_query", "")) + return {title}State( + request=input_data.get("current_query", ""), + messages=input_data.get("messages", []), + ) def state_to_output(self, state: {title}State) -> dict[str, Any]: return state.output diff --git a/src/agentomatic/core/agent_invoke.py b/src/agentomatic/core/agent_invoke.py index dccb7b8c..7ac3934e 100644 --- a/src/agentomatic/core/agent_invoke.py +++ b/src/agentomatic/core/agent_invoke.py @@ -84,12 +84,10 @@ def build_invoke_state( user_id = data.get("user_id") or "default-user" thread_id = data.get("thread_id") or default_thread_id or f"thread_{uuid.uuid4().hex[:12]}" - context = data.get("context") if isinstance(data.get("context"), dict) else {} - if not isinstance(context, dict): - context = {} - metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {} - if not isinstance(metadata, dict): - metadata = {} + # Copy the nested dicts: the payload is often a stored record (a task's + # ``input``), and the knob mirroring below must not write back into it. + context = dict(data["context"]) if isinstance(data.get("context"), dict) else {} + metadata = dict(data["metadata"]) if isinstance(data.get("metadata"), dict) else {} # Preserve every non-structural top-level key (extras + known knobs). extras = {k: v for k, v in data.items() if k not in _STRUCTURAL_KEYS} diff --git a/src/agentomatic/core/platform.py b/src/agentomatic/core/platform.py index e6a3d7a3..2fd7d584 100644 --- a/src/agentomatic/core/platform.py +++ b/src/agentomatic/core/platform.py @@ -120,6 +120,26 @@ def _minimal_openapi_paths(routes: Any) -> dict[str, Any]: return paths +_EPHEMERAL_MAX_THREADS = 1000 +"""Thread cap for the in-memory store used when no durable store is configured.""" + + +def _env_flag(var: str, default: bool) -> bool: + """Read a boolean feature flag from the environment. + + Args: + var: Environment variable name. + default: Value used when the variable is unset or empty. + + Returns: + ``True`` for ``1/true/yes/on`` (case-insensitive), else ``False``. + """ + raw = os.getenv(var) + if raw is None or not raw.strip(): + return default + return raw.strip().lower() in {"1", "true", "yes", "on"} + + class _LazyStoreProxy(BaseStore): """Proxy that resolves ``platform._store`` at call time. @@ -779,27 +799,40 @@ async def _init_connections(self) -> None: await self._auto_derive_store_from_connections() if self._store is None: await self._auto_derive_store_from_database_url() - if self._store is None and self._logs_history: - if db_url_configured: - # A DB was configured — do not silently fall back to memory - # (that would make audit/logs look "on" while not persisting). - logger.error( - "logs_history=True and a database URL is configured, but " - "SQLAlchemyStore could not be initialised. Fix DATABASE_URL " - "/ AGENTOMATIC_DB_URL / MEMORY connection — refusing " - "ephemeral MemoryStore fallback." - ) - else: - from agentomatic.storage import MemoryStore - - self._store = MemoryStore() - self._provisional_memory_store = True - logger.warning( - "logs_history=True without a durable store — using MemoryStore " - "(ephemeral; lost on restart). Pass store=SQLAlchemyStore(...), " - "declare a MEMORY connection, or set DATABASE_URL / " - "AGENTOMATIC_DB_URL (Postgres, SQLite, or any SQLAlchemy async URL)." - ) + if self._store is None and db_url_configured: + # A DB was configured — do not silently fall back to memory + # (that would make threads / audit logs look "on" while not + # persisting anything). + logger.error( + "A database URL is configured, but SQLAlchemyStore could not be " + "initialised. Fix DATABASE_URL / AGENTOMATIC_DB_URL / MEMORY " + "connection — refusing the ephemeral MemoryStore fallback, so " + "conversation threads" + + (" and invocation logs" if self._logs_history else "") + + " are unavailable." + ) + elif self._store is None and ( + self._logs_history or _env_flag("AGENTOMATIC_EPHEMERAL_THREADS", True) + ): + # Nothing durable is configured (the default for a freshly + # scaffolded project). Without *some* store every thread route + # answered 400 "Thread storage not configured" — and Studio's chat + # creates a thread before its first message, so chatting with any + # template agent failed out of the box. A bounded in-memory store + # keeps chat, /chat history and HITL approvals working, while the + # thread cap stops a long-running process growing without bound. + from agentomatic.storage import MemoryStore + + self._store = MemoryStore(max_threads=_EPHEMERAL_MAX_THREADS) + self._provisional_memory_store = True + logger.warning( + "No durable store configured — using an in-memory store for " + f"conversation threads{' and invocation logs' if self._logs_history else ''} " + f"(ephemeral, lost on restart, capped at {_EPHEMERAL_MAX_THREADS} threads). " + "Pass store=SQLAlchemyStore(...), declare a MEMORY connection, or set " + "DATABASE_URL / AGENTOMATIC_DB_URL (Postgres, SQLite, or any SQLAlchemy " + "async URL). Set AGENTOMATIC_EPHEMERAL_THREADS=0 to disable this fallback." + ) def _resolve_database_url(self) -> str | None: """Resolve the platform DB URL from env / active stack (if any). diff --git a/src/agentomatic/storage/memory.py b/src/agentomatic/storage/memory.py index 7ea0e674..b7184405 100644 --- a/src/agentomatic/storage/memory.py +++ b/src/agentomatic/storage/memory.py @@ -17,9 +17,19 @@ class MemoryStore(BaseStore): All data is lost when the process stops. For production, use :class:`~agentomatic.storage.sqlalchemy.SQLAlchemyStore` or implement your own :class:`BaseStore` subclass. + + Args: + max_threads: Optional cap on stored conversation threads. Once it is + reached, creating a thread evicts the least recently updated one + (with its messages, checkpoints and suspended states), so a + long-running process cannot grow without bound. ``None`` (the + default) keeps every thread. """ - def __init__(self) -> None: + def __init__(self, *, max_threads: int | None = None) -> None: + if max_threads is not None and max_threads < 1: + raise ValueError("max_threads must be at least 1") + self.max_threads = max_threads self._threads: dict[str, dict[str, Any]] = {} self._messages: dict[str, list[dict[str, Any]]] = {} self._feedback: list[dict[str, Any]] = [] @@ -53,8 +63,20 @@ async def create_thread( } self._threads[thread_id] = thread self._messages[thread_id] = [] + await self._evict_overflow(keep=thread_id) return thread + async def _evict_overflow(self, *, keep: str) -> None: + """Drop least recently updated threads beyond :attr:`max_threads`.""" + if self.max_threads is None or len(self._threads) <= self.max_threads: + return + by_age = sorted( + (tid for tid in self._threads if tid != keep), + key=lambda tid: self._threads[tid].get("updated_at") or "", + ) + for tid in by_age[: len(self._threads) - self.max_threads]: + await self.delete_thread(tid) + async def get_thread(self, thread_id: str) -> dict[str, Any] | None: return self._threads.get(thread_id) diff --git a/src/agentomatic/studio/router.py b/src/agentomatic/studio/router.py index fb4e92c4..bdf18d3a 100644 --- a/src/agentomatic/studio/router.py +++ b/src/agentomatic/studio/router.py @@ -36,6 +36,41 @@ from agentomatic.storage.base import BaseStore +def _reply_text(payload: Any) -> str: + """Find the assistant reply in a Studio run's final output. + + Adapters report the final *state*, whose shape is agent-defined: a class + agent nests its output (``{"output": {"output": {"response": ...}}}``), a + LangGraph agent keeps ``response`` or an AI message at the end of + ``messages``. Breadth-first search for the shallowest non-empty + ``response`` string, then fall back to the last assistant message. + + Args: + payload: The run's recorded output. + + Returns: + The reply text, or ``""`` when none is found. + """ + queue: list[Any] = [payload] + messages: list[Any] = [] + while queue: + node = queue.pop(0) + if isinstance(node, dict): + response = node.get("response") + if isinstance(response, str) and response.strip(): + return response + if isinstance(node.get("messages"), list) and not messages: + messages = node["messages"] + queue.extend(v for v in node.values() if isinstance(v, dict)) + for message in reversed(messages): + role = message.get("role") or message.get("type") if isinstance(message, dict) else None + if role in ("assistant", "ai"): + content = message.get("content") + if isinstance(content, str) and content.strip(): + return content + return "" + + def _now_iso() -> str: """Return the current UTC time as an ISO-8601 string.""" return datetime.now(UTC).isoformat() @@ -184,6 +219,78 @@ def _get_adapter(name: str): agent = _resolve_agent(name) return agent, _adapter_for(agent) + # Studio chat must behave like ``/chat``: load the thread's history into + # ``state["messages"]`` before the run and persist the turn afterwards. + # Without it a chatbot answered every Studio message as if it were the + # first, and a reopened thread showed no messages at all. + memory = None + if store is not None: + from agentomatic.core.memory_manager import ConversationMemoryManager + + memory = ConversationMemoryManager(store=store) + + async def _attach_history(agent: Any, state: dict[str, Any]) -> str | None: + """Load thread history into ``state``; return the query to persist. + + Args: + agent: Registered agent being run. + state: Initial run state (mutated in place). + + Returns: + The user query when the turn should be saved after the run, else + ``None`` (no store, no chat-shaped query, or a structured input). + """ + query = state.get("current_query") + # ``bool(store)`` is False until lifespan has resolved a real store. + if memory is None or not store or not isinstance(query, str) or not query.strip(): + return None + try: + thread_id = await memory.get_or_create_thread( + state.get("thread_id"), + state.get("user_id") or "default-user", + agent.name, + title=query[:60], + ) + state["thread_id"] = thread_id + state["messages"] = await memory.load_history(thread_id, query) + except Exception as exc: # noqa: BLE001 - memory must never break a run + logger.warning(f"Studio history loading failed: {exc}") + return None + return query + + async def _with_memory( + frames: AsyncGenerator[str, None], + agent: Any, + run_id: str, + thread_id: str, + query: str | None, + ) -> AsyncGenerator[str, None]: + """Relay run frames, then save the turn once the run has completed.""" + async for frame in frames: + yield frame + await _save_turn(agent, run_id, thread_id, query) + + async def _save_turn(agent: Any, run_id: str, thread_id: str, query: str | None) -> None: + """Persist ``query`` and the run's reply to the thread (best-effort).""" + if memory is None or query is None: + return + run = tracker.get_run(run_id) + if run is None or run.status != "completed": + return + reply = _reply_text(run.output) + if not reply: + return + try: + await memory.save_turn( + thread_id, + query, + reply, + agent_name=getattr(agent, "slug", None) or agent.name, + assistant_metadata={"run_id": run_id, "source": "studio"}, + ) + except Exception as exc: # noqa: BLE001 + logger.warning(f"Studio turn persistence failed: {exc}") + # ================================================================== # Discovery endpoints # ================================================================== @@ -315,12 +422,15 @@ async def create_run(name: str, request: StudioRunRequest) -> StudioRunInfo: ) state = _build_studio_state(request, thread_id) + query = await _attach_history(_agent, state) + thread_id = state.get("thread_id") or thread_id # Execute — consume the stream to completion, discard SSE frames async for _frame in tracker.execute_with_adapter( adapter, state, run.id, thread_id, request.checkpoint_id, request.breakpoints ): pass + await _save_turn(_agent, run.id, thread_id, query) # Return the final run info updated_run = tracker.get_run(run.id) @@ -349,11 +459,24 @@ async def stream_run(name: str, request: StudioRunRequest) -> StreamingResponse: ) state = _build_studio_state(request, thread_id) + query = await _attach_history(_agent, state) + thread_id = state.get("thread_id") or thread_id return StreamingResponse( numbered_stream( - tracker.execute_with_adapter( - adapter, state, run.id, thread_id, request.checkpoint_id, request.breakpoints + _with_memory( + tracker.execute_with_adapter( + adapter, + state, + run.id, + thread_id, + request.checkpoint_id, + request.breakpoints, + ), + _agent, + run.id, + thread_id, + query, ), stream_id=run.id, owner=f"studio:{name}", diff --git a/src/agentomatic/tasks/progress.py b/src/agentomatic/tasks/progress.py index bae9f7d9..79aa7f38 100644 --- a/src/agentomatic/tasks/progress.py +++ b/src/agentomatic/tasks/progress.py @@ -76,13 +76,35 @@ def report_stage_sync( total: int | None = None, message: str = "", ) -> None: - """Schedule :func:`report_stage` from a sync graph node (no-op if no loop/ctx).""" + """Schedule :func:`report_stage` from a sync graph node (no-op if no loop/ctx). + + Sync nodes run in a worker thread (see + :func:`~agentomatic.async_utils.run_in_worker_thread`), where there is no + running loop. The report is then handed to the loop serving the task, so + progress keeps flowing to ``GET /tasks/{id}/events``. + """ ctx = get_task_context() if ctx is None: return try: loop = asyncio.get_running_loop() except RuntimeError: + from agentomatic.async_utils import owner_loop + + origin = owner_loop() + if origin is None or origin.is_closed(): + return + + async def _forward() -> None: + await ctx.report( + stage=stage, + percent=percent, + current=current, + total=total, + message=message or stage, + ) + + asyncio.run_coroutine_threadsafe(_forward(), origin) return task = loop.create_task( report_stage( diff --git a/tests/test_no_unhandled_500s.py b/tests/test_no_unhandled_500s.py index f7557c63..ba757175 100644 --- a/tests/test_no_unhandled_500s.py +++ b/tests/test_no_unhandled_500s.py @@ -13,8 +13,10 @@ None of those were caught by testing individual features, because each was only reachable in a configuration no individual test happened to build. This -module instead walks *every* mounted route and asserts none of them 5xx, in the -default no-store posture that a fresh `agentomatic run` actually uses. +module instead walks *every* mounted route and asserts none of them 5xx, both in +the default posture a fresh `agentomatic run` uses (no store configured, so the +platform falls back to a bounded in-memory store) and with that fallback +disabled (``AGENTOMATIC_EPHEMERAL_THREADS=0``, genuinely no store). """ from __future__ import annotations @@ -59,9 +61,8 @@ _CONTROL_TOKEN = "sweep-control-token" -@pytest.fixture(scope="module") -def swept_app(): - """A fully-featured platform in the DEFAULT posture: no store configured.""" +def _build_swept_app(): + """A fully-featured platform with no store configured.""" import tempfile from pathlib import Path @@ -84,6 +85,21 @@ async def echo(state: dict[str, Any]) -> dict[str, Any]: return platform.build() +@pytest.fixture(scope="module", params=["ephemeral-store", "no-store"]) +def swept_app(request): + """Both store postures: the default fallback, and the fallback disabled. + + The flag is read at lifespan start-up, which runs each time a test enters + ``TestClient``, so it stays set for the lifetime of the module-scoped app. + """ + with pytest.MonkeyPatch.context() as mp: + if request.param == "no-store": + mp.setenv("AGENTOMATIC_EPHEMERAL_THREADS", "0") + else: + mp.delenv("AGENTOMATIC_EPHEMERAL_THREADS", raising=False) + yield _build_swept_app() + + def _probe_targets(app) -> list[tuple[str, str, str]]: """Return ``(method, concrete_path, route_template)`` for every route.""" targets: list[tuple[str, str, str]] = [] @@ -136,9 +152,10 @@ def test_the_sweep_covers_a_meaningful_number_of_routes(swept_app) -> None: assert len(targets) >= 80, f"only {len(targets)} route/method pairs probed" -def test_store_dependent_routes_answer_4xx_rather_than_crashing(swept_app) -> None: +def test_store_dependent_routes_answer_4xx_rather_than_crashing(monkeypatch) -> None: """The specific regression: these need a store, and none is configured.""" - with TestClient(swept_app, raise_server_exceptions=False) as client: + monkeypatch.setenv("AGENTOMATIC_EPHEMERAL_THREADS", "0") + with TestClient(_build_swept_app(), raise_server_exceptions=False) as client: for path in ( "/api/v1/a1/optimization-runs", "/api/v1/a1/logs", @@ -150,6 +167,23 @@ def test_store_dependent_routes_answer_4xx_rather_than_crashing(swept_app) -> No ) +def test_default_posture_serves_thread_routes(monkeypatch) -> None: + """A fresh project configures no store — threads must still work. + + Studio's "New Chat" creates a thread before the first message; without a + store that answered 400 "Thread storage not configured", so no chat could + ever start on a freshly scaffolded project. + """ + monkeypatch.delenv("AGENTOMATIC_EPHEMERAL_THREADS", raising=False) + with TestClient(_build_swept_app(), raise_server_exceptions=False) as client: + created = client.post("/api/v1/a1/threads", json={"user_id": "u", "title": "New Chat"}) + assert created.status_code == 200, created.text + thread_id = created.json()["id"] + assert client.get(f"/api/v1/a1/threads/{thread_id}").status_code == 200 + assert client.get("/api/v1/a1/threads").json()["count"] == 1 + assert client.get("/api/v1/a1/optimization-runs").status_code == 200 + + def test_studio_graph_degrades_for_an_agent_without_a_graph(swept_app) -> None: """The Studio UI calls this for *every* agent; a node_fn-only agent has no graph to draw, which must not be a 500. diff --git a/tests/test_sync_node_offload.py b/tests/test_sync_node_offload.py new file mode 100644 index 00000000..7f283208 --- /dev/null +++ b/tests/test_sync_node_offload.py @@ -0,0 +1,188 @@ +# pyright: reportMissingParameterType=none +"""Sync graph nodes must not block the event loop. + +Template nodes call ``self.llm.invoke(...)`` — a blocking network call. The +async execution paths ran such nodes inline on the event loop, so while a model +answered the whole server stood still: an ``async`` task submission only +returned once the LLM had finished, and task polling, SSE progress and health +checks stalled with it. Sync nodes now run in a worker thread. +""" + +from __future__ import annotations + +import asyncio +import threading +import time +from dataclasses import dataclass, field +from typing import Any + +import pytest +from fastapi.testclient import TestClient + +from agentomatic import AgentPlatform +from agentomatic.agents import BaseGraphAgent +from agentomatic.storage import MemoryStore + + +@dataclass +class _State: + request: str = "" + output: dict[str, Any] = field(default_factory=dict) + + +class _SlowSyncAgent(BaseGraphAgent[_State]): + """A sync node that blocks like an LLM call and reports task progress.""" + + agent_name = "slow_sync" + agent_description = "blocking sync node" + delay = 0.6 + + def build_graph(self) -> Any: + g = self.new_graph() + g.add_node("work", self.work) + g.set_entry_point("work") + g.set_finish_point("work") + return g.compile() + + def work(self, state: _State) -> _State: + from agentomatic.tasks import report_stage_sync + + report_stage_sync("thinking", percent=50.0) + time.sleep(self.delay) + state.output = { + "response": f"done: {state.request}", + "prompt": self.resolve_system_prompt(default="default prompt"), + "thread": threading.current_thread().name, + } + return state + + def input_to_state(self, data: dict[str, Any]) -> _State: + return _State(request=data.get("current_query", "")) + + def state_to_output(self, state: _State) -> dict[str, Any]: + return state.output + + +@pytest.fixture +def client(tmp_path): + platform = AgentPlatform(agents_dir=tmp_path / "agents", enable_studio=False) + reg = _SlowSyncAgent().as_registered_agent() + platform.register_agent( + manifest=reg.manifest, + node_fn=reg.node_fn, + graph_fn=reg.graph_fn, + class_instance=reg.class_instance, + ) + with TestClient(platform.build()) as c: + yield c + + +class TestEventLoopStaysResponsive: + def test_async_task_submission_returns_before_the_node_finishes(self, client) -> None: + started = time.perf_counter() + response = client.post( + "/api/v1/tasks", + json={"target_type": "agent", "target": "slow_sync", "input": {"query": "x"}}, + ) + elapsed = time.perf_counter() - started + assert response.status_code == 202 + assert elapsed < _SlowSyncAgent.delay / 2, f"submission blocked for {elapsed:.2f}s" + + # While the node sleeps, other requests are still served. + health_started = time.perf_counter() + assert client.get("/health").status_code == 200 + assert time.perf_counter() - health_started < _SlowSyncAgent.delay / 2 + + task_id = response.json()["id"] + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + record = client.get(f"/api/v1/tasks/{task_id}").json() + if record["status"] == "succeeded": + break + time.sleep(0.05) + assert record["status"] == "succeeded", record + assert record["result"]["response"] == "done: x" + + def test_progress_from_an_offloaded_sync_node_reaches_the_task(self, client) -> None: + response = client.post( + "/api/v1/tasks", + json={ + "target_type": "agent", + "target": "slow_sync", + "input": {"query": "x"}, + "mode": "sync", + "wait": True, + }, + ) + task_id = response.json()["id"] + with client.stream("GET", f"/api/v1/tasks/{task_id}/events?since=1") as stream: + body = "".join(stream.iter_text()) + assert '"stage": "thinking"' in body or '"stage":"thinking"' in body, body + + def test_sync_node_runs_off_the_loop_thread(self, client) -> None: + response = client.post("/api/v1/slow_sync/invoke", json={"query": "x"}) + assert response.status_code == 200 + thread_name = response.json()["output"]["thread"] + assert thread_name != "MainThread" + + +class TestRequestPromptIsolation: + async def test_concurrent_runs_keep_their_own_prompt_override(self) -> None: + """Candidates scored concurrently must each see their own prompt.""" + agent = _SlowSyncAgent() + agent.delay = 0.2 + + async def run(prompt: str) -> str: + out = await agent.atransform({"current_query": "q", "system_prompt_override": prompt}) + return out["prompt"] + + results = await asyncio.gather(*(run(f"prompt {i}") for i in range(4))) + assert results == [f"prompt {i}" for i in range(4)] + # Nothing leaks once the runs are over. + assert agent._request_system_prompt is None + + def test_override_is_cleared_after_a_sync_transform(self) -> None: + agent = _SlowSyncAgent() + agent.delay = 0 + out = agent.transform({"current_query": "q", "system_prompt_override": "custom"}) + assert out["prompt"] == "custom" + assert agent.transform({"current_query": "q"})["prompt"] == "default prompt" + + +class TestBoundedMemoryStore: + async def test_oldest_threads_are_evicted_past_the_cap(self) -> None: + store = MemoryStore(max_threads=2) + for i in range(3): + await store.create_thread(f"t{i}", "u", "a") + await store.add_message(f"t{i}", "user", f"m{i}") + await asyncio.sleep(0.001) + assert await store.get_thread("t0") is None + assert await store.get_messages("t0") == [] + assert await store.get_thread("t1") is not None + assert await store.get_thread("t2") is not None + + async def test_recently_updated_thread_survives_eviction(self) -> None: + store = MemoryStore(max_threads=2) + await store.create_thread("old", "u", "a") + await asyncio.sleep(0.001) + await store.create_thread("mid", "u", "a") + await asyncio.sleep(0.001) + await store.add_message("old", "user", "still talking") + await asyncio.sleep(0.001) + await store.create_thread("new", "u", "a") + assert await store.get_thread("old") is not None + assert await store.get_thread("mid") is None + + def test_unbounded_by_default_and_validates_the_cap(self) -> None: + assert MemoryStore().max_threads is None + with pytest.raises(ValueError): + MemoryStore(max_threads=0) + + +def test_build_invoke_state_does_not_mutate_the_payload() -> None: + from agentomatic.core.agent_invoke import build_invoke_state + + payload: dict[str, Any] = {"query": "q", "temperature": 0.3, "metadata": {}, "context": {}} + state = build_invoke_state(payload) + assert state["metadata"] == {"temperature": 0.3} + assert payload["metadata"] == {} diff --git a/tests/test_template_chat_threads_tasks.py b/tests/test_template_chat_threads_tasks.py new file mode 100644 index 00000000..71ec6326 --- /dev/null +++ b/tests/test_template_chat_threads_tasks.py @@ -0,0 +1,301 @@ +# pyright: reportMissingParameterType=none +# pyright: reportAttributeAccessIssue=none +"""Every chat-capable template must chat, thread and run as a task out of the box. + +Regression for a freshly scaffolded project (``agentomatic new`` + +``agentomatic init NAME --template basic|full|...``) where talking to the agent +from Studio failed with ``400``: + +* Studio's "New Chat" creates a thread first (``POST /api/v1/{agent}/threads``). + No store is configured in a fresh project, so every thread route answered + ``400 "Thread storage not configured"`` and no conversation could start. +* Studio runs never loaded the thread's history nor saved the turn, so a + chatbot answered each message as if it were the first and a reopened thread + was empty. +* The ``basic`` / ``full`` templates sent the model a single string and ignored + ``state.messages`` entirely. + +The project is scaffolded with the real CLI and served from its own +``main.py`` — the same app ``agentomatic run`` / ``uvicorn main:app`` serve. +""" + +from __future__ import annotations + +import sys +import time +from pathlib import Path +from typing import Any + +import pytest +from click.testing import CliRunner +from fastapi.testclient import TestClient + +from agentomatic.cli.commands import cli +from agentomatic.cli.project import scaffold_project + +#: template -> agent name. Names are unique so their ``agents.`` modules +#: cannot collide with other suites' scaffolds in the same interpreter. +TEMPLATES = { + "basic": "tct_basic", + "full": "tct_full", + "chatbot": "tct_chat", + "rag": "tct_rag", + "coordinator": "tct_coord", + "extraction": "tct_extract", +} + +#: Templates whose single LLM call is a conversation (system + turns). +HISTORY_AWARE = ("basic", "full", "chatbot") + + +class RecordingLLM: + """Stand-in chat model that records every payload it is sent.""" + + def __init__(self) -> None: + self.calls: list[Any] = [] + + def invoke(self, payload: Any, **_: Any) -> Any: + self.calls.append(payload) + + class _Reply: + content = f"reply #{len(self.calls)}" + + return _Reply() + + +def _texts(payload: Any) -> list[str]: + """Flatten an LLM payload (str, dicts or LangChain messages) to texts.""" + if isinstance(payload, str): + return [payload] + out: list[str] = [] + for item in payload: + content = item.get("content") if isinstance(item, dict) else getattr(item, "content", "") + out.append(str(content)) + return out + + +def _purge_agent_modules() -> None: + for mod in [m for m in sys.modules if m == "agents" or m.startswith("agents.")]: + sys.modules.pop(mod, None) + + +@pytest.fixture(scope="module") +def project_app(tmp_path_factory): + """Scaffold a project with one agent per template and build its ``main:app``.""" + root = tmp_path_factory.mktemp("tpl_chat") + project = root / "proj" + scaffold_project(project, "proj", force=True) + runner = CliRunner() + with pytest.MonkeyPatch.context() as mp: + mp.chdir(project) + mp.delenv("AGENTOMATIC_EPHEMERAL_THREADS", raising=False) + mp.setenv("AGENTOMATIC_LOG_LEVEL", "WARNING") + for template, name in TEMPLATES.items(): + result = runner.invoke(cli, ["init", name, "--template", template]) + assert result.exit_code == 0, result.output + _purge_agent_modules() + mp.syspath_prepend(str(project)) + namespace: dict[str, Any] = {} + source = (project / "main.py").read_text() + exec(compile(source, str(project / "main.py"), "exec"), namespace) # noqa: S102 + platform = namespace["_platform"] + llms: dict[str, RecordingLLM] = {} + for name in TEMPLATES.values(): + agent = platform._registry.get(name) + assert agent is not None, f"agent {name} was not discovered" + llms[name] = RecordingLLM() + agent.class_instance.llm = llms[name] + with TestClient(namespace["app"]) as client: + yield client, llms + _purge_agent_modules() + + +def _stream_turn(client: TestClient, agent: str, thread_id: str, query: str) -> list[str]: + """Send one Studio chat turn and return its SSE data frames.""" + with client.stream( + "POST", + f"/studio/agents/{agent}/runs/stream", + json={"query": query, "thread_id": thread_id, "user_id": "studio-user"}, + ) as response: + assert response.status_code == 200 + return [line for line in response.iter_lines() if line.startswith("data:")] + + +def _wait(client: TestClient, task_id: str, timeout: float = 20.0) -> dict[str, Any]: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + record = client.get(f"/api/v1/tasks/{task_id}").json() + if record["status"] in {"succeeded", "failed", "cancelled"}: + return record + time.sleep(0.05) + raise AssertionError(f"task {task_id} did not finish") + + +@pytest.mark.parametrize("template", list(TEMPLATES)) +class TestStudioChat: + def test_new_chat_thread_can_be_created(self, project_app, template: str) -> None: + client, _ = project_app + agent = TEMPLATES[template] + response = client.post( + f"/api/v1/{agent}/threads", json={"user_id": "studio-user", "title": "New Chat"} + ) + assert response.status_code == 200, response.text + thread_id = response.json()["id"] + assert client.get(f"/api/v1/{agent}/threads/{thread_id}").status_code == 200 + listed = client.get(f"/api/v1/{agent}/threads").json() + assert thread_id in {t["id"] for t in listed["threads"]} + + def test_studio_turns_are_persisted(self, project_app, template: str) -> None: + client, _ = project_app + agent = TEMPLATES[template] + thread_id = client.post(f"/api/v1/{agent}/threads", json={"title": "t"}).json()["id"] + for query in ("My name is Ada.", "What is my name?"): + frames = _stream_turn(client, agent, thread_id, query) + assert not any('"run_error"' in f for f in frames), frames + messages = client.get(f"/api/v1/{agent}/threads/{thread_id}/messages").json()["messages"] + assert [m["role"] for m in messages] == ["user", "assistant", "user", "assistant"] + assert messages[0]["content"] == "My name is Ada." + assert messages[1]["content"].strip() + + def test_thread_lifecycle_routes(self, project_app, template: str) -> None: + client, _ = project_app + agent = TEMPLATES[template] + thread_id = client.post(f"/api/v1/{agent}/threads", json={"title": "t"}).json()["id"] + _stream_turn(client, agent, thread_id, "hello") + renamed = client.patch(f"/api/v1/{agent}/threads/{thread_id}", json={"title": "Renamed"}) + assert renamed.status_code == 200 + forked = client.post( + f"/api/v1/{agent}/threads/{thread_id}/fork", json={"message_index": 0} + ) + assert forked.status_code == 200, forked.text + assert client.delete(f"/api/v1/{agent}/threads/{thread_id}").status_code == 200 + + +@pytest.mark.parametrize("template", HISTORY_AWARE) +def test_prior_turns_reach_the_model_in_studio(project_app, template: str) -> None: + client, llms = project_app + agent = TEMPLATES[template] + thread_id = client.post(f"/api/v1/{agent}/threads", json={"title": "t"}).json()["id"] + _stream_turn(client, agent, thread_id, "Remember this token: ZX42QV") + _stream_turn(client, agent, thread_id, "What token did I give you?") + last = _texts(llms[agent].calls[-1]) + assert any("ZX42QV" in text for text in last), last + assert last[-1] == "What token did I give you?" + + +@pytest.mark.parametrize("template", ("basic", "full")) +def test_basic_templates_send_a_real_system_message(project_app, template: str) -> None: + client, llms = project_app + agent = TEMPLATES[template] + response = client.post(f"/api/v1/{agent}/invoke", json={"query": "ping"}) + assert response.status_code == 200, response.text + payload = llms[agent].calls[-1] + assert isinstance(payload, list) + assert payload[0]["role"] == "system" + assert payload[0]["content"].strip() + assert _texts(payload)[-1] == "ping" + + +@pytest.mark.parametrize("template", list(TEMPLATES)) +class TestTasks: + def test_async_task_succeeds(self, project_app, template: str) -> None: + client, _ = project_app + agent = TEMPLATES[template] + response = client.post( + "/api/v1/tasks", + json={"target_type": "agent", "target": agent, "input": {"query": "hello"}}, + ) + assert response.status_code == 202, response.text + record = _wait(client, response.json()["id"]) + assert record["status"] == "succeeded", record + assert record["result"] + + def test_sync_task_succeeds(self, project_app, template: str) -> None: + client, _ = project_app + agent = TEMPLATES[template] + response = client.post( + "/api/v1/tasks", + json={ + "target_type": "agent", + "target": agent, + "input": {"query": "hello"}, + "mode": "sync", + "wait": True, + }, + ) + assert response.status_code == 200, response.text + assert response.json()["status"] == "succeeded", response.json() + + def test_studio_task_board_defaults_are_accepted(self, project_app, template: str) -> None: + """The Task Board submits the defaults of the published input schema.""" + client, _ = project_app + agent = TEMPLATES[template] + schema = client.get(f"/studio/agents/{agent}/schemas").json()["input_schema"] + payload: dict[str, Any] = {} + for key, prop in (schema.get("properties") or {}).items(): + if "default" in prop: + payload[key] = prop["default"] + elif prop.get("type") == "object": + payload[key] = {} + payload["query"] = "from the task board" + response = client.post( + "/api/v1/tasks", + json={ + "target_type": "agent", + "target": agent, + "input": payload, + "mode": "sync", + "wait": True, + "retry": {"max_attempts": 3, "backoff": "exponential", "base_delay": 1}, + }, + ) + assert response.status_code == 200, response.text + assert response.json()["status"] == "succeeded", response.json() + + def test_task_input_is_not_mutated_by_the_run(self, project_app, template: str) -> None: + client, _ = project_app + agent = TEMPLATES[template] + response = client.post( + "/api/v1/tasks", + json={ + "target_type": "agent", + "target": agent, + "input": {"query": "hi", "metadata": {}}, + "mode": "sync", + "wait": True, + }, + ) + stored = response.json()["input"] + # A custom request schema (``full``) may not publish ``metadata``. + assert stored.get("metadata", {}) == {} + + +def test_a2a_task_round_trip(project_app) -> None: + client, _ = project_app + agent = TEMPLATES["basic"] + response = client.post(f"/api/v1/{agent}/a2a/tasks", json={"message": {"content": "hi"}}) + assert response.status_code == 200, response.text + task_id = response.json()["task_id"] + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + view = client.get(f"/api/v1/{agent}/a2a/tasks/{task_id}").json() + if view["status"] in {"completed", "failed", "canceled"}: + break + time.sleep(0.05) + assert view["status"] == "completed", view + + +def test_ephemeral_store_can_be_disabled(tmp_path: Path, monkeypatch) -> None: + """``AGENTOMATIC_EPHEMERAL_THREADS=0`` restores the explicit no-store posture.""" + from agentomatic import AgentManifest, AgentPlatform + + async def echo(state: dict[str, Any]) -> dict[str, Any]: + return {"response": "ok"} + + monkeypatch.setenv("AGENTOMATIC_EPHEMERAL_THREADS", "0") + platform = AgentPlatform(agents_dir=tmp_path / "agents") + platform.register_agent(manifest=AgentManifest(name="e1", slug="e1"), node_fn=echo) + with TestClient(platform.build()) as client: + response = client.post("/api/v1/e1/threads", json={"title": "t"}) + assert response.status_code == 400 + assert response.json()["detail"] == "Thread storage not configured" From 868755f8fbd3f2f3513fafb2198387c2bde53c98 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 18:49:09 +0000 Subject: [PATCH 02/16] fix(optimize): accept every metric protocol everywhere; hold the test split out of selection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `PromptFitterBridge(metric=OptimizeMetricAdapter(judge))` crashed mid-fit with "'OptimizeMetricAdapter' object has no attribute 'evaluate'" — logged as a warning, so fit() silently continued without optimizing. The two metric protocols (sync `score(example, prediction)` / async `evaluate(query, response, expected, context)`) are now bridged in both directions: `as_optimize_metric` / `ScoreMetricAdapter` and `as_agent_metric`, applied by compile/evaluate, MetricLoss/resolve_loss, agents.WeightedMetric, optimize.WeightedMetric/CompositeMetric, resolve_metrics, PromptFitterBridge (fails fast at construction) and PromptFitter.fit. - Class-agent metrics scored inside the fitter now see the example's metadata and the agent's structured output (scoring context), so a deterministic metric scores the same during selection as in agent.evaluate(). - OptimizeMetricAdapter no longer fabricates a neutral 0.5 when the judge fails: it scores 0.0, logs, and counts `failures`. - PromptFitterBridge folded the `test` split into the pool candidates are selected on; test is now passed to the fitter as its held-out set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- src/agentomatic/agents/__init__.py | 2 + src/agentomatic/agents/base.py | 10 +- src/agentomatic/agents/history.py | 13 +- src/agentomatic/agents/metrics.py | 91 +++++++++- src/agentomatic/agents/optimizers.py | 76 +++++++- src/agentomatic/optimize/__init__.py | 4 + src/agentomatic/optimize/fitter.py | 21 ++- src/agentomatic/optimize/metrics.py | 203 +++++++++++++++++++++- src/agentomatic/optimize/runner.py | 7 + tests/fake_openai_server.py | 197 +++++++++++++++++++++ tests/test_metric_protocol_bridge.py | 221 ++++++++++++++++++++++++ tests/test_optimization_bugs.py | 12 +- tests/test_optimize_cli_search_space.py | 2 +- 13 files changed, 819 insertions(+), 40 deletions(-) create mode 100644 tests/fake_openai_server.py create mode 100644 tests/test_metric_protocol_bridge.py diff --git a/src/agentomatic/agents/__init__.py b/src/agentomatic/agents/__init__.py index a1f8b866..070b26c7 100644 --- a/src/agentomatic/agents/__init__.py +++ b/src/agentomatic/agents/__init__.py @@ -69,6 +69,7 @@ def state_to_output(self, state): OptimizeMetricAdapter, ResponseSimilarityMetric, WeightedMetric, + as_agent_metric, ) from agentomatic.agents.optimizers import ( GridSearchOptimizer, @@ -116,6 +117,7 @@ def state_to_output(self, state): "WeightedMetric", "ResponseSimilarityMetric", "OptimizeMetricAdapter", + "as_agent_metric", # Optimizers "NoOpOptimizer", "GridSearchOptimizer", diff --git a/src/agentomatic/agents/base.py b/src/agentomatic/agents/base.py index d1be953c..c18223c2 100644 --- a/src/agentomatic/agents/base.py +++ b/src/agentomatic/agents/base.py @@ -558,6 +558,10 @@ def evaluate( """ if metrics is None: metrics = list(self._compile_metrics) + else: + from .metrics import as_agent_metric + + metrics = [as_agent_metric(m) for m in metrics] if not metrics: # A metric is a live Python object, so it cannot be written to # ``config.json`` and does not come back with ``load()``. Say so @@ -675,7 +679,11 @@ def compile( Returns: Self for chaining. """ - metrics = list(metrics or []) + from .metrics import as_agent_metric + + # Optimize metrics (``LocalJudgeMetric``, ``ExactMatchMetric``, …) are + # wrapped so they can be listed here directly. + metrics = [as_agent_metric(m) for m in (metrics or [])] if not metrics: logger.warning( "compile() called without metrics — fit()/evaluate() will " diff --git a/src/agentomatic/agents/history.py b/src/agentomatic/agents/history.py index d13d3bf3..d5640d3d 100644 --- a/src/agentomatic/agents/history.py +++ b/src/agentomatic/agents/history.py @@ -424,8 +424,11 @@ def compute(self, example: AgentExample, prediction: dict[str, Any]) -> float: class MetricLoss(Loss): """Turn a 0..1 (higher-better) metric into a loss (``1 - score``).""" - def __init__(self, metric: Metric, name: str | None = None) -> None: - self.metric = metric + def __init__(self, metric: Metric | Any, name: str | None = None) -> None: + from .metrics import as_agent_metric + + # Optimize metrics (e.g. ``LocalJudgeMetric``) are wrapped automatically. + self.metric = as_agent_metric(metric) self.name = name or f"{getattr(metric, 'name', 'metric')}_loss" def compute(self, example: AgentExample, prediction: dict[str, Any]) -> float: @@ -452,14 +455,14 @@ def resolve_loss(obj: Any) -> Loss | None: """Coerce ``obj`` into a :class:`Loss`. Accepts ``None`` (→ ``None``), an existing ``Loss``, a metric-like object - with ``.score`` (→ :class:`MetricLoss`), or a plain callable - (→ :class:`CallableLoss`). + with ``.score`` or an optimize metric with async ``.evaluate`` + (→ :class:`MetricLoss`), or a plain callable (→ :class:`CallableLoss`). """ if obj is None: return None if isinstance(obj, Loss): return obj - if hasattr(obj, "score"): + if hasattr(obj, "score") or callable(getattr(obj, "evaluate", None)): return MetricLoss(obj) if callable(obj): return CallableLoss( diff --git a/src/agentomatic/agents/metrics.py b/src/agentomatic/agents/metrics.py index b84a9515..937a2b60 100644 --- a/src/agentomatic/agents/metrics.py +++ b/src/agentomatic/agents/metrics.py @@ -16,6 +16,8 @@ from collections.abc import Callable, Sequence from typing import Any +from loguru import logger + from .types import AgentExample # --------------------------------------------------------------------------- @@ -273,10 +275,10 @@ def __init__( comp_name = getattr(comp_metric, "name", None) or "component" comp_weight = 1.0 - if not hasattr(comp_metric, "score"): - raise TypeError( - f"Component '{comp_name}' does not implement the Metric.score protocol" - ) + try: + comp_metric = as_agent_metric(comp_metric) + except TypeError as exc: + raise TypeError(f"Component '{comp_name}': {exc}") from exc components.append((str(comp_name), comp_metric, float(comp_weight))) total_weight = sum(w for _, _, w in components) @@ -304,7 +306,8 @@ def score( for comp_name, comp_metric, comp_weight in self._components: try: raw = comp_metric.score(example, prediction) - except Exception: + except Exception as exc: # noqa: BLE001 - see docstring + logger.warning(f"WeightedMetric component '{comp_name}' failed: {exc}") raw = 0.0 component_scores[comp_name] = float(raw) weighted_sum += float(raw) * comp_weight @@ -333,6 +336,16 @@ class OptimizeMetricAdapter: :func:`agentomatic.async_utils.run_sync` (persistent loop; works inside an existing event loop via a worker thread) + The adapter speaks **both** metric protocols, so the same object can be + used as a ``compile(metrics=[...])`` entry, inside ``agents.WeightedMetric`` + / ``MetricLoss``, *and* as the ``metric=`` fit objective of + ``PromptFitterBridge`` / ``PromptFitter`` (which call the async + :meth:`evaluate`). + + A failed evaluation (judge unreachable, unparsable reply) scores ``0.0`` + and is logged and counted in :attr:`failures` — never a made-up + mid-scale score that would hide the outage from the optimizer. + Args: optimize_metric: An instance of ``optimize.BaseMetric``. name: Optional override name. @@ -352,10 +365,38 @@ def __init__( optimize_metric: Any, name: str | None = None, ) -> None: + if not callable(getattr(optimize_metric, "evaluate", None)): + raise TypeError( + f"OptimizeMetricAdapter wraps an optimize metric with an async " + f"`evaluate(query, response, expected, context)`; got " + f"{type(optimize_metric).__name__}. Class-agent metrics with " + "`score(example, prediction)` can be used directly." + ) self._metric = optimize_metric self.name = name or getattr(optimize_metric, "name", "adapted_metric") self.last_result: Any | None = None """Most recent ``EvalResult`` from :meth:`score` (for report rationales).""" + self.failures = 0 + """Number of evaluations that failed and were scored ``0.0``.""" + + @property + def optimize_metric(self) -> Any: + """The wrapped ``optimize.BaseMetric``.""" + return self._metric + + async def evaluate( + self, + query: str, + response: str, + expected: str | None = None, + context: list[str] | None = None, + ) -> Any: + """Delegate to the wrapped metric's async ``evaluate`` (fit objective path). + + Returns: + The wrapped metric's ``EvalResult``. + """ + return await self._metric.evaluate(query, response, expected, context) def score( self, @@ -442,10 +483,44 @@ def score( # async clients survive across fit → evaluate. try: result = run_sync(self._metric.evaluate(query, response, expected, context)) - except Exception: - return 0.5 # judge unavailable — neutral, don't crash training + except Exception as exc: # noqa: BLE001 - one failed judge call must not abort fit + self.failures += 1 + logger.warning(f"Metric '{self.name}' failed ({exc}); scoring this example 0.0") + return 0.0 self.last_result = result if (getattr(result, "metadata", None) or {}).get("evaluation_failed"): + self.failures += 1 return 0.0 - return float(getattr(result, "score", 0.5)) + return float(getattr(result, "score", 0.0) or 0.0) + + +def as_agent_metric(metric: Any) -> Any: + """Coerce any supported metric into the class-agent ``Metric`` protocol. + + ``compile(metrics=[...])``, ``evaluate(metrics=[...])``, + ``agents.WeightedMetric`` and ``MetricLoss`` call the sync + ``score(example, prediction)``. An optimize metric (``LocalJudgeMetric``, + ``LLMJudgeMetric``, ``ExactMatchMetric``, …) only has the async + ``evaluate`` — it is wrapped in :class:`OptimizeMetricAdapter` so it can be + passed anywhere without manual wrapping. + + Args: + metric: A class-agent metric or an optimize metric. + + Returns: + An object with ``name`` and ``score(example, prediction) -> float``. + + Raises: + TypeError: When ``metric`` implements neither protocol. + """ + if callable(getattr(metric, "score", None)): + return metric + if callable(getattr(metric, "evaluate", None)): + return OptimizeMetricAdapter(metric) + raise TypeError( + f"{type(metric).__name__} is not a usable metric: implement " + "`score(example, prediction) -> float` (agentomatic.agents.Metric) or " + "`async evaluate(query, response, expected=None, context=None)` " + "(agentomatic.optimize.BaseMetric)." + ) diff --git a/src/agentomatic/agents/optimizers.py b/src/agentomatic/agents/optimizers.py index f3ec5c50..77e39149 100644 --- a/src/agentomatic/agents/optimizers.py +++ b/src/agentomatic/agents/optimizers.py @@ -190,8 +190,11 @@ class PromptFitterBridge: agent_name: Name for the fitter to use. task_model: Model for running tasks. rewrite_model: Model for prompt rewriting. - metric: An ``optimize.BaseMetric`` used as the fit objective. Defaults - to ``ExactMatchMetric`` when omitted. + metric: The fit objective PromptFitter selects candidates with. Any + metric works: an ``optimize.BaseMetric`` (``LocalJudgeMetric``, + ``CompositeMetric``, …), an ``OptimizeMetricAdapter`` (unwrapped), + or a class-agent metric with ``score(example, prediction)`` + (wrapped). Defaults to ``ExactMatchMetric`` when omitted. max_trials: Maximum optimization trials. fitter: Pre-built fitter instance (mainly for testing / advanced use); when given, construction kwargs are ignored. @@ -258,7 +261,14 @@ def __init__( self.task_model = task_model self.rewrite_model = rewrite_model self.optimizer = optimizer - self.metric = metric + # Coerce now so an unusable metric fails at construction with a clear + # message instead of mid-fit (where it was logged and skipped). An + # injected ``fitter`` owns its metric contract, so it gets it verbatim. + from agentomatic.optimize.metrics import as_optimize_metric + + self.metric = ( + as_optimize_metric(metric) if metric is not None and fitter is None else metric + ) self.max_trials = max_trials self.fitter = fitter self.local_agent = local_agent @@ -300,13 +310,20 @@ def _skip(reason: str) -> dict[str, Any]: if not len(opt_dataset): return _skip("empty dataset") - trainset, valset = self._split(opt_dataset) + trainset, valset, testset = self._split_three(opt_dataset) metric = self._resolve_metric() if metric is None: return _skip("no usable metric") + logger.info( + "PromptFitterBridge: train={} (proposals) · validation={} (selection) · " + "test={} (held out — generalization gate only)", + len(trainset), + len(valset), + len(testset) if testset is not None else "auto-reserved from validation", + ) try: - result = self._run_async(fitter.fit(trainset, valset, metric)) + result = self._run_async(fitter.fit(trainset, valset, metric, testset=testset)) except RuntimeError as exc: return _skip(f"cannot run fitter here ({exc})") except Exception as exc: # noqa: BLE001 @@ -440,9 +457,56 @@ def _resolve_metric(self) -> Any | None: except Exception: # noqa: BLE001 return None + @staticmethod + def _split_three(opt_dataset: Any) -> tuple[Any, Any, Any | None]: + """Split into ``(train, validation, test)`` without leaking ``test``. + + * ``train`` — failure analysis and few-shot demonstrations. + * ``validation`` — the only data candidates are scored/selected on. + * ``test`` — handed to the fitter as its held-out ``testset``: it is + never used for selection, only for the generalization gate that + rejects an overfit candidate (and for the reported holdout score). + + The ``test`` split used to be folded into the validation pool, so the + "held-out" score was measured on data the winner had been picked on. + + Without a ``validation`` split, validation is carved (20%) from + ``train``. Without a ``test`` split, ``None`` is returned and the + fitter reserves its own holdout slice from validation. + """ + from agentomatic.optimize.dataset import Dataset + + points = list(getattr(opt_dataset, "points", []) or []) + + def _split_of(point: Any) -> str: + return str((getattr(point, "metadata", None) or {}).get("split", "train")) + + train = [p for p in points if _split_of(p) == "train"] + val = [p for p in points if _split_of(p) in ("validation", "val")] + test = [p for p in points if _split_of(p) == "test"] + testset = Dataset(points=test) if test else None + if train and not val and len(train) >= 2: + cut = max(1, int(round(len(train) * 0.8))) + cut = min(cut, len(train) - 1) + train, val = train[:cut], train[cut:] + if train and val: + return Dataset(points=train), Dataset(points=val), testset + if val and not train: + return Dataset(points=val), Dataset(points=val), testset + if test and not train and not val: + # Only a test split was labelled: nothing else to learn from. + train_ds, val_ds = PromptFitterBridge._split(Dataset(points=test)) + return train_ds, val_ds, None + train_ds, val_ds = PromptFitterBridge._split(opt_dataset) + return train_ds, val_ds, None + @staticmethod def _split(opt_dataset: Any) -> tuple[Any, Any]: - """Prefer ``metadata.split`` labels; else fall back to an 80/20 cut.""" + """Prefer ``metadata.split`` labels; else fall back to an 80/20 cut. + + Two-way split kept for callers that do not hold out a test set; + :meth:`optimize` uses :meth:`_split_three`. + """ from agentomatic.optimize.dataset import Dataset points = list(getattr(opt_dataset, "points", []) or []) diff --git a/src/agentomatic/optimize/__init__.py b/src/agentomatic/optimize/__init__.py index ff044bad..266f8766 100644 --- a/src/agentomatic/optimize/__init__.py +++ b/src/agentomatic/optimize/__init__.py @@ -202,7 +202,9 @@ LLMJudgeMetric, MetricResult, RedTeamMetric, + ScoreMetricAdapter, WeightedMetric, + as_optimize_metric, resolve_metrics, ) from agentomatic.optimize.optimizer import OptimizationResult, PromptOptimizer @@ -401,6 +403,8 @@ "BaseMetric", "ContainsMetric", "CustomMetric", + "ScoreMetricAdapter", + "as_optimize_metric", "DeepEvalMetric", "ExactMatchMetric", "GEvalMetric", diff --git a/src/agentomatic/optimize/fitter.py b/src/agentomatic/optimize/fitter.py index 99a40059..0c17628c 100644 --- a/src/agentomatic/optimize/fitter.py +++ b/src/agentomatic/optimize/fitter.py @@ -632,6 +632,11 @@ async def fit( tracker = None tracker_exp_id = None + # Any metric protocol is accepted: class-agent ``score()`` metrics and + # ``OptimizeMetricAdapter`` are bridged to the async ``evaluate()``. + from agentomatic.optimize.metrics import as_optimize_metric + + metric = as_optimize_metric(metric) metric = self._augment_metric_with_local_judges(metric) # ── Generalization safety net: always reserve a holdout ────── @@ -1806,13 +1811,15 @@ async def _evaluate_config( continue try: - # TODO: check if thise should be calling metric.score or metric evaluate ? and check entire metrics code for inifications - eval_result: EvalResult = await metric.evaluate( - query=rr.query, - response=rr.response, - expected=rr.expected, - context=rr.context or rr.retrieval_context, - ) + from agentomatic.optimize.metrics import scoring_run + + with scoring_run(rr): + eval_result: EvalResult = await metric.evaluate( + query=rr.query, + response=rr.response, + expected=rr.expected, + context=rr.context or rr.retrieval_context, + ) # Honest eval: skip fabricated / failed judge scores from the # average so a broken LLM-as-judge cannot invent mid-scale loss. if (eval_result.metadata or {}).get("evaluation_failed"): diff --git a/src/agentomatic/optimize/metrics.py b/src/agentomatic/optimize/metrics.py index 23e2ba79..a68ca8b6 100644 --- a/src/agentomatic/optimize/metrics.py +++ b/src/agentomatic/optimize/metrics.py @@ -21,7 +21,9 @@ import os import re from abc import ABC, abstractmethod -from collections.abc import Callable +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from contextvars import ContextVar from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, cast @@ -820,7 +822,9 @@ def resolve_metrics( - ``"red_team"`` — adversarial scoring Args: - metrics: List of metric names (str) or BaseMetric instances. + metrics: List of metric names (str) or metric instances — a + ``BaseMetric``, an ``OptimizeMetricAdapter`` or a class-agent + ``score(example, prediction)`` metric. model: LLM model for evaluation (used by DeepEval/LLM metrics). Returns: @@ -828,13 +832,12 @@ def resolve_metrics( """ resolved: list[BaseMetric] = [] for m in metrics: - if isinstance(m, BaseMetric): - resolved.append(m) - else: - m_any: Any = m - if not isinstance(m_any, str): - raise TypeError(f"Expected str or BaseMetric, got {type(m)}") + m_any: Any = m + if isinstance(m_any, str): resolved.append(_resolve_single(m_any, model)) + else: + # Instances of either metric protocol (see ``as_optimize_metric``). + resolved.append(as_optimize_metric(m_any)) return resolved @@ -937,6 +940,11 @@ class WeightedMetric: metric: BaseMetric weight: float = 1.0 + def __post_init__(self) -> None: + # Accept class-agent ``score()`` metrics and ``OptimizeMetricAdapter`` + # too: CompositeMetric awaits ``metric.evaluate`` on every component. + self.metric = as_optimize_metric(self.metric) + class CompositeMetric(BaseMetric): """Weighted composition of multiple metrics returning ``MetricResult``. @@ -1389,3 +1397,182 @@ def _extract_tokens( pass # Rough estimate: ~4 chars per token return max(1, len(response) // 4) + + +# ===================================================================== +# Protocol bridge: agents.Metric (sync ``score``) ⇄ optimize.BaseMetric +# ===================================================================== + +#: The run being scored by ``PromptFitter`` (set around each ``evaluate`` +#: call). Lets example-aware metrics reach the dataset metadata and the +#: agent's structured output, which the string-based ``evaluate`` signature +#: cannot carry. ``None`` outside a fitter scoring pass. +_SCORING_RUN: ContextVar[Any] = ContextVar("agentomatic_scoring_run", default=None) + + +@contextmanager +def scoring_run(run: Any) -> Iterator[None]: + """Expose ``run`` (a ``RunResult``) to metrics evaluated in this block. + + Args: + run: The run result being scored. + + Yields: + Nothing; the run is visible via :func:`current_scoring_run`. + """ + token = _SCORING_RUN.set(run) + try: + yield + finally: + _SCORING_RUN.reset(token) + + +def current_scoring_run() -> Any: + """Return the ``RunResult`` currently being scored, if any.""" + return _SCORING_RUN.get() + + +def _decode_json_dict(text: str | None) -> dict[str, Any] | None: + """Return ``text`` parsed as a JSON object, or ``None`` when it is not one.""" + import json + + if not text: + return None + stripped = text.strip() + if not stripped.startswith("{"): + return None + try: + value = json.loads(stripped) + except ValueError: + return None + return value if isinstance(value, dict) else None + + +_STRUCTURED_HEADER = re.compile( + r"^[ \t]*##[ \t]*Expected structured output[ \t]*$", re.MULTILINE | re.IGNORECASE +) + + +def _expected_structured(expected: str | None) -> dict[str, Any] | None: + """Recover ``expected_output`` from an ``AgentExample.to_datapoint`` reference.""" + if not expected: + return None + header = _STRUCTURED_HEADER.search(expected) + if header is None: + return None + rest = expected[header.end() :] + following = _ANY_SECTION_HEADER.search(rest) + return _decode_json_dict(rest[: following.start()] if following else rest) + + +class ScoreMetricAdapter(BaseMetric): + """Run a sync ``score(example, prediction)`` metric as an optimize metric. + + Class-agent metrics (:mod:`agentomatic.agents.metrics` — e.g. + ``ExactKeyMatchMetric``, ``ContainsTermsMetric``, ``agents.WeightedMetric``) + implement ``score(example, prediction) -> float``. ``PromptFitter`` scores + candidates through the async ``evaluate(query, response, expected, + context)`` protocol instead, so handing it such a metric used to fail with + ``AttributeError: ... has no attribute 'evaluate'``. This adapter rebuilds + an :class:`~agentomatic.agents.types.AgentExample` and a prediction dict + and calls ``score`` in a worker thread. Inside ``PromptFitter`` the + rebuilt example carries the dataset metadata (``must_include``, rubric + hints, …) and the prediction is the agent's full structured output, so a + class-agent metric scores exactly as it does in ``agent.evaluate``. + + You rarely need it directly — :func:`as_optimize_metric` applies it + wherever an optimize metric is required. + + Args: + metric: Object with ``score(example, prediction) -> float``. + name: Optional override name (defaults to ``metric.name``). + """ + + def __init__(self, metric: Any, name: str | None = None) -> None: + self.metric = metric + self.name = name or str(getattr(metric, "name", None) or "score_metric") + + async def evaluate( + self, + query: str, + response: str, + expected: str | None = None, + context: list[str] | None = None, + ) -> EvalResult: + """Score ``response`` with the wrapped sync metric.""" + import asyncio + + from agentomatic.agents.types import AgentExample + + run = current_scoring_run() + run_meta = dict(getattr(run, "metadata", None) or {}) + example_meta = dict(run_meta.get("example") or {}) + + answer = plain_expected(expected) + expected_output = _expected_structured(expected) or _decode_json_dict(answer) + if expected_output is None and answer is not None: + expected_output = {"response": answer} + example = AgentExample( + id=str(example_meta.get("id") or "fit"), + input={ + "current_query": query, + "query": query, + "question": query, + **({"context": list(context)} if context else {}), + }, + expected_output=expected_output, + metadata=example_meta, + split=str(example_meta.get("split") or "validation"), + ) + output = run_meta.get("output") + prediction = ( + dict(output) + if isinstance(output, dict) + else (_decode_json_dict(response) or {"response": response}) + ) + score = await asyncio.to_thread(self.metric.score, example, prediction) + return EvalResult( + metric_name=self.name, + score=max(0.0, min(1.0, float(score))), + reason=f"{type(self.metric).__name__}.score", + ) + + +def as_optimize_metric(metric: Any) -> BaseMetric: + """Coerce any supported metric into an optimize :class:`BaseMetric`. + + Accepts, in order: + + 1. An ``OptimizeMetricAdapter`` — unwrapped to the optimize metric it + carries (keeps ``CompositeMetric`` per-dimension tracking intact). + 2. A :class:`BaseMetric` (or any object with an async ``evaluate``). + 3. A class-agent metric with ``score(example, prediction)`` — wrapped in + :class:`ScoreMetricAdapter`. + + Args: + metric: The metric to coerce. + + Returns: + A metric exposing ``async evaluate(query, response, expected, context)``. + + Raises: + TypeError: When ``metric`` implements neither protocol. + """ + import inspect + + from agentomatic.agents.metrics import OptimizeMetricAdapter + + if isinstance(metric, OptimizeMetricAdapter): + return as_optimize_metric(metric.optimize_metric) + if isinstance(metric, BaseMetric): + return metric + if inspect.iscoroutinefunction(getattr(metric, "evaluate", None)): + return cast(BaseMetric, metric) + if callable(getattr(metric, "score", None)): + return ScoreMetricAdapter(metric) + raise TypeError( + f"{type(metric).__name__} is not a usable metric: implement " + "`async evaluate(query, response, expected=None, context=None) -> EvalResult` " + "(agentomatic.optimize.BaseMetric) or " + "`score(example, prediction) -> float` (agentomatic.agents.Metric)." + ) diff --git a/src/agentomatic/optimize/runner.py b/src/agentomatic/optimize/runner.py index d4ab75c3..105885d8 100644 --- a/src/agentomatic/optimize/runner.py +++ b/src/agentomatic/optimize/runner.py @@ -175,6 +175,9 @@ async def _run_local( query=query, response=response, duration_ms=duration, + # The full structured output, for metrics that score fields + # other than the response text (see ScoreMetricAdapter). + metadata={"output": raw} if isinstance(raw, dict) else {}, ) except Exception as exc: duration = (time.perf_counter() - t0) * 1000 @@ -349,6 +352,10 @@ async def _run_one(point: dict[str, Any]) -> RunResult: result.expected = point.get("expected_answer") or point.get("expected") if not result.context: result.context = point.get("context", []) + if isinstance(meta, dict) and meta: + # Dataset metadata (rubric hints, required facts, split…) + # for example-aware metrics. + result.metadata = {**result.metadata, "example": dict(meta)} return result return list(await asyncio.gather(*[_run_one(p) for p in points])) diff --git a/tests/fake_openai_server.py b/tests/fake_openai_server.py new file mode 100644 index 00000000..4fd5949a --- /dev/null +++ b/tests/fake_openai_server.py @@ -0,0 +1,197 @@ +"""A deterministic OpenAI-compatible model server for offline optimization tests. + +It plays every role the optimization stack sends to an LLM, recognising each +by its prompt: + +* **agent** (``Policy snippets: … Question: …``) — answers *well* (quotes the + snippets) only when the system prompt asks it to quote policy, and vaguely + otherwise. A better prompt therefore measurably scores higher, which is + what makes an optimization run meaningful. +* **judge** (``You are an expert evaluation judge``) — returns the + ``overall_score`` JSON ``LocalJudgeMetric`` expects, scored by how many + words of the expected answer the response recalls. +* **rewriter** (asks for an improved system prompt) — returns + :data:`IMPROVED_PROMPT` after a ``---`` line. +* **augmenter** (``dataset augmentation expert``) — returns a JSON array of + paraphrased seed queries. + +Every request body is recorded on :attr:`FakeOpenAIServer.requests`. +""" + +from __future__ import annotations + +import json +import re +import socket +import threading +import time +from typing import Any + +from fastapi import FastAPI, Request + +#: The prompt the fake rewriter proposes. Contains the trigger word ("quote"). +IMPROVED_PROMPT = ( + "You are a precise Acme Cloud support assistant. Quote the relevant policy " + "snippet verbatim, then answer in one short sentence. Never invent policy." +) + +_VAGUE_ANSWER = "Thanks for reaching out! Our team is happy to help with that." + + +def _words(text: str) -> set[str]: + return {w for w in re.findall(r"[a-z0-9>:.-]+", text.lower()) if len(w) > 3} + + +def _section(prompt: str, header: str) -> str: + match = re.search(rf"## {re.escape(header)}[^\n]*\n(.*?)(?:\n## |\Z)", prompt, re.S) + return match.group(1).strip() if match else "" + + +def _agent_reply(system: str, user: str) -> str: + snippets = [line[2:].strip() for line in user.splitlines() if line.startswith("- ")] + if "quote" in system.lower() and snippets: + return " ".join(snippets) + return _VAGUE_ANSWER + + +def _judge_reply(prompt: str) -> str: + response = _section(prompt, "AI Response") + # A dataset reference nests its own "## Expected answer" section. + expected = _section(prompt, "Expected answer") or _section( + prompt, "Expected / Quality Reference" + ) + wanted = _words(expected) + score = round(len(wanted & _words(response)) / len(wanted), 2) if wanted else 0.5 + return json.dumps( + { + "overall_score": score, + "feedback": "Grounded in policy." if score >= 0.5 else "Too vague; cite the policy.", + "motivation": f"Recalled {score:.0%} of the reference facts.", + "what_worked": ["polite tone"], + "what_failed": [] if score >= 0.5 else ["does not state the policy"], + "improvement_hints": ["Quote the relevant policy snippet verbatim."], + "dimensions": {"correctness": score, "completeness": score, "relevance": score}, + } + ) + + +def _augment_reply(prompt: str) -> str: + match = re.search(r"```json\s*\n(.*?)```", prompt, re.S) + seeds = json.loads(match.group(1)) if match else [] + out = [] + for i, seed in enumerate(seeds): + query = str(seed.get("query", "")).rstrip("?") + out.append( + { + "query": f"Quick question {i}: {query.lower()}?", + "expected_answer": seed.get("expected_answer", ""), + } + ) + return json.dumps(out) + + +def respond(messages: list[dict[str, Any]]) -> str: + """Return the fake model's reply for one chat-completions request.""" + system = " ".join(str(m.get("content", "")) for m in messages if m.get("role") == "system") + user = str(messages[-1].get("content", "")) if messages else "" + text = f"{system}\n{user}" + if "Policy snippets:" in user: + return _agent_reply(system, user) + if "You are an expert evaluation judge" in text: + return _judge_reply(text) + if "dataset augmentation expert" in text: + return _augment_reply(text) + if "system prompt" in text.lower() and ("improv" in text.lower() or "rewrite" in text.lower()): + return f"Here is the improved prompt.\n---\n{IMPROVED_PROMPT}" + if "json" in text.lower(): + return json.dumps({"score": 0.5, "reasoning": "fake"}) + return "OK" + + +def _build_app(server: FakeOpenAIServer) -> FastAPI: + app = FastAPI() + + @app.get("/v1/models") + async def models() -> dict[str, Any]: + return {"data": [{"id": "fake-model", "object": "model"}]} + + @app.post("/v1/chat/completions") + async def completions(request: Request) -> dict[str, Any]: + body = await request.json() + server.requests.append(body) + content = respond(body.get("messages") or []) + return { + "id": "chatcmpl-fake", + "object": "chat.completion", + "created": int(time.time()), + "model": body.get("model", "fake-model"), + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": content}, + "finish_reason": "stop", + } + ], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + } + + return app + + +class FakeOpenAIServer: + """Run the fake model server on a free local port in a background thread. + + Usage:: + + with FakeOpenAIServer() as server: + base_url = server.base_url # "http://127.0.0.1:/v1" + """ + + def __init__(self) -> None: + self.requests: list[dict[str, Any]] = [] + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + self.port = sock.getsockname()[1] + self.base_url = f"http://127.0.0.1:{self.port}/v1" + self._server: Any = None + self._thread: threading.Thread | None = None + + def roles(self) -> dict[str, int]: + """Count recorded requests per role (agent / judge / rewrite / augment).""" + counts = {"agent": 0, "judge": 0, "rewrite": 0, "augment": 0, "other": 0} + for body in self.requests: + reply = respond(body.get("messages") or []) + text = json.dumps(body.get("messages") or []) + if "Policy snippets:" in text: + counts["agent"] += 1 + elif "expert evaluation judge" in text: + counts["judge"] += 1 + elif "dataset augmentation expert" in text: + counts["augment"] += 1 + elif reply.endswith(IMPROVED_PROMPT): + counts["rewrite"] += 1 + else: + counts["other"] += 1 + return counts + + def __enter__(self) -> FakeOpenAIServer: + import uvicorn + + config = uvicorn.Config( + _build_app(self), host="127.0.0.1", port=self.port, log_level="warning" + ) + self._server = uvicorn.Server(config) + self._thread = threading.Thread(target=self._server.run, daemon=True) + self._thread.start() + deadline = time.monotonic() + 10 + while not self._server.started: + if time.monotonic() > deadline: + raise RuntimeError("fake OpenAI server did not start") + time.sleep(0.02) + return self + + def __exit__(self, *exc: object) -> None: + if self._server is not None: + self._server.should_exit = True + if self._thread is not None: + self._thread.join(timeout=5) diff --git a/tests/test_metric_protocol_bridge.py b/tests/test_metric_protocol_bridge.py new file mode 100644 index 00000000..0ded9ef6 --- /dev/null +++ b/tests/test_metric_protocol_bridge.py @@ -0,0 +1,221 @@ +# pyright: reportMissingParameterType=none +"""Every metric must work in every slot, whichever protocol it implements. + +Two metric protocols coexist: + +* ``agentomatic.agents`` — sync ``score(example, prediction) -> float`` + (``compile(metrics=...)``, ``evaluate``, ``agents.WeightedMetric``, + ``MetricLoss``); +* ``agentomatic.optimize`` — async ``evaluate(query, response, expected, + context) -> EvalResult`` (``PromptFitter``, ``CompositeMetric``). + +Handing ``PromptFitterBridge(metric=OptimizeMetricAdapter(judge))`` to fit +crashed mid-run with ``'OptimizeMetricAdapter' object has no attribute +'evaluate'`` — logged as a warning, so training silently continued without +optimizing. These tests pin the bridge in both directions. +""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from agentomatic.agents import ( + AgentExample, + CallableMetric, + ContainsTermsMetric, + MetricLoss, + OptimizeMetricAdapter, + PromptFitterBridge, + as_agent_metric, + resolve_loss, +) +from agentomatic.agents import WeightedMetric as AgentWeightedMetric +from agentomatic.optimize import ( + BaseMetric, + CompositeMetric, + ExactMatchMetric, + ScoreMetricAdapter, + as_optimize_metric, + resolve_metrics, +) +from agentomatic.optimize.metrics import EvalResult, WeightedMetric, scoring_run +from agentomatic.optimize.runner import RunResult + + +class _StubJudge(BaseMetric): + """Optimize metric returning a fixed score (or failing on demand).""" + + name = "stub_judge" + + def __init__(self, score: float = 0.8, *, fail: bool = False) -> None: + self._score = score + self._fail = fail + self.calls: list[tuple[str, str, str | None]] = [] + + async def evaluate(self, query, response, expected=None, context=None) -> EvalResult: + self.calls.append((query, response, expected)) + if self._fail: + raise ConnectionError("judge unreachable") + return EvalResult(metric_name=self.name, score=self._score, reason="stub") + + +def _example(**metadata: Any) -> AgentExample: + return AgentExample( + id="ex1", + input={"current_query": "What is the refund window?"}, + expected_output={"response": "30 days"}, + metadata=metadata, + ) + + +class TestOptimizeMetricAdapter: + def test_speaks_both_protocols(self) -> None: + adapter = OptimizeMetricAdapter(_StubJudge(0.7), name="judge") + assert adapter.score(_example(), {"response": "30 days"}) == pytest.approx(0.7) + result = asyncio.run(adapter.evaluate("q", "r", "e")) + assert result.score == pytest.approx(0.7) + + def test_failures_score_zero_and_are_counted_not_faked(self) -> None: + adapter = OptimizeMetricAdapter(_StubJudge(fail=True), name="judge") + assert adapter.score(_example(), {"response": "x"}) == 0.0 + assert adapter.failures == 1 + + def test_rejects_a_non_optimize_metric_with_guidance(self) -> None: + with pytest.raises(TypeError, match="score\\(example, prediction\\)"): + OptimizeMetricAdapter(ContainsTermsMetric(["x"])) + + def test_unwrapped_for_the_fitter(self) -> None: + judge = _StubJudge() + assert as_optimize_metric(OptimizeMetricAdapter(judge)) is judge + + +class TestPromptFitterBridgeMetric: + def test_accepts_the_adapter_from_the_user_script(self) -> None: + judge = _StubJudge() + bridge = PromptFitterBridge(metric=OptimizeMetricAdapter(judge, name="judge")) + assert bridge.metric is judge + + def test_wraps_class_agent_metrics(self) -> None: + bridge = PromptFitterBridge(metric=ContainsTermsMetric(["30 days"])) + assert isinstance(bridge.metric, ScoreMetricAdapter) + + def test_fails_fast_on_an_unusable_metric(self) -> None: + with pytest.raises(TypeError, match="not a usable metric"): + PromptFitterBridge(metric=object()) + + +class TestScoreMetricAdapter: + def test_class_agent_metric_scores_through_evaluate(self) -> None: + adapter = as_optimize_metric(ContainsTermsMetric(["30 days"])) + result = asyncio.run(adapter.evaluate("q", "Refunds within 30 days.", "30 days")) + assert result.score == 1.0 + + def test_rebuilds_expected_output_from_a_rich_reference(self) -> None: + seen: dict[str, Any] = {} + + def fn(example: AgentExample, prediction: dict[str, Any]) -> float: + seen["expected"] = example.expected_output + return 1.0 + + reference = _example().to_datapoint().expected_answer + asyncio.run(as_optimize_metric(CallableMetric("c", fn)).evaluate("q", "r", reference)) + assert seen["expected"] == {"response": "30 days"} + + def test_sees_example_metadata_and_structured_output_inside_the_fitter(self) -> None: + seen: dict[str, Any] = {} + + def fn(example: AgentExample, prediction: dict[str, Any]) -> float: + seen["metadata"] = example.metadata + seen["prediction"] = prediction + return 0.5 + + run = RunResult( + query="q", + response="30 days", + metadata={ + "example": {"must_include": ["30 days"]}, + "output": {"response": "30 days", "sources": ["kb"]}, + }, + ) + adapter = as_optimize_metric(CallableMetric("c", fn)) + + async def score() -> EvalResult: + with scoring_run(run): + return await adapter.evaluate("q", "30 days", "30 days") + + assert asyncio.run(score()).score == 0.5 + assert seen["metadata"] == {"must_include": ["30 days"]} + assert seen["prediction"] == {"response": "30 days", "sources": ["kb"]} + + +class TestCompositionAcceptsEitherProtocol: + def test_composite_metric_with_a_class_agent_component(self) -> None: + composite = CompositeMetric( + [ + WeightedMetric(name="judge", metric=_StubJudge(1.0), weight=1), + WeightedMetric(name="terms", metric=ContainsTermsMetric(["30 days"]), weight=1), + ] + ) + result = asyncio.run(composite.evaluate("q", "within 30 days", "30 days")) + assert result.metadata["dimensions"] == {"judge": 1.0, "terms": 1.0} + assert result.score == pytest.approx(1.0) + + def test_agents_weighted_metric_with_an_optimize_component(self) -> None: + weighted = AgentWeightedMetric( + [("judge", _StubJudge(0.4), 1), ("em", ExactMatchMetric(), 1)] + ) + score = weighted.score(_example(), {"response": "30 days"}) + assert weighted.last_component_scores["judge"] == pytest.approx(0.4) + assert weighted.last_component_scores["em"] == pytest.approx(1.0) + assert score == pytest.approx(0.7) + + def test_metric_loss_and_resolve_loss_accept_optimize_metrics(self) -> None: + loss = MetricLoss(_StubJudge(0.75)) + assert loss.compute(_example(), {"response": "x"}) == pytest.approx(0.25) + assert resolve_loss(_StubJudge(0.75)) is not None + + def test_resolve_metrics_accepts_instances_of_both_protocols(self) -> None: + resolved = resolve_metrics(["exact_match", ContainsTermsMetric(["a"]), _StubJudge()]) + assert all(callable(getattr(m, "evaluate", None)) for m in resolved) + + def test_compile_and_evaluate_accept_optimize_metrics(self) -> None: + from dataclasses import dataclass + + from agentomatic.agents import AgentDataset, BaseGraphAgent + + @dataclass + class S: + q: str = "" + out: str = "" + + class Echo(BaseGraphAgent[S]): + agent_name = "echo" + + def build_graph(self) -> Any: + g = self.new_graph() + g.add_node("n", self.n) + g.set_entry_point("n") + g.set_finish_point("n") + return g.compile() + + def n(self, s: S) -> S: + s.out = "30 days" + return s + + def input_to_state(self, d: dict[str, Any]) -> S: + return S(q=d.get("current_query", "")) + + def state_to_output(self, s: S) -> dict[str, Any]: + return {"response": s.out} + + agent = Echo() + agent.compile(AgentDataset(examples=[_example()]), metrics=[ExactMatchMetric()]) + report = agent.evaluate([_example()]) + assert report.scores["exact_match"] == pytest.approx(1.0) + + def test_as_agent_metric_rejects_unusable_objects(self) -> None: + with pytest.raises(TypeError, match="not a usable metric"): + as_agent_metric(42) diff --git a/tests/test_optimization_bugs.py b/tests/test_optimization_bugs.py index 0e0ff116..a6a32e45 100644 --- a/tests/test_optimization_bugs.py +++ b/tests/test_optimization_bugs.py @@ -748,7 +748,9 @@ async def evaluate(self, query, response, expected=None, context=None): # -- error handling ------------------------------------------------------- - def test_score_returns_neutral_on_exception(self): + def test_score_is_zero_and_counted_on_exception(self): + """A failed judge must not invent a mid-scale score (it hid outages).""" + class FailMetric: name = "fail" @@ -758,9 +760,10 @@ async def evaluate(self, *a, **kw): adapter = OptimizeMetricAdapter(FailMetric()) ex = self._make_example() result = adapter.score(ex, {"response": "r"}) - assert result == pytest.approx(0.5) # neutral, not 0.0 crash + assert result == 0.0 # no crash, and no fabricated 0.5 + assert adapter.failures == 1 - def test_score_returns_neutral_on_sync_exception(self): + def test_score_is_zero_and_counted_on_sync_exception(self): class SyncFail: name = "sync_fail" @@ -770,7 +773,8 @@ def evaluate(self, *a, **kw): adapter = OptimizeMetricAdapter(SyncFail()) ex = self._make_example() result = adapter.score(ex, {"response": "r"}) - assert result == pytest.approx(0.5) + assert result == 0.0 + assert adapter.failures == 1 # -- integration with training stack ------------------------------------- diff --git a/tests/test_optimize_cli_search_space.py b/tests/test_optimize_cli_search_space.py index 93111470..2fb57bd2 100644 --- a/tests/test_optimize_cli_search_space.py +++ b/tests/test_optimize_cli_search_space.py @@ -204,7 +204,7 @@ def test_bad_entry_raises(self) -> None: WeightedMetric([(1, 2, 3, 4)]) def test_component_missing_score_raises(self) -> None: - with pytest.raises(TypeError, match="Metric.score protocol"): + with pytest.raises(TypeError, match="not a usable metric"): WeightedMetric([("bad", object(), 1.0)]) def test_bare_metric_defaults_to_weight_one(self) -> None: From a39b603b8dd1f180dd1eae6ddba192ee894033cb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 19:04:58 +0000 Subject: [PATCH 03/16] feat(optimize): an anti-overfitting mechanism for prompt optimization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prompt optimization could accept prompts that only fit the data they were selected on. It now separates data roles and gates acceptance: - The optimizer learns from TRAIN only: failure clustering, judge feedback, few-shot demos and expected-tips come from a train reflection sample (`reflect_on="train"`, `reflection_size`), never from the validation examples candidates are selected on (their gold answers used to be pasted into the rewrite briefing). A holdout carved from train leaves the pool. - Candidates are SELECTED on validation, and only with a paired-bootstrap confidence that they beat the incumbent (`min_confidence=0.8`) — judge noise no longer passes as an improvement. - A held-out slice can only VETO, measured against the incumbent: no regression (`holdout_tolerance`), no widened validation/held-out gap (`max_generalization_gap`), and a validation gain must transfer (`min_transfer_ratio=0.25`) — the signature of memorised answers. - `test` is never passed to the fitter; an optional `split="holdout"` is the gate (else a slice of validation). AgentDataset gains `.holdout` and warns about unknown split labels. - Failed points (agent errors, judge failures) count as 0.0 instead of being dropped, so a candidate that breaks on hard inputs cannot win. - `max_trials` is a budget of distinct candidates (duplicates of an already scored config are skipped); rounds round up; promotion compares against the incumbent on the same minibatch; ROUND_END fires on every round and a stop requested in one fit no longer ends the next. - Every trial records its prompt, decision and reason. - Rewrites are no longer corrupted: text replies keep fenced blocks (only the first fence used to be returned) and `extract_prompt_text` splits on a `---` line only. - Concurrent candidate evaluation no longer swaps shared agent attributes for BaseGraphAgent (the race leaked prompts/temperature). - PromptFitterBridge selects on the compiled loss/metric by default, keeps every epoch's result (`agent._fit_results`), applies a config only when it improved, bakes few-shot demos into the served prompt, and routes judge calls to `llm_base_url` from construction (the epoch-0 baseline hit the default endpoint). The expected-tips candidate no longer injects another project's domain text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- src/agentomatic/agents/optimizers.py | 148 ++++-- src/agentomatic/agents/types.py | 33 +- src/agentomatic/optimize/briefing.py | 35 +- src/agentomatic/optimize/callbacks.py | 6 + src/agentomatic/optimize/fitter.py | 441 ++++++++++++++---- src/agentomatic/optimize/fitter_optimizers.py | 60 ++- src/agentomatic/optimize/learning.py | 196 ++++++-- src/agentomatic/optimize/llm_caller.py | 19 +- src/agentomatic/optimize/train_api.py | 4 +- tests/test_all_methods_extensive.py | 6 +- tests/test_eval_blackout.py | 3 +- tests/test_fit_anti_overfitting.py | 307 ++++++++++++ tests/test_fitter.py | 11 +- tests/test_train_pipeline_fixes.py | 8 +- 14 files changed, 1053 insertions(+), 224 deletions(-) create mode 100644 tests/test_fit_anti_overfitting.py diff --git a/src/agentomatic/agents/optimizers.py b/src/agentomatic/agents/optimizers.py index 77e39149..dda73f77 100644 --- a/src/agentomatic/agents/optimizers.py +++ b/src/agentomatic/agents/optimizers.py @@ -175,6 +175,10 @@ def _apply_config(agent: Any, config: dict[str, Any]) -> None: # --------------------------------------------------------------------------- +#: Section header PromptFitter uses when baking demonstrations into a prompt. +_FEW_SHOT_HEADER = "## Few-shot examples" + + class PromptFitterBridge: """Bridge that runs the ``optimize.PromptFitter`` engine from ``fit()``. @@ -275,6 +279,13 @@ def __init__( self.llm_base_url = llm_base_url self.llm_api_key = llm_api_key self.kwargs = kwargs + if llm_base_url or llm_api_key: + # fit() scores the epoch-0 baseline (judges included) before any + # PromptFitter exists; route those calls to the same endpoint now + # instead of the OMLX_BASE_URL / default fallback. + from agentomatic.optimize.llm_caller import LLMCaller + + LLMCaller.configure(base_url=llm_base_url, api_key=llm_api_key) def optimize( self, @@ -310,26 +321,41 @@ def _skip(reason: str) -> dict[str, Any]: if not len(opt_dataset): return _skip("empty dataset") - trainset, valset, testset = self._split_three(opt_dataset) - metric = self._resolve_metric() + trainset, valset, gateset = self._split_three(opt_dataset) + metric = self._resolve_metric(agent, metrics) if metric is None: return _skip("no usable metric") + n_test = sum( + 1 + for p in getattr(opt_dataset, "points", []) + if (getattr(p, "metadata", None) or {}).get("split") == "test" + ) logger.info( - "PromptFitterBridge: train={} (proposals) · validation={} (selection) · " - "test={} (held out — generalization gate only)", + "PromptFitterBridge: train={} (optimizer learns from) · validation={} " + "(candidates selected on) · holdout={} (veto-only gate) · test={} " + "(never used — evaluate it after fit)", len(trainset), len(valset), - len(testset) if testset is not None else "auto-reserved from validation", + len(gateset) if gateset is not None else "auto-reserved from validation", + n_test, ) try: - result = self._run_async(fitter.fit(trainset, valset, metric, testset=testset)) + result = self._run_async(fitter.fit(trainset, valset, metric, testset=gateset)) except RuntimeError as exc: return _skip(f"cannot run fitter here ({exc})") except Exception as exc: # noqa: BLE001 return _skip(f"fit failed ({exc})") agent._last_fit_result = result # noqa: SLF001 - intentional handoff + # Every epoch's result, so reports show the ORIGINAL prompt → final + # prompt across epochs (the last result alone starts from the prompt + # an earlier epoch already improved). + history = getattr(agent, "_fit_results", None) + if not isinstance(history, list): + history = [] + agent._fit_results = history # noqa: SLF001 + history.append(result) agent._last_optimize_status = "ok" # noqa: SLF001 logger.info(f"PromptFitterBridge: fit complete for '{name}'") return self._extract_config(agent, result) @@ -427,7 +453,9 @@ def _build_fitter(self, agent: Any, name: str) -> Any: } # Same compounding for few-shot examples accepted by an earlier epoch. baseline_few_shot: list[dict[str, Any]] = [] - if isinstance(compiled_cfg, dict): + if isinstance(compiled_cfg, dict) and _FEW_SHOT_HEADER not in (baseline_prompt or ""): + # (A prompt that already has its demonstrations baked in — see + # ``_extract_config`` — must not get them appended a second time.) raw_few_shot = compiled_cfg.get("few_shot_examples") or [] if isinstance(raw_few_shot, list): baseline_few_shot = [fs for fs in raw_few_shot if isinstance(fs, dict)] @@ -446,34 +474,61 @@ def _build_fitter(self, agent: Any, name: str) -> Any: **kwargs, ) - def _resolve_metric(self) -> Any | None: - """Return the fit objective metric (default: ExactMatch).""" + def _resolve_metric(self, agent: Any = None, metrics: Sequence[Any] = ()) -> Any | None: + """Return the metric candidates are selected on. + + Order: the bridge's ``metric=``; else the metric behind the compiled + ``loss`` (what ``fit()`` reports as ``loss``/``val_loss``); else the + first compiled metric; else ``ExactMatchMetric``. Selecting on the + same objective that is reported keeps "the optimizer improved it" + and "the loss went down" the same statement. + """ if self.metric is not None: return self.metric - try: - from agentomatic.optimize.metrics import ExactMatchMetric + from agentomatic.optimize.metrics import ExactMatchMetric, as_optimize_metric - return ExactMatchMetric() - except Exception: # noqa: BLE001 - return None + loss_metric = getattr(getattr(agent, "_loss", None), "metric", None) + for candidate, source in ( + (loss_metric, "compiled loss"), + (next(iter(metrics), None), "first compiled metric"), + ): + if candidate is None: + continue + try: + resolved = as_optimize_metric(candidate) + except TypeError: + continue + logger.info( + "PromptFitterBridge: selecting candidates on the {} ('{}')", + source, + getattr(candidate, "name", type(candidate).__name__), + ) + return resolved + logger.info("PromptFitterBridge: no metric given — selecting on ExactMatchMetric") + return ExactMatchMetric() @staticmethod def _split_three(opt_dataset: Any) -> tuple[Any, Any, Any | None]: - """Split into ``(train, validation, test)`` without leaking ``test``. + """Split into ``(train, validation, holdout)``; ``test`` is never used. - * ``train`` — failure analysis and few-shot demonstrations. + * ``train`` — what the optimizer learns from (failures, feedback, + few-shot demonstrations). * ``validation`` — the only data candidates are scored/selected on. - * ``test`` — handed to the fitter as its held-out ``testset``: it is - never used for selection, only for the generalization gate that - rejects an overfit candidate (and for the reported holdout score). + * ``holdout`` — optional ``split="holdout"`` examples: the unseen gate + that can only *veto* an overfit candidate. ``None`` lets the fitter + reserve a slice of validation instead. + * ``test`` — dropped here. A test set that gates or selects candidates + is no longer an unbiased estimate; evaluate it after ``fit()``. - The ``test`` split used to be folded into the validation pool, so the - "held-out" score was measured on data the winner had been picked on. + (The test split used to be folded into the selection pool, so the + "held-out" score was measured on data the winner had been picked on.) Without a ``validation`` split, validation is carved (20%) from - ``train``. Without a ``test`` split, ``None`` is returned and the - fitter reserves its own holdout slice from validation. + ``train`` after a seeded shuffle — never ``train == validation`` + unless only one example exists. """ + import random + from agentomatic.optimize.dataset import Dataset points = list(getattr(opt_dataset, "points", []) or []) @@ -483,22 +538,27 @@ def _split_of(point: Any) -> str: train = [p for p in points if _split_of(p) == "train"] val = [p for p in points if _split_of(p) in ("validation", "val")] - test = [p for p in points if _split_of(p) == "test"] - testset = Dataset(points=test) if test else None + hold = [p for p in points if _split_of(p) == "holdout"] + gate = Dataset(points=hold) if hold else None + if not train and not val: + # Nothing labelled for optimization (e.g. only ``test``): fall back + # to an unlabelled 80/20 cut of what is not test. + train = [p for p in points if _split_of(p) not in ("test", "holdout")] if train and not val and len(train) >= 2: - cut = max(1, int(round(len(train) * 0.8))) - cut = min(cut, len(train) - 1) - train, val = train[:cut], train[cut:] - if train and val: - return Dataset(points=train), Dataset(points=val), testset + shuffled = list(train) + random.Random(0).shuffle(shuffled) + cut = min(max(1, int(round(len(shuffled) * 0.8))), len(shuffled) - 1) + train, val = shuffled[:cut], shuffled[cut:] if val and not train: - return Dataset(points=val), Dataset(points=val), testset - if test and not train and not val: - # Only a test split was labelled: nothing else to learn from. - train_ds, val_ds = PromptFitterBridge._split(Dataset(points=test)) - return train_ds, val_ds, None - train_ds, val_ds = PromptFitterBridge._split(opt_dataset) - return train_ds, val_ds, None + logger.warning( + "PromptFitterBridge: no train split — the optimizer will learn from the " + "validation examples it selects on (overfitting risk). Label some rows " + 'split="train".' + ) + train = list(val) + if not val: + val = list(train) + return Dataset(points=train), Dataset(points=val), gate @staticmethod def _split(opt_dataset: Any) -> tuple[Any, Any]: @@ -553,6 +613,11 @@ def _extract_config(cls, agent: Any, result: Any) -> dict[str, Any]: best = getattr(result, "best_config", None) if best is None: return {} + if getattr(result, "improved", True) is False: + # Nothing was accepted: applying the fitter's *baseline* would still + # change the agent (the baseline may have been resolved from + # prompts.json while the agent served its own default). + return {} raw = best.to_dict() if hasattr(best, "to_dict") else dict(getattr(best, "__dict__", {})) config: dict[str, Any] = {} for key in (*cls._APPLICABLE_KEYS, *cls._APPLICABLE_BLOCKS): @@ -572,6 +637,15 @@ def _extract_config(cls, agent: Any, result: Any) -> dict[str, Any]: if param_value is None: continue config[param_key] = param_value + if config.get("few_shot_examples") and config.get("system_prompt"): + # Candidates were *scored* with their demonstrations baked into + # the prompt; serve them the same way (resolve_system_prompt does + # not read ``few_shot_examples``), or the fitted score never shows + # up in production. + from agentomatic.optimize.fitter import PromptFitter + + if _FEW_SHOT_HEADER not in config["system_prompt"]: + config["system_prompt"] = PromptFitter._prompt_with_few_shot(best) # noqa: SLF001 return config @staticmethod diff --git a/src/agentomatic/agents/types.py b/src/agentomatic/agents/types.py index 72e7e994..f8047d30 100644 --- a/src/agentomatic/agents/types.py +++ b/src/agentomatic/agents/types.py @@ -339,7 +339,17 @@ def to_datapoint(self) -> Any: @dataclass class AgentDataset: - """Collection of agent examples with train/val/test splits. + """Collection of agent examples with train / validation / holdout / test splits. + + Split roles during prompt optimization: + + * ``train`` — what the optimizer learns from (failures, judge feedback, + few-shot demonstrations). + * ``validation`` (or ``val``) — what candidates are scored and selected on. + * ``holdout`` (optional) — the unseen gate that can only *veto* an overfit + candidate. Without it, a slice of validation is reserved automatically. + * ``test`` — never touched by optimization; evaluate it yourself after + ``fit()`` for an unbiased estimate. Example:: @@ -351,6 +361,22 @@ class AgentDataset: examples: list[AgentExample] = field(default_factory=list) metadata: dict[str, Any] = field(default_factory=dict) + #: Split labels the dataset understands; anything else belongs to no split. + KNOWN_SPLITS = frozenset({"train", "validation", "val", "holdout", "test"}) + + def __post_init__(self) -> None: + unknown = sorted({e.split for e in self.examples if e.split not in self.KNOWN_SPLITS}) + if unknown: + from loguru import logger + + logger.warning( + "AgentDataset '{}': split label(s) {} are not one of {} — those " + "examples belong to no split and are ignored by fit()/evaluate splits.", + self.name, + unknown, + sorted(self.KNOWN_SPLITS), + ) + # --- Properties for split access --- @property @@ -363,6 +389,11 @@ def validation(self) -> list[AgentExample]: """Return validation examples.""" return [e for e in self.examples if e.split in ("validation", "val")] + @property + def holdout(self) -> list[AgentExample]: + """Return held-out gate examples (``split="holdout"``).""" + return [e for e in self.examples if e.split == "holdout"] + @property def test(self) -> list[AgentExample]: """Return test examples.""" diff --git a/src/agentomatic/optimize/briefing.py b/src/agentomatic/optimize/briefing.py index 301ac971..b9456833 100644 --- a/src/agentomatic/optimize/briefing.py +++ b/src/agentomatic/optimize/briefing.py @@ -388,21 +388,38 @@ def build_full_optimization_briefing( return "\n\n".join(sections) +#: A line that is only ``---`` — the delimiter the rewrite instructions ask for. +_DELIMITER_LINE = re.compile(r"^[ \t]*-{3,}[ \t]*$", re.MULTILINE) +#: A trailing commentary block a model appends after the prompt. +_TRAILING_NOTES = re.compile( + r"\n\s*\n(?:\*\*)?(?:changes|notes?|explanation|rationale|what changed)(?:\*\*)?\s*:.*\Z", + re.S | re.I, +) + + def extract_prompt_text(raw: str, *, fallback: str = "") -> str: - """Pull the final system-prompt text out of a free-form LLM reply.""" + """Pull the final system-prompt text out of a free-form LLM reply. + + The rewrite instructions ask for reasoning, then the prompt after a line + containing only ``---``. Only such a *line* delimits: a prompt that uses + ``---`` inside a sentence (or as its own section rule, after the first + delimiter) is kept whole. A fenced block is unwrapped only when it is + labelled ``text`` / ``markdown`` / ``prompt`` or wraps the whole reply — + a ```json example *inside* the new prompt must survive. + """ new_prompt = (raw or "").strip() - if "---" in new_prompt: - new_prompt = new_prompt.split("---", 1)[-1].strip() if "" in new_prompt and "" in new_prompt: new_prompt = new_prompt.split("", 1)[-1].strip() - # Prefer fenced blocks when present - fence = re.search(r"```(?:text|markdown|prompt)?\s*\n(.*?)```", new_prompt, re.S | re.I) + delimiter = _DELIMITER_LINE.search(new_prompt) + if delimiter: + new_prompt = new_prompt[delimiter.end() :].strip() + fence = re.search(r"```(?:text|markdown|prompt)[ \t]*\n(.*?)```", new_prompt, re.S | re.I) if fence: new_prompt = fence.group(1).strip() - elif new_prompt.startswith("```"): - lines = new_prompt.split("\n") - end = -1 if lines[-1].strip() == "```" else len(lines) - new_prompt = "\n".join(lines[1:end]).strip() + elif new_prompt.startswith("```") and new_prompt.rstrip().endswith("```"): + lines = new_prompt.strip().split("\n") + new_prompt = "\n".join(lines[1:-1]).strip() + new_prompt = _TRAILING_NOTES.sub("", new_prompt).strip() # Drop common labels for prefix in ("Improved system prompt:", "New system prompt:", "System prompt:"): if new_prompt.lower().startswith(prefix.lower()): diff --git a/src/agentomatic/optimize/callbacks.py b/src/agentomatic/optimize/callbacks.py index 73c1413b..3ae4cff8 100644 --- a/src/agentomatic/optimize/callbacks.py +++ b/src/agentomatic/optimize/callbacks.py @@ -133,6 +133,12 @@ async def on_event(self, event: OptimizationEvent, data: EventData) -> None: best_score = getattr(data, "best_score", None) if name == "FIT_START": + # A callback instance may be reused across fits (the bridge builds + # a new PromptFitter every epoch): a stop requested in the last + # fit must not end the next one before it starts. + ctx.stop_requested = False + ctx.prompt_override = False + ctx.scores_history = [] ctx.agent_name = str(getattr(data, "agent", "") or "") ctx.experiment_id = str(getattr(data, "experiment_id", "") or "") ctx.total_iterations = int(getattr(data, "total_rounds", 0) or 0) diff --git a/src/agentomatic/optimize/fitter.py b/src/agentomatic/optimize/fitter.py index 0c17628c..9e35d9c2 100644 --- a/src/agentomatic/optimize/fitter.py +++ b/src/agentomatic/optimize/fitter.py @@ -149,20 +149,25 @@ def _wrap_local_agent(agent: Any) -> Any: async fn(query, *, prompt_override, context, invoke) -> str - The *prompt_override* is injected via two mechanisms so that agents - which read from state metadata honour it: - - 1. Temporarily set ``agent.system_prompt = prompt_override`` (if the - attribute exists) and restore the original value after the call. - 2. Include ``metadata.system_prompt_override`` in the input dict so - graph nodes that inspect metadata also receive the override. - - The output dict is serialised to JSON; plain string outputs are - returned as-is. + The *prompt_override* travels in the request (``system_prompt_override`` + at the top level and in ``metadata``), which + :meth:`~agentomatic.agents.base.BaseGraphAgent.resolve_system_prompt` + reads per run — so concurrent candidate evaluations on one instance never + see each other's prompt. Only objects that are *not* a ``BaseGraphAgent`` + additionally get ``agent.system_prompt`` / ``compiled_config`` swapped + for the call; that shared-state swap is serialised with a lock (it raced + under ``concurrency > 1`` and could leave a candidate prompt behind). + + A dict output is returned as-is (the runner derives the scored text and + keeps the structured output for metrics); other outputs as a string. """ import asyncio import inspect - import json as _json + + from agentomatic.agents.base import BaseGraphAgent + + swaps_attributes = not isinstance(agent, BaseGraphAgent) + swap_lock = asyncio.Lock() async def _callable( query: str, @@ -199,9 +204,23 @@ async def _callable( if "temperature" in model_params: input_data.setdefault("temperature", model_params["temperature"]) - # Temporarily override the agent's system_prompt attribute so that - # nodes which read self.system_prompt pick up the candidate prompt. - # Track whether we successfully mutated so we restore even when the + if not swaps_attributes: + if hasattr(agent, "atransform") and inspect.iscoroutinefunction(agent.atransform): + output = await agent.atransform(input_data) + else: + output = await asyncio.to_thread(agent.transform, input_data) + return output if isinstance(output, dict) else str(output or "") + + async with swap_lock: + return await _call_with_swapped_attributes(input_data, prompt_override, model_params) + + async def _call_with_swapped_attributes( + input_data: dict[str, Any], + prompt_override: str | None, + model_params: dict[str, Any] | None, + ) -> Any: + # Duck-typed agents may read ``self.system_prompt`` directly: swap it + # for the call. Track whether we mutated so we restore even when the # original value was ``None`` / empty (otherwise the override sticks). original_prompt: str | None = None prompt_overridden = False @@ -248,14 +267,7 @@ async def _callable( pass if isinstance(output, dict): - # Prefer structured output, else response field, else full dict - inner = output.get("output") - if isinstance(inner, dict) and inner: - return _json.dumps(inner, ensure_ascii=False) - response = output.get("response") - if response is not None: - return str(response) - return _json.dumps(output, ensure_ascii=False) + return output return str(output) if output is not None else "" return _callable @@ -342,6 +354,34 @@ class PromptFitter: Pass count when SLM auto-detect fires (default 3). llm_default_passes : int Pass count when LLM auto-detect fires (default 2). + max_generalization_gap : float + Largest part of a candidate's validation gain allowed *not* to show up + on the held-out slice (default ``0.15``; half the gain for large gains). + holdout_fraction : float + Share of the validation set reserved as the held-out gate when no + ``testset`` is passed to :meth:`fit` (default ``0.2``). + min_transfer_ratio : float + Share of a validation gain that must also appear on the held-out + slice (default ``0.25``). Rejects prompts fitted to the validation + examples. ``0`` disables the rule. + holdout_tolerance : float + Held-out regression tolerated as noise (default ``0.02``). + min_confidence : float + Paired-bootstrap confidence required that a candidate beats the + incumbent on validation (default ``0.8``). Rejects "improvements" that + are judge noise. ``0`` disables the test. + reflect_on : str + Data the optimizer *learns from* (failures, judge feedback, few-shot + demos): ``"train"`` (default — never the data candidates are selected + on) or ``"validation"`` (legacy; the proposer sees the selection set). + reflection_size : int + Train examples evaluated per incumbent for reflection (default 8). + + Anti-overfitting, in one place: proposals are built from **train**, + candidates are **selected** on validation (with a paired-confidence test), + and a **held-out** slice that neither step sees can only *veto* a + candidate (regression, missing transfer, widened gap). The ``test`` split + should never be passed here — keep it for your final ``agent.evaluate``. Examples -------- @@ -403,6 +443,11 @@ def __init__( baseline_few_shot_examples: list[dict[str, Any]] | None = None, max_generalization_gap: float = 0.15, holdout_fraction: float = 0.2, + min_transfer_ratio: float = 0.25, + holdout_tolerance: float = 0.02, + min_confidence: float = 0.8, + reflect_on: str = "train", + reflection_size: int = 8, drain_seconds: float = 1.5, sequential: bool | None = None, trace_store_path: str | None = None, @@ -439,6 +484,13 @@ def __init__( self.llm_default_passes = llm_default_passes self.max_generalization_gap = max_generalization_gap self.holdout_fraction = holdout_fraction + self.min_transfer_ratio = max(0.0, float(min_transfer_ratio)) + self.holdout_tolerance = abs(float(holdout_tolerance)) + self.min_confidence = min(1.0, max(0.0, float(min_confidence))) + if reflect_on not in ("train", "validation"): + raise ValueError("reflect_on must be 'train' or 'validation'") + self.reflect_on = reflect_on + self.reflection_size = max(1, int(reflection_size)) self.drain_seconds = drain_seconds # Optional pre-set baseline: overrides prompts.json on first step. # Used by PromptFitterBridge to compound improvements across epochs. @@ -483,6 +535,8 @@ def __init__( #: Set when an evaluation scored nothing at all, so the summary can say #: the reported score is not a measurement. self._eval_blackout: str = "" + #: Blackout message of the most recent ``_evaluate_config`` call only. + self._last_eval_blackout: str = "" self._reward_adapter = MetricRewardAdapter() # Fitter optimizer — lazy-imported to avoid circular deps @@ -642,6 +696,7 @@ async def fit( # ── Generalization safety net: always reserve a holdout ────── from agentomatic.optimize.learning import ( check_generalization, + paired_improvement_confidence, split_holdout, synthesize_epoch_learning, ) @@ -662,13 +717,16 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: # Tiny valsets: borrow holdout from train so generalization # safety stays always-on (never silently skip). if not hold_pts and len(trainset) >= 2: - _fit_train, hold_pts = split_holdout( + fit_train, hold_pts = split_holdout( list(trainset), fraction=self.holdout_fraction, min_size=1, ) fit_pts = list(valset) holdout_source = "trainset" + # The gate must stay unseen: the optimizer learns from train, + # so the carved examples leave the train pool. + trainset = Dataset.from_list(_as_dicts(fit_train)) if hold_pts: # Rebuild fit valset only when we carved holdout out of it. if holdout_source == "valset": @@ -700,9 +758,27 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: metric, ) logger.info("📊 Baseline score: {:.4f}", baseline_score) + # Only a blackout of the baseline invalidates the whole run; a single + # broken candidate must not flag a healthy fit (it used to stick). + baseline_blackout = self._last_eval_blackout + self._eval_blackout = baseline_blackout if baseline_dims: for dim, val in baseline_dims.items(): logger.debug(" {}: {:.4f}", dim, val) + best_point_scores = [float(d.get("avg_score", 0.0) or 0.0) for d in baseline_details] + + # ── Reflection data: what the optimizer LEARNS from ───────────── + # Failure analysis, judge feedback and few-shot demos are drawn from + # train, never from the validation examples candidates are selected + # on — a proposer that reads validation gold answers writes prompts + # that memorise them (validation ↑, unseen data flat). + reflect_set = self._reflection_set(trainset, fit_valset) + if reflect_set is fit_valset: + reflect_details = baseline_details + else: + _, _, reflect_details = await self._evaluate_config( + baseline_config, reflect_set, metric + ) saturation_warning = "" if baseline_score >= _SATURATION_SCORE: @@ -744,7 +820,7 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: # ── Step 3: Cluster failures ───────────────────────────────── logger.info("🔍 Step 3/10 — Clustering baseline failures") - failures = [d for d in baseline_details if d.get("avg_score", 1.0) < _FAILURE_THRESHOLD] + failures = [d for d in reflect_details if d.get("avg_score", 1.0) < _FAILURE_THRESHOLD] failure_clusters_raw: list[dict[str, Any]] = [] if failures: logger.info(" Found {} failures (score < {:.1f})", len(failures), _FAILURE_THRESHOLD) @@ -797,7 +873,11 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: best_holdout_score = baseline_holdout_score no_improvement_rounds = 0 - max_rounds = max(1, self.max_trials // _CANDIDATES_PER_ROUND) + max_rounds = max(1, -(-self.max_trials // _CANDIDATES_PER_ROUND)) + # ``max_trials`` is a budget of *distinct candidates evaluated*; + # duplicates of an already-scored config are skipped for free. + seen_configs = {self._config_fingerprint(baseline_config)} + evaluated_candidates = 0 logger.info( "🔄 Starting optimisation: {} rounds × {} candidates = {} max evals", max_rounds, @@ -844,7 +924,7 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: minibatch_size / max(len(val_points), 1), ) - eval_results = self._build_eval_results(baseline_details, metric) + eval_results = self._build_eval_results(reflect_details, metric) # Effective patience: never exceed max_rounds so early stopping can # still fire, but honour the configured ``self.patience`` (wired from @@ -863,7 +943,7 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: ) ) - def _record_round( + async def _record_round( *, round_idx: int, round_t0: float, @@ -871,7 +951,7 @@ def _record_round( accepted_name: str, n_candidates: int, ) -> None: - """Always append score + prompt history for Keras-style curves.""" + """Append score + prompt history and emit ``ROUND_END`` (every path).""" nonlocal eval_results round_elapsed = time.perf_counter() - round_t0 logger.info( @@ -907,8 +987,39 @@ def _record_round( len(epoch_learning.what_failed), "; ".join(epoch_learning.next_focus[:2]) or "n/a", ) + # Emitted on every path — skipped rounds used to end silently, so + # iteration-based callbacks (EarlyStopping, ModelCheckpoint) never + # saw them. + await self._callbacks.emit( + OptimizationEvent.ROUND_END, + EventData( + agent=self.agent, + experiment_id=experiment_id, + round_idx=round_idx, + total_rounds=max_rounds, + score=best_score, + best_score=best_score, + baseline_score=baseline_score, + elapsed_seconds=round_elapsed, + score_history=[rs.score for rs in score_history], + prompt=best_config.system_prompt, + ), + ) for round_idx in range(max_rounds): + if round_idx and self._callbacks.stop_requested(): + was_early_stopped = True + early_stop_reason = early_stop_reason or ( + f"callback stop_requested before round {round_idx + 1}" + ) + break + if evaluated_candidates >= self.max_trials: + logger.info( + " Trial budget used: {}/{} candidates evaluated", + evaluated_candidates, + self.max_trials, + ) + break round_t0 = time.perf_counter() round_num = round_idx + 1 logger.info("── Round {}/{} ──", round_num, max_rounds) @@ -983,7 +1094,7 @@ def _record_round( candidates = await self._optimizer.propose( current_config=best_config, eval_results=eval_results, - dataset_sample=train_points[:20], + dataset_sample=self._sample_points(train_points, 20, seed=round_idx), search_space=self._search_space, iteration=round_idx, context=opt_context, @@ -991,7 +1102,7 @@ def _record_round( except Exception as exc: logger.error(" Candidate proposal failed: {}", exc) no_improvement_rounds += 1 - _record_round( + await _record_round( round_idx=round_idx, round_t0=round_t0, round_improved=False, @@ -1011,10 +1122,39 @@ def _record_round( break continue + unique: list[PromptCandidate] = [] + for cand in candidates: + fingerprint = self._config_fingerprint(cand.config) + if fingerprint in seen_configs: + trials.append( + { + "round": round_num, + "name": cand.name, + "source": cand.source, + "phase": "skipped", + "score": None, + "system_prompt": getattr(cand.config, "system_prompt", "") or "", + "decision": "duplicate", + "reason": "Identical to a config already evaluated — not re-scored.", + } + ) + continue + seen_configs.add(fingerprint) + unique.append(cand) + if len(unique) < len(candidates): + logger.info( + " Skipped {} duplicate candidate(s) (same config as one already " + "scored — a failing rewrite model often re-proposes the current prompt)", + len(candidates) - len(unique), + ) + remaining_budget = max(0, self.max_trials - evaluated_candidates) + candidates = unique[:remaining_budget] + evaluated_candidates += len(candidates) + if not candidates: - logger.warning(" No candidates produced — skipping round") + logger.warning(" No new candidates produced — skipping round") no_improvement_rounds += 1 - _record_round( + await _record_round( round_idx=round_idx, round_t0=round_t0, round_improved=False, @@ -1036,6 +1176,7 @@ def _record_round( # ── Step 5: Score candidates on minibatch ──────────────── logger.info(" ⚡ Step 5 — Minibatch scoring ({} pts)", len(minibatch_dataset)) candidate_scores: list[tuple[PromptCandidate, float, dict[str, float]]] = [] + mini_trials: dict[int, dict[str, Any]] = {} for cand in candidates: try: @@ -1048,20 +1189,25 @@ def _record_round( cand.scores = dict(cand_dims) candidate_scores.append((cand, cand_score, cand_dims)) - trials.append( - { - "round": round_num, - "name": cand.name, - "source": cand.source, - "phase": "minibatch", - "score": cand_score, - "dimensions": dict(cand_dims), - "mutation_notes": cand.mutation_notes, - "critique": (cand.metadata or {}).get("critique", ""), - "resource_versions": len(self._resource_registry.history()), - "trace_count": len(self._trace_store), - } - ) + mini_trial = { + "round": round_num, + "name": cand.name, + "source": cand.source, + "phase": "minibatch", + "score": cand_score, + "dimensions": dict(cand_dims), + "system_prompt": getattr(cand.config, "system_prompt", "") or "", + "model_params": dict(getattr(cand.config, "model_params", {}) or {}), + "few_shot_count": len(getattr(cand.config, "few_shot_examples", []) or []), + "mutation_notes": cand.mutation_notes, + "critique": (cand.metadata or {}).get("critique", ""), + "resource_versions": len(self._resource_registry.history()), + "trace_count": len(self._trace_store), + "decision": "screened", + "reason": "", + } + trials.append(mini_trial) + mini_trials[id(cand)] = mini_trial await self._callbacks.emit( OptimizationEvent.CANDIDATE_EVALUATED, EventData( @@ -1091,7 +1237,7 @@ def _record_round( if not candidate_scores: logger.warning(" All candidates failed — skipping round") no_improvement_rounds += 1 - _record_round( + await _record_round( round_idx=round_idx, round_t0=round_t0, round_improved=False, @@ -1115,14 +1261,41 @@ def _record_round( key=lambda t: (t[1], -_candidate_source_rank(t[0].source or "")), reverse=True, ) + # Compare against the incumbent's score on the *same* minibatch + # (not its full-validation score — different examples). + mini_n = len(minibatch_dataset) + incumbent_mini = ( + sum(best_point_scores[:mini_n]) / mini_n + if mini_n and len(best_point_scores) >= mini_n + else best_score + ) promotable = [ - (cand, sc, dims) for cand, sc, dims in candidate_scores if sc > best_score + (cand, sc, dims) for cand, sc, dims in candidate_scores if sc > incumbent_mini ][:_TOP_K_CANDIDATES] + promoted_ids = {id(cand) for cand, _, _ in promotable} + for cand, sc, _ in candidate_scores: + trial = mini_trials.get(id(cand)) + if trial is None: + continue + if id(cand) in promoted_ids: + trial["decision"] = "promoted" + trial["reason"] = ( + f"Minibatch {sc:.4f} > incumbent {incumbent_mini:.4f} — " + "promoted to full validation." + ) + else: + trial["decision"] = "not_promoted" + trial["reason"] = ( + f"Minibatch {sc:.4f} ≤ incumbent {incumbent_mini:.4f} on the same examples." + ) if not promotable: - logger.info(" No candidates beat current best ({:.4f})", best_score) + logger.info( + " No candidates beat the incumbent on the minibatch ({:.4f})", + incumbent_mini, + ) no_improvement_rounds += 1 - _record_round( + await _record_round( round_idx=round_idx, round_t0=round_t0, round_improved=False, @@ -1184,24 +1357,36 @@ def _record_round( holdout_score=cand_holdout, max_gap=self.max_generalization_gap, min_holdout_improvement=0.0, - baseline_holdout=baseline_holdout_score, + baseline_holdout=best_holdout_score, + baseline_fit=best_score, + min_transfer_ratio=self.min_transfer_ratio, + holdout_tolerance=self.holdout_tolerance, ) - trials.append( - { - "round": round_num, - "name": cand.name, - "source": cand.source, - "phase": "full_val", - "score": full_score, - "holdout_score": cand_holdout, - "generalization": gen_check.to_dict(), - "dimensions": dict(full_dims), - "system_prompt": getattr(cand.config, "system_prompt", "") or "", - "prompt_preview": ( - (getattr(cand.config, "system_prompt", "") or "")[:240] - ), - } + cand_points = [float(d.get("avg_score", 0.0) or 0.0) for d in full_details] + confidence = paired_improvement_confidence( + cand_points, best_point_scores, seed=round_idx ) + full_trial: dict[str, Any] = { + "round": round_num, + "name": cand.name, + "source": cand.source, + "phase": "full_val", + "score": full_score, + "mini_score": mini_score, + "incumbent_score": best_score, + "holdout_score": cand_holdout, + "incumbent_holdout_score": best_holdout_score, + "confidence": round(confidence, 4), + "generalization": gen_check.to_dict(), + "dimensions": dict(full_dims), + "system_prompt": getattr(cand.config, "system_prompt", "") or "", + "prompt_preview": ( + (getattr(cand.config, "system_prompt", "") or "")[:240] + ), + "decision": "rejected", + "reason": "", + } + trials.append(full_trial) logger.info( " {} full-val: {:.4f} (minibatch was {:.4f})" + (f", holdout={cand_holdout:.4f}" if cand_holdout is not None else ""), @@ -1221,10 +1406,20 @@ def _record_round( composite_baseline=best_score, composite_candidate=full_score, ) + if accept and self.min_confidence > 0 and confidence < self.min_confidence: + accept = False + reason = ( + f"Not significant: P(candidate > incumbent) = {confidence:.2f} < " + f"{self.min_confidence:.2f} over {len(cand_points)} validation " + "example(s) — likely judge noise" + ) + logger.info(" 🎲 {}", reason) if accept and not gen_check.ok: accept = False reason = f"Generalization safety net: {gen_check.reason}" logger.warning(" 🛡️ {}", reason) + full_trial["decision"] = "accepted" if accept else "rejected" + full_trial["reason"] = reason if accept: logger.info( @@ -1263,7 +1458,14 @@ def _record_round( best_score = full_score best_dims = dict(full_dims) best_holdout_score = cand_holdout - eval_results = self._build_eval_results(full_details, metric) + best_point_scores = cand_points + if reflect_set is fit_valset: + reflect_details = full_details + else: + _, _, reflect_details = await self._evaluate_config( + cand.config, reflect_set, metric + ) + eval_results = self._build_eval_results(reflect_details, metric) round_improved = True accepted_name = cand.name # Keep APO beam / TPE observations in sync with accepts. @@ -1335,28 +1537,13 @@ def _record_round( else: no_improvement_rounds += 1 - _record_round( + await _record_round( round_idx=round_idx, round_t0=round_t0, round_improved=round_improved, accepted_name=accepted_name, n_candidates=len(candidates) if candidates else 0, ) - await self._callbacks.emit( - OptimizationEvent.ROUND_END, - EventData( - agent=self.agent, - experiment_id=experiment_id, - round_idx=round_idx, - total_rounds=max_rounds, - score=best_score, - best_score=best_score, - baseline_score=baseline_score, - elapsed_seconds=time.perf_counter() - round_t0, - score_history=[rs.score for rs in score_history], - prompt=best_config.system_prompt, - ), - ) if tracker is not None and tracker_exp_id is not None: try: @@ -1396,7 +1583,11 @@ def _record_round( ) break - if not round_improved and no_improvement_rounds >= effective_patience: + if ( + not round_improved + and no_improvement_rounds >= effective_patience + and round_idx < max_rounds - 1 + ): was_early_stopped = True early_stop_reason = ( f"no improvement for {effective_patience} round(s) " @@ -1423,7 +1614,7 @@ def _record_round( baseline_config, best_config, ) - blackout = getattr(self, "_eval_blackout", "") + blackout = self._eval_blackout = baseline_blackout if blackout: # Ahead of every other advisory: nothing else in this report means # anything if no datapoint was ever scored. @@ -1508,9 +1699,12 @@ def _record_round( early_stop_reason=early_stop_reason, dataset_sizes={ "train": len(trainset), + "reflection": len(reflect_set) if reflect_set is not fit_valset else 0, "fit_val": len(fit_valset), "holdout": len(holdout_set) if holdout_set is not None else 0, - "test": len(testset) if testset is not None else 0, + "test": ( + len(testset) if testset is not None and testset is not holdout_set else 0 + ), }, ) @@ -1714,6 +1908,8 @@ async def _evaluate_config( *eval_details* is a list of dicts with per-point results. """ points = [dp.to_dict() for dp in dataset] + # Per call: one broken candidate must not flag the rest of the run. + self._last_eval_blackout = self._eval_blackout = "" # Publish a versioned resource snapshot for this evaluation. resource_id: str | None = None @@ -1927,13 +2123,24 @@ async def _evaluate_config( else: cause = f"the metric scored none of {len(run_results)} response(s)" first_error = metric_errors[0] if metric_errors else "" - self._eval_blackout = ( + self._last_eval_blackout = ( f"No datapoint could be evaluated: {cause}. The score below is " "not a measurement." + (f" First error: {first_error[:200]}" if first_error else "") ) - logger.error("❌ {}", self._eval_blackout) - avg_score = sum(scores) / scored_count if scored_count else 0.0 + self._eval_blackout = self._last_eval_blackout + logger.error("❌ {}", self._last_eval_blackout) + failed_count = len(run_results) - scored_count + if run_results and 0 < failed_count < len(run_results): + logger.warning( + " {}/{} point(s) failed (agent error or metric failure) and count as 0.0", + failed_count, + len(run_results), + ) + # Failed points count as 0.0: averaging only the points that worked let + # a candidate that crashes the agent on hard inputs outscore one that + # answers them all (and the selection score disagreed with evaluate()). + avg_score = sum(scores) / len(run_results) if run_results else 0.0 per_dim: dict[str, float] = { dim: sum(vals) / len(vals) for dim, vals in dim_accumulators.items() if vals } @@ -1942,6 +2149,62 @@ async def _evaluate_config( return avg_score, per_dim, eval_details + def _reflection_set(self, trainset: Dataset, fit_valset: Dataset) -> Dataset: + """Return the data the optimizer reflects on (never the selection set). + + Args: + trainset: Training data (proposals may learn from it). + fit_valset: Validation data candidates are selected on. + + Returns: + A deterministic sample of ``trainset`` (``reflection_size``), or + ``fit_valset`` itself for ``reflect_on="validation"`` or when + there is no training data (with a warning). + """ + if self.reflect_on == "validation": + return fit_valset + points = list(trainset) + if not points: + logger.warning( + "⚠️ No training data: the optimizer will learn from the validation " + "set it is selected on — high overfitting risk. Add a train split." + ) + return fit_valset + sample = self._sample_points(points, self.reflection_size, seed=0) + return Dataset.from_list([p.to_dict() if hasattr(p, "to_dict") else p for p in sample]) + + @staticmethod + def _sample_points(points: list[Any], k: int, *, seed: int) -> list[Any]: + """Deterministic sample of up to ``k`` points drawn across the whole list. + + ``points[:k]`` only ever showed the optimizer the first rows — with an + augmented dataset, never the synthetic ones appended at the end. + """ + import random + + if len(points) <= k: + return list(points) + rng = random.Random(seed) + return [points[i] for i in sorted(rng.sample(range(len(points)), k))] + + @staticmethod + def _config_fingerprint(config: PromptRuntimeConfig) -> str: + """Stable identity of everything a candidate may change.""" + import hashlib + + payload = { + "system_prompt": (config.system_prompt or "").strip(), + "user_template": getattr(config, "user_template", "") or "", + "few_shot": getattr(config, "few_shot_examples", None) or [], + "model_params": getattr(config, "model_params", None) or {}, + "rag_params": getattr(config, "rag_params", None) or {}, + "tool_params": getattr(config, "tool_params", None) or {}, + "output_contract": getattr(config, "output_contract", None), + "model_choice": getattr(config, "model_choice", None), + } + raw = json.dumps(payload, sort_keys=True, default=str) + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + @staticmethod def _prompt_with_few_shot(config: PromptRuntimeConfig) -> str: """Merge ``system_prompt`` + few-shot examples into one override string.""" diff --git a/src/agentomatic/optimize/fitter_optimizers.py b/src/agentomatic/optimize/fitter_optimizers.py index a82f900f..1672e941 100644 --- a/src/agentomatic/optimize/fitter_optimizers.py +++ b/src/agentomatic/optimize/fitter_optimizers.py @@ -499,8 +499,16 @@ def _prompt_with_expected_tips( dataset_sample: list[dict[str, Any]], eval_results: list[dict[str, Any]], ) -> str: - """Append concrete grounding tips mined from expected answers.""" + """Append grounding tips distilled from the *training* labels. + + Only what the dataset author declared is used: ``must_include`` terms + (from the expected output or the example metadata) and the output keys + every labelled example shares. Arbitrary tokens from expected answers + are not mined — stuffing a prompt with them overfits the data it came + from. Both inputs are training data (the fitter reflects on train). + """ must_terms: list[str] = [] + key_sets: list[frozenset[str]] = [] for src in list(dataset_sample or []) + list(eval_results or []): expected = ( src.get("expected_answer") or src.get("expected") or src.get("expected_output") @@ -509,38 +517,42 @@ def _prompt_with_expected_tips( if isinstance(expected, dict): exp_dict = expected elif isinstance(expected, str) and "## Expected structured output" in expected: + blob = expected.split("## Expected structured output", 1)[1].split("\n## ", 1)[0] try: - exp_dict = json.loads(expected.split("## Expected structured output", 1)[1]) - except (json.JSONDecodeError, TypeError, IndexError): + parsed = json.loads(blob) + exp_dict = parsed if isinstance(parsed, dict) else {} + except (json.JSONDecodeError, TypeError): exp_dict = {} - for term in exp_dict.get("must_include") or []: + if exp_dict: + key_sets.append(frozenset(k for k in exp_dict if k != "must_include")) + meta = src.get("metadata") if isinstance(src.get("metadata"), dict) else {} + for term in list(exp_dict.get("must_include") or []) + list( + meta.get("must_include") or [] + ): t = str(term).strip() if t and t.lower() not in {x.lower() for x in must_terms}: must_terms.append(t) - for key in ("content", "next_action"): - val = exp_dict.get(key) - if isinstance(val, str) and val.strip(): - for tok in val.split(): - if len(tok) > 5 and tok.lower() not in {x.lower() for x in must_terms}: - must_terms.append(tok) - if len(must_terms) >= 12: - break - if len(must_terms) >= 12: - break - if not must_terms: + shared_keys = sorted(frozenset.intersection(*key_sets)) if key_sets else [] + if not must_terms and len(shared_keys) < 2: return system_prompt - tip = ( - "\n\n## Fit tips (from labelled demos)\n" - "- Ground every answer ONLY in the provided snapshot; never invent budgets " - "or stakeholders.\n" - "- Always return non-empty JSON keys `content` and `next_action`.\n" - "- Prefer concrete next actions (≥4 words) tied to unknowns/status.\n" - "- When relevant, include these anchors naturally: " + ", ".join(must_terms[:10]) + "." - ) + lines = [ + "", + "", + "## Fit tips (from labelled training examples)", + "- Ground every answer only in the provided input and context; never invent facts.", + ] + if len(shared_keys) >= 2: + lines.append("- Return every required field: " + ", ".join(shared_keys) + ".") + if must_terms: + lines.append( + "- When relevant, state these required facts explicitly: " + + ", ".join(must_terms[:10]) + + "." + ) base = (system_prompt or "").rstrip() if "## Fit tips" in base: return base - return base + tip + return base + "\n".join(lines) # ===================================================================== diff --git a/src/agentomatic/optimize/learning.py b/src/agentomatic/optimize/learning.py index 8a67ef11..fe906d4a 100644 --- a/src/agentomatic/optimize/learning.py +++ b/src/agentomatic/optimize/learning.py @@ -12,6 +12,7 @@ from __future__ import annotations +from collections.abc import Sequence from dataclasses import asdict, dataclass, field from typing import Any @@ -108,6 +109,12 @@ class GeneralizationCheck: holdout_score: float | None gap: float | None max_gap: float + #: Candidate − incumbent on the selection (validation) set. + fit_delta: float | None = None + #: Candidate − incumbent on the held-out set. + holdout_delta: float | None = None + #: How much the fit−holdout gap widened vs the incumbent. + gap_growth: float | None = None def to_dict(self) -> dict[str, Any]: """Serialize for trials / artefacts.""" @@ -121,22 +128,46 @@ def check_generalization( max_gap: float = 0.15, min_holdout_improvement: float = 0.0, baseline_holdout: float | None = None, + baseline_fit: float | None = None, + min_transfer_ratio: float = 0.0, + holdout_tolerance: float = 0.02, ) -> GeneralizationCheck: """Reject candidates that look overfit to the optimisation set. - Rules (always applied when a holdout score is available): - - 1. ``fit_score − holdout_score`` must not exceed *max_gap*. - 2. If *baseline_holdout* is given, holdout must not regress below - ``baseline_holdout − epsilon`` and should improve by at least - *min_holdout_improvement* when that threshold is > 0. + The held-out slice is never used to *pick* candidates — only to veto + them. Two modes: + + **Incumbent-relative** (``baseline_fit`` and ``baseline_holdout`` given — + what :class:`~agentomatic.optimize.PromptFitter` uses). Deltas are + measured against the current best config on the same two slices: + + 1. *Gap growth* — ``(fit − holdout) − (baseline_fit − baseline_holdout)``, + the part of the validation gain that does not replicate on held-out + data, must not exceed ``max_gap`` (or half the validation gain, for + large gains). A dataset whose baseline already scores differently on + the two slices is not penalised for that. + 2. *No held-out regression* — ``holdout − baseline_holdout`` must be + ``≥ −holdout_tolerance``. + 3. *Transfer* — when the candidate improves validation by ``Δfit > 0``, + held-out must improve by at least ``min_transfer_ratio × Δfit``. + A prompt that memorised validation answers improves validation only; + this is the rule that rejects it. Skipped when the held-out slice is + already saturated (``baseline_holdout ≥ 0.99``). + + **Absolute** (legacy — no ``baseline_fit``): ``fit − holdout ≤ max_gap``, + plus the regression rule when ``baseline_holdout`` is given. Args: - fit_score: Score on the set used for candidate selection (val). - holdout_score: Score on a held-out generalization slice / test. - max_gap: Maximum allowed ``fit − holdout`` gap. - min_holdout_improvement: Required holdout lift vs baseline. - baseline_holdout: Baseline holdout score for the same slice. + fit_score: Candidate score on the selection (validation) set. + holdout_score: Candidate score on the held-out slice. + max_gap: Maximum allowed gap (absolute mode) or gap growth. + min_holdout_improvement: Required held-out lift vs baseline. + baseline_holdout: Incumbent / baseline score on the held-out slice. + baseline_fit: Incumbent score on the selection set (enables the + incumbent-relative mode). + min_transfer_ratio: Share of the validation gain that must show up + on held-out data (``0`` disables the transfer rule). + holdout_tolerance: Held-out regression tolerated as noise. Returns: :class:`GeneralizationCheck` with accept/reject decision. @@ -152,58 +183,123 @@ def check_generalization( ) gap = fit_score - holdout_score - if gap > max_gap: + fit_delta = fit_score - baseline_fit if baseline_fit is not None else None + holdout_delta = holdout_score - baseline_holdout if baseline_holdout is not None else None + gap_growth = ( + gap - (baseline_fit - baseline_holdout) + if baseline_fit is not None and baseline_holdout is not None + else None + ) + + def _result(ok: bool, reason: str) -> GeneralizationCheck: return GeneralizationCheck( - ok=False, - reason=( - f"Overfit risk: fit={fit_score:.4f} vs holdout={holdout_score:.4f} " - f"(gap={gap:+.4f} > max_gap={max_gap:.4f})" - ), + ok=ok, + reason=reason, fit_score=fit_score, holdout_score=holdout_score, gap=gap, max_gap=max_gap, + fit_delta=fit_delta, + holdout_delta=holdout_delta, + gap_growth=gap_growth, ) - if baseline_holdout is not None: - holdout_delta = holdout_score - baseline_holdout - if holdout_delta < -0.02: - return GeneralizationCheck( - ok=False, - reason=( - f"Holdout regression: {holdout_score:.4f} < baseline " - f"{baseline_holdout:.4f} (Δ={holdout_delta:+.4f})" - ), - fit_score=fit_score, - holdout_score=holdout_score, - gap=gap, - max_gap=max_gap, + if gap_growth is not None: + # Large real gains leave some unreplicated noise on a small held-out + # slice; allow up to half the gain before calling it overfitting. + allowed = max(max_gap, 0.5 * fit_delta) if fit_delta and fit_delta > 0 else max_gap + if gap_growth > allowed: + return _result( + False, + f"Overfit risk: the validation/held-out gap widened by {gap_growth:+.4f} " + f"(> {allowed:.4f}); fit={fit_score:.4f}, holdout={holdout_score:.4f}", + ) + elif gap > max_gap: + return _result( + False, + f"Overfit risk: fit={fit_score:.4f} vs holdout={holdout_score:.4f} " + f"(gap={gap:+.4f} > max_gap={max_gap:.4f})", + ) + + if holdout_delta is not None and baseline_holdout is not None: + if holdout_delta < -abs(holdout_tolerance): + return _result( + False, + f"Holdout regression: {holdout_score:.4f} < baseline " + f"{baseline_holdout:.4f} (Δ={holdout_delta:+.4f}, " + f"tolerance {holdout_tolerance:.4f})", ) if min_holdout_improvement > 0 and holdout_delta < min_holdout_improvement: - return GeneralizationCheck( - ok=False, - reason=( - f"Holdout improvement {holdout_delta:+.4f} below " - f"min_holdout_improvement={min_holdout_improvement:.4f}" - ), - fit_score=fit_score, - holdout_score=holdout_score, - gap=gap, - max_gap=max_gap, + return _result( + False, + f"Holdout improvement {holdout_delta:+.4f} below " + f"min_holdout_improvement={min_holdout_improvement:.4f}", ) - - return GeneralizationCheck( - ok=True, - reason=( - f"Generalization OK: fit={fit_score:.4f}, holdout={holdout_score:.4f}, gap={gap:+.4f}" - ), - fit_score=fit_score, - holdout_score=holdout_score, - gap=gap, - max_gap=max_gap, + if ( + min_transfer_ratio > 0 + and fit_delta is not None + and fit_delta > 0 + and baseline_holdout < 0.99 + ): + required = min_transfer_ratio * fit_delta + if holdout_delta < required - 1e-9: + return _result( + False, + f"Does not transfer: validation improved {fit_delta:+.4f} but held-out " + f"only {holdout_delta:+.4f} (< {min_transfer_ratio:.0%} of the gain = " + f"{required:+.4f}) — likely fitted to the validation examples", + ) + + return _result( + True, + f"Generalization OK: fit={fit_score:.4f}, holdout={holdout_score:.4f}, gap={gap:+.4f}" + + (f", held-out Δ={holdout_delta:+.4f}" if holdout_delta is not None else ""), ) +def paired_improvement_confidence( + candidate: Sequence[float], + incumbent: Sequence[float], + *, + n_boot: int = 1000, + seed: int = 0, +) -> float: + """Bootstrap confidence that ``candidate`` beats ``incumbent`` on average. + + Both sequences are per-example scores on the *same* examples in the same + order. Resampling the paired differences estimates ``P(mean Δ > 0)`` — + a guard against accepting a candidate whose "improvement" is judge noise + on a handful of validation examples. + + Args: + candidate: Candidate per-example scores. + incumbent: Incumbent per-example scores (same examples, same order). + n_boot: Bootstrap resamples. + seed: RNG seed (deterministic decisions). + + Returns: + A probability in ``[0, 1]``; ``1.0`` when every paired difference is + positive, ``0.0`` when none is, ``0.5`` when the inputs are unusable. + """ + import random + + if not candidate or len(candidate) != len(incumbent): + return 0.5 + diffs = [float(c) - float(i) for c, i in zip(candidate, incumbent, strict=True)] + if all(d > 0 for d in diffs): + return 1.0 + if all(d <= 0 for d in diffs): + return 0.0 + rng = random.Random(seed) + n = len(diffs) + wins = 0 + for _ in range(max(1, n_boot)): + total = sum(diffs[rng.randrange(n)] for _ in range(n)) + if total > 0: + wins += 1 + return wins / max(1, n_boot) + + def synthesize_epoch_learning( *, round_idx: int, diff --git a/src/agentomatic/optimize/llm_caller.py b/src/agentomatic/optimize/llm_caller.py index c9486174..ebba2d22 100644 --- a/src/agentomatic/optimize/llm_caller.py +++ b/src/agentomatic/optimize/llm_caller.py @@ -446,10 +446,16 @@ async def _call_ollama( def _normalize_llm_text(text: str) -> str: - """Strip thinking / reasoning preambles before returning optimize text.""" - from agentomatic.providers.message_utils import strip_thinking_for_json + """Strip thinking / reasoning preambles before returning optimize text. - return strip_thinking_for_json(text or "").strip() + Only the reasoning is removed. Fenced blocks are kept: this used to return + the *first* fenced block, so a rewritten prompt that quoted the old prompt + in a fence (or contained a ```json example) was silently replaced by that + fragment. JSON callers extract their object in ``call_with_json``. + """ + from agentomatic.providers.message_utils import split_thinking_text + + return split_thinking_text(text or "").answer.strip() def _is_openai_compatible_local(base_url: str | None) -> bool: @@ -641,6 +647,13 @@ async def _call_openai( response = await asyncio.wait_for(c.chat.completions.create(**kwargs), timeout=timeout) choice = response.choices[0] + if getattr(choice, "finish_reason", None) == "length": + logger.warning( + "LLM reply from '{}' was cut off at max_tokens={} — the output is " + "truncated (raise max_tokens or ask for less per call).", + model_name, + max_tokens, + ) message = choice.message content = message.content or "" reasoning = getattr(message, "reasoning_content", None) or "" diff --git a/src/agentomatic/optimize/train_api.py b/src/agentomatic/optimize/train_api.py index 2517bfd4..9cbcc9e5 100644 --- a/src/agentomatic/optimize/train_api.py +++ b/src/agentomatic/optimize/train_api.py @@ -746,7 +746,9 @@ def compile_agent( patience=patience, concurrency=concurrency, sequential=sequential, - experiment_dir=str(experiment_dir) if experiment_dir else None, + # ``None`` reached PromptFitter as a path and every artefact + # (report, result JSON) failed to save. + experiment_dir=str(experiment_dir) if experiment_dir else ".optimize", auto_report=auto_report, drain_seconds=drain_seconds, ) diff --git a/tests/test_all_methods_extensive.py b/tests/test_all_methods_extensive.py index 226c355c..b022534c 100644 --- a/tests/test_all_methods_extensive.py +++ b/tests/test_all_methods_extensive.py @@ -756,7 +756,7 @@ def test_augment_local_judges_wraps_and_extends(self) -> None: assert any(wm.name == "local_judges" for wm in aug.metrics) @pytest.mark.asyncio - async def test_evaluate_config_skips_failed_and_averages(self, monkeypatch) -> None: + async def test_evaluate_config_counts_failed_points_as_zero(self, monkeypatch) -> None: a = _DemoAgent() f = PromptFitter( agent="demo", @@ -792,7 +792,9 @@ async def _eval(query, response, expected=None, context=None): ), metric, ) - assert avg == pytest.approx(1.0) + # A failed evaluation counts as 0.0 — averaging only the points that + # worked let a candidate that breaks the judge on hard inputs win. + assert avg == pytest.approx(0.5) assert any(d.get("error") for d in details) def test_param_suggestions_and_baseline_load(self, tmp_path: Path, monkeypatch) -> None: diff --git a/tests/test_eval_blackout.py b/tests/test_eval_blackout.py index 44269f53..39442c20 100644 --- a/tests/test_eval_blackout.py +++ b/tests/test_eval_blackout.py @@ -158,7 +158,8 @@ async def test_one_success_clears_it(self) -> None: ContainsMetric(), ) - assert score == 1.0 + # The failed point counts as 0.0; the average is still a measurement. + assert score == 0.5 assert not fitter._eval_blackout # noqa: SLF001 @pytest.mark.asyncio diff --git a/tests/test_fit_anti_overfitting.py b/tests/test_fit_anti_overfitting.py new file mode 100644 index 00000000..98a7598e --- /dev/null +++ b/tests/test_fit_anti_overfitting.py @@ -0,0 +1,307 @@ +# pyright: reportMissingParameterType=none +# pyright: reportAttributeAccessIssue=none +"""Prompt optimization must not reward prompts that overfit. + +The mechanism, end to end: + +* the optimizer **learns** from train only (failures, judge feedback, demos); +* candidates are **selected** on validation, and only when the gain is + unlikely to be noise (paired bootstrap confidence); +* a **held-out** slice neither step sees can only *veto* a candidate — for + regressing, for widening the validation/held-out gap, or for a validation + gain that does not transfer (the signature of memorised validation answers); +* the ``test`` split is never used by optimization at all. + +The simulated agent below answers correctly only for the queries its prompt +"knows": ``GENERAL`` knows everything, ``MEMO: `` only those listed — +the textbook overfit prompt. +""" + +from __future__ import annotations + +import dataclasses +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from agentomatic.optimize import ( + CustomMetric, + DataPoint, + Dataset, + PromptFitter, +) +from agentomatic.optimize.config import PromptCandidate, PromptRuntimeConfig +from agentomatic.optimize.events import OptimizationEvent +from agentomatic.optimize.learning import check_generalization, paired_improvement_confidence +from agentomatic.optimize.runner import AgentRunner + +TRAIN = [f"t{i}" for i in range(4)] +VAL = [f"v{i}" for i in range(4)] +HOLD = [f"h{i}" for i in range(3)] + + +def _ds(queries: list[str]) -> Dataset: + return Dataset(points=[DataPoint(query=q, expected_answer=f"ans-{q}") for q in queries]) + + +async def _agent(query: str, *, prompt_override=None, context=None, invoke=None) -> str: + prompt = prompt_override or "" + if "GENERAL" in prompt: + return f"ans-{query}" + if prompt.startswith("MEMO:") and query in prompt.split(): + return f"ans-{query}" + return "no idea" + + +def _metric() -> CustomMetric: + return CustomMetric(lambda q, r, e, c: 1.0 if r == e else 0.0, name="exact") + + +class _Proposer: + """Duck-typed optimizer that proposes fixed prompts and records what it saw.""" + + name = "scripted" + + def __init__(self, rounds: list[list[str]]) -> None: + self._rounds = rounds + self.seen_eval_queries: list[str] = [] + self.seen_sample_queries: list[str] = [] + + async def propose( + self, + current_config, + eval_results, + dataset_sample, + search_space, + iteration=0, + context=None, + ) -> list[PromptCandidate]: + self.seen_eval_queries += [str(r.get("query")) for r in eval_results] + self.seen_sample_queries += [str(p.get("query")) for p in dataset_sample] + prompts = self._rounds[iteration] if iteration < len(self._rounds) else [] + # Like the real optimizers: change the prompt, keep everything else. + return [ + PromptCandidate( + name=f"c{iteration}_{i}", + config=dataclasses.replace(current_config, system_prompt=text), + source="scripted", + ) + for i, text in enumerate(prompts) + ] + + +class _Events: + def __init__(self) -> None: + self.events: list[OptimizationEvent] = [] + + async def on_event(self, event, data) -> None: + self.events.append(event) + + +def _fitter(tmp_path, proposer: Any, **kwargs: Any) -> PromptFitter: + fitter = PromptFitter( + agent="sim", + optimizer=proposer, + baseline_system_prompt="You are a baseline assistant.", + experiment_dir=str(tmp_path), + auto_report=False, + drain_seconds=0, + **{"max_trials": 8, "patience": 3, **kwargs}, + ) + fitter._runner = AgentRunner(agent="sim", agent_callable=_agent) # noqa: SLF001 + fitter._failure_clusterer.cluster = AsyncMock(return_value=[]) # noqa: SLF001 + return fitter + + +def _decisions(result) -> dict[str, tuple[str, str]]: + return { + t["system_prompt"]: (t["decision"], t.get("reason", "")) + for t in result.trials + if t.get("phase") in ("full_val", "skipped") + } + + +class TestAcceptance: + async def test_memorised_validation_answers_are_rejected(self, tmp_path) -> None: + memo = "MEMO: " + " ".join(VAL) + fitter = _fitter(tmp_path, _Proposer([[memo]])) + result = await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + + decision, reason = _decisions(result)[memo] + assert decision == "rejected" + # Validation 0 → 1 while held-out stays 0: vetoed by the safety net. + assert "Generalization safety net" in reason + assert not result.improved + assert result.best_prompt == "You are a baseline assistant." + + async def test_a_generalizing_prompt_is_accepted(self, tmp_path) -> None: + fitter = _fitter(tmp_path, _Proposer([["GENERAL assistant"]])) + result = await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + + assert _decisions(result)["GENERAL assistant"][0] == "accepted" + assert result.improved + assert result.best_score == pytest.approx(1.0) + assert result.holdout_score == pytest.approx(1.0) + + async def test_the_generalizing_prompt_wins_over_the_memorising_one(self, tmp_path) -> None: + memo = "MEMO: " + " ".join(VAL) + fitter = _fitter(tmp_path, _Proposer([[memo, "GENERAL assistant"]])) + result = await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + assert result.best_prompt == "GENERAL assistant" + + async def test_duplicates_of_the_incumbent_are_not_rescored(self, tmp_path) -> None: + fitter = _fitter(tmp_path, _Proposer([["You are a baseline assistant."]])) + result = await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + assert _decisions(result)["You are a baseline assistant."][0] == "duplicate" + assert not any(t.get("phase") == "minibatch" for t in result.trials) + + +class TestProposerIsolation: + async def test_the_optimizer_learns_from_train_only(self, tmp_path) -> None: + proposer = _Proposer([["GENERAL assistant"], ["GENERAL assistant v2"]]) + fitter = _fitter(tmp_path, proposer) + await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + + seen = set(proposer.seen_eval_queries) | set(proposer.seen_sample_queries) + assert seen, "the proposer must receive reflection data" + assert seen <= set(TRAIN), f"validation/holdout leaked to the proposer: {seen}" + + async def test_legacy_reflection_on_validation_is_opt_in(self, tmp_path) -> None: + proposer = _Proposer([["GENERAL assistant"]]) + fitter = _fitter(tmp_path, proposer, reflect_on="validation") + await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + assert set(proposer.seen_eval_queries) <= set(VAL) + + +class TestBudgetAndEvents: + async def test_max_trials_caps_distinct_candidates(self, tmp_path) -> None: + many = [[f"cand {i}" for i in range(10)] for _ in range(5)] + fitter = _fitter(tmp_path, _Proposer(many), max_trials=3) + result = await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + assert sum(1 for t in result.trials if t.get("phase") == "minibatch") == 3 + + async def test_round_end_is_emitted_for_rounds_without_candidates(self, tmp_path) -> None: + events = _Events() + fitter = _fitter(tmp_path, _Proposer([[], []]), max_trials=8, callbacks=[events]) + await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + starts = events.events.count(OptimizationEvent.ROUND_START) + assert starts >= 1 + assert events.events.count(OptimizationEvent.ROUND_END) == starts + + async def test_every_scored_candidate_records_its_prompt_and_decision(self, tmp_path) -> None: + fitter = _fitter(tmp_path, _Proposer([["no help", "GENERAL assistant"]])) + result = await fitter.fit(_ds(TRAIN), _ds(VAL), _metric(), testset=_ds(HOLD)) + mini = [t for t in result.trials if t["phase"] == "minibatch"] + assert {t["system_prompt"] for t in mini} == {"no help", "GENERAL assistant"} + assert all(t["decision"] in {"promoted", "not_promoted"} and t["reason"] for t in mini) + + +class TestGeneralizationRules: + def test_memorisation_does_not_transfer(self) -> None: + check = check_generalization( + fit_score=0.19, + holdout_score=0.085, + baseline_fit=0.085, + baseline_holdout=0.085, + min_transfer_ratio=0.25, + ) + assert not check.ok and "Does not transfer" in check.reason + + def test_a_large_real_gain_is_accepted(self) -> None: + check = check_generalization( + fit_score=0.8, + holdout_score=0.7, + baseline_fit=0.1, + baseline_holdout=0.2, + min_transfer_ratio=0.25, + ) + assert check.ok + + def test_held_out_regression_is_rejected(self) -> None: + check = check_generalization( + fit_score=0.9, + holdout_score=0.4, + baseline_fit=0.6, + baseline_holdout=0.5, + min_transfer_ratio=0.0, + ) + assert not check.ok + + def test_legacy_absolute_gap(self) -> None: + assert not check_generalization(fit_score=0.9, holdout_score=0.5, max_gap=0.15).ok + assert check_generalization(fit_score=0.6, holdout_score=0.5, max_gap=0.15).ok + + def test_paired_confidence(self) -> None: + assert paired_improvement_confidence([1, 1, 1], [0, 0, 0]) == 1.0 + assert paired_improvement_confidence([0.5, 0.6], [0.5, 0.6]) == 0.0 + noisy = paired_improvement_confidence([0.9, 0.1, 0.8, 0.2], [0.5, 0.5, 0.5, 0.5]) + assert 0.0 < noisy < 0.8 + + +class TestBridgeDataRoles: + @staticmethod + def _points(**splits: int) -> Dataset: + points = [] + for split, n in splits.items(): + points += [ + DataPoint(query=f"{split}{i}", expected_answer="x", metadata={"split": split}) + for i in range(n) + ] + return Dataset(points=points) + + def test_test_split_never_reaches_the_fitter(self) -> None: + from agentomatic.agents import PromptFitterBridge + + train, val, gate = PromptFitterBridge._split_three( # noqa: SLF001 + self._points(train=4, validation=3, test=3) + ) + used = {p.query for p in [*train, *val, *(gate or [])]} + assert not any(q.startswith("test") for q in used) + assert gate is None # the fitter reserves its own slice of validation + + def test_holdout_split_becomes_the_gate(self) -> None: + from agentomatic.agents import PromptFitterBridge + + _train, val, gate = PromptFitterBridge._split_three( # noqa: SLF001 + self._points(train=4, validation=3, holdout=2, test=3) + ) + assert gate is not None and {p.query for p in gate} == {"holdout0", "holdout1"} + assert {p.query for p in val} == {"validation0", "validation1", "validation2"} + + def test_train_only_is_split_without_overlap(self) -> None: + from agentomatic.agents import PromptFitterBridge + + train, val, _ = PromptFitterBridge._split_three(self._points(train=10)) # noqa: SLF001 + assert not ({p.query for p in train} & {p.query for p in val}) + assert len(val) >= 1 + + def test_a_non_improving_result_changes_nothing(self) -> None: + from agentomatic.agents import PromptFitterBridge + from agentomatic.optimize import PromptFitResult + + result = PromptFitResult( + best_config=PromptRuntimeConfig(system_prompt="from prompts.json"), + baseline_config=PromptRuntimeConfig(system_prompt="from prompts.json"), + best_score=0.5, + baseline_score=0.5, + ) + assert PromptFitterBridge._extract_config(None, result) == {} # noqa: SLF001 + + def test_few_shot_demos_are_served_as_they_were_scored(self) -> None: + from agentomatic.agents import PromptFitterBridge + from agentomatic.optimize import PromptFitResult + + best = PromptRuntimeConfig( + system_prompt="Be precise.", + few_shot_examples=[{"query": "q", "response": "a"}], + ) + result = PromptFitResult( + best_config=best, + baseline_config=PromptRuntimeConfig(system_prompt="base"), + best_score=0.9, + baseline_score=0.1, + ) + config = PromptFitterBridge._extract_config(None, result) # noqa: SLF001 + assert config["system_prompt"].startswith("Be precise.") + assert "## Few-shot examples" in config["system_prompt"] diff --git a/tests/test_fitter.py b/tests/test_fitter.py index 543552e7..4195d1b0 100644 --- a/tests/test_fitter.py +++ b/tests/test_fitter.py @@ -1516,7 +1516,8 @@ def transform(self, input_data): agent = FakeAgent() fn = _wrap_local_agent(agent) result = await fn("hello", prompt_override=None, context=None, invoke=None) - assert result == "transformed:hello" + # Dicts pass through; AgentRunner derives the scored text. + assert result == {"response": "transformed:hello"} @pytest.mark.asyncio async def test_wrap_atransform(self): @@ -1529,7 +1530,7 @@ async def atransform(self, input_data): agent = FakeAsyncAgent() fn = _wrap_local_agent(agent) result = await fn("world", prompt_override=None, context=None, invoke=None) - assert result == "async:world" + assert result == {"response": "async:world"} @pytest.mark.asyncio async def test_wrap_output_dict(self): @@ -1544,7 +1545,9 @@ def transform(self, input_data): agent = FakeAgent() fn = _wrap_local_agent(agent) result = await fn("q", prompt_override=None, context=None, invoke=None) - data = json.loads(result) + from agentomatic.optimize.runner import _response_text + + data = json.loads(_response_text(result)) assert data == {"content": "foo", "next_action": "bar"} @pytest.mark.asyncio @@ -1577,7 +1580,7 @@ def transform(self, input_data): fn = _wrap_local_agent(agent) result = await fn("q", prompt_override="overridden", context=None, invoke=None) # response was generated with the override - assert result == "overridden" + assert result == {"response": "overridden"} # original prompt restored after call assert agent.system_prompt == "original" diff --git a/tests/test_train_pipeline_fixes.py b/tests/test_train_pipeline_fixes.py index 71cdce41..9e1e4a78 100644 --- a/tests/test_train_pipeline_fixes.py +++ b/tests/test_train_pipeline_fixes.py @@ -244,7 +244,7 @@ def test_invoke_stream_emits_node_frames(self, tmp_path) -> None: class TestFitterEvalHonesty: @pytest.mark.asyncio - async def test_evaluate_config_skips_failed_judge(self, monkeypatch) -> None: + async def test_evaluate_config_counts_failed_judge_as_zero(self, monkeypatch) -> None: from agentomatic.optimize.dataset import Dataset from agentomatic.optimize.fitter import PromptFitter from agentomatic.optimize.runner import RunResult @@ -287,6 +287,8 @@ async def _eval(query, response, expected=None, context=None): ), metric, ) - # Only the successful point contributes → avg 1.0, not 0.5. - assert avg == pytest.approx(1.0) + # The failed judge call counts as 0.0 (not skipped): skipping it let a + # candidate that breaks the judge on hard inputs outscore one that + # answers them. The failure stays visible in the details. + assert avg == pytest.approx(0.5) assert any(d.get("error") for d in details) From 950baa352c616d48d57ec882ccfd561900de9506 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 19:14:43 +0000 Subject: [PATCH 04/16] fix(optimize): judge scores and metric aggregation mean what they say MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Judge replies are normalised instead of clamped: a 0–10 or 0–100 score (`7`, `85`, "8/10", "80%") used to read as a perfect 1.0. LocalJudgeMetric accepts `score`/`overall`/`rating` as well as `overall_score`, falls back to the mean of the dimension scores, parses each dimension on its own (one nested dimension used to discard a valid overall score), keeps string fields whole, and flags failure explicitly rather than by feedback text. LLMJudgeMetric/GEvalMetric accept `overall_score`; judges take their own `base_url`/`api_key`. - CompositeMetric counts a failed component as 0 at its full weight (a failed judge used to *raise* the composite) and reports failure when half the weight failed; negative weights are rejected (every metric is higher-is-better); its sync `score()` shares the one adapter. - MultiJudgePanel keeps each weight with its own judge when another fails, guards a zero total, implements median/min/max (unknown names raise), and exposes a name and dimensions. - DeepEval bias/toxicity/hallucination are inverted to higher-is-better (maximising them favoured toxic answers); a missing DeepEval score is a failed evaluation. LatencyMetric reads the measured call duration; a CustomMetric returning NaN is a failure, other values are clamped. - local_judges no longer mutate the caller's CompositeMetric each epoch. - agents.EarlyStopping follows Keras patience, implements restore_best and infers mode from the `loss` suffix; fit() rejects optimize-side callbacks with a clear message; fit_agent monitors `loss` when there is no validation split. Crashed examples no longer count as passed. Metric names must be unique. evaluate() reports metric failures. One judge call per example no matter how many wrappers share the judge. - build_default_metrics selects candidates on the same blend the loss reports (the fit metric had no judge). run_sync reuses one background loop inside a running loop instead of leaking a new loop per call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- src/agentomatic/agents/base.py | 30 ++ src/agentomatic/agents/history.py | 48 +++- src/agentomatic/agents/metrics.py | 60 ++-- src/agentomatic/agents/types.py | 13 +- src/agentomatic/async_utils.py | 35 ++- src/agentomatic/optimize/fitter.py | 14 +- src/agentomatic/optimize/judges.py | 238 ++++++++++------ src/agentomatic/optimize/metrics.py | 337 ++++++++++++++++------ src/agentomatic/optimize/train_api.py | 17 +- tests/test_all_methods_extensive.py | 18 +- tests/test_fitter.py | 4 +- tests/test_metric_honesty.py | 388 ++++++++++++++++++++++++++ tests/test_optimization_bugs.py | 7 +- tests/test_train_api_and_holysheet.py | 4 +- 14 files changed, 995 insertions(+), 218 deletions(-) create mode 100644 tests/test_metric_honesty.py diff --git a/src/agentomatic/agents/base.py b/src/agentomatic/agents/base.py index c18223c2..b3d4c45d 100644 --- a/src/agentomatic/agents/base.py +++ b/src/agentomatic/agents/base.py @@ -585,6 +585,7 @@ def evaluate( example_results: list[ExampleResult] = [] metric_totals: dict[str, float] = {m.name: 0.0 for m in metrics} + metric_failures: dict[str, int] = {} for example in examples: t0 = time.perf_counter() @@ -595,8 +596,11 @@ def evaluate( scores: dict[str, float] = {} metric_meta: dict[str, Any] = {} for metric in metrics: + failures_before = getattr(metric, "failures", 0) try: score = metric.score(example, prediction) + if getattr(metric, "failures", 0) > failures_before: + metric_failures[metric.name] = metric_failures.get(metric.name, 0) + 1 scores[metric.name] = score metric_totals[metric.name] += score last = getattr(metric, "last_result", None) @@ -616,6 +620,7 @@ def evaluate( except Exception as exc: logger.warning(f"Metric '{metric.name}' error: {exc}") scores[metric.name] = 0.0 + metric_failures[metric.name] = metric_failures.get(metric.name, 0) + 1 example_results.append( ExampleResult( @@ -646,7 +651,16 @@ def evaluate( dataset_name=dataset_name, scores=avg_scores, example_results=example_results, + metadata={ + "metric_failures": metric_failures, + "transform_errors": sum(1 for r in example_results if r.error), + }, ) + if metric_failures: + logger.warning( + "evaluate(): metric failures scored as 0.0 — {} (check the judge endpoint)", + ", ".join(f"{k}: {v}/{len(examples)}" for k, v in metric_failures.items()), + ) self.evaluation_history.append(report) return report @@ -684,6 +698,15 @@ def compile( # Optimize metrics (``LocalJudgeMetric``, ``ExactMatchMetric``, …) are # wrapped so they can be listed here directly. metrics = [as_agent_metric(m) for m in (metrics or [])] + names = [m.name for m in metrics] + duplicates = sorted({n for n in names if names.count(n) > 1}) + if duplicates or "loss" in names: + # Epoch logs are keyed by metric name: duplicates were summed + # (two "quality" metrics reported 1.70) and "loss" was overwritten. + raise ValueError( + f"Metric names must be unique and not 'loss' (got {names}); " + "pass name=... to tell them apart." + ) if not metrics: logger.warning( "compile() called without metrics — fit()/evaluate() will " @@ -823,6 +846,13 @@ def fit( callbacks = list(callbacks or []) for cb in callbacks: + if not callable(getattr(cb, "set_agent", None)): + raise TypeError( + f"{type(cb).__name__} is not an agent.fit() callback. Use " + "agentomatic.agents.EarlyStopping / EpochDiffCallback here; " + "agentomatic.optimize.EarlyStopping & co. belong to " + "PromptFitter(callbacks=[...]) (the inner trial loop)." + ) cb.set_agent(self) cb.set_params(history.params) cb.on_train_begin() diff --git a/src/agentomatic/agents/history.py b/src/agentomatic/agents/history.py index d5640d3d..d6aa3839 100644 --- a/src/agentomatic/agents/history.py +++ b/src/agentomatic/agents/history.py @@ -150,13 +150,21 @@ def on_epoch_end(self, epoch: int, logs: dict[str, float] | None = None) -> None class EarlyStopping(Callback): """Stop training when a monitored metric stops improving. + Keras semantics: training stops once ``patience`` consecutive epochs + fail to improve ``monitor`` (``patience=0`` stops at the first one). + + Note that ``val_loss`` is measured on the validation split — the same + data prompt candidates are selected on — so it is a selection score, not + an unbiased estimate. Keep a ``test`` split for that. + Args: monitor: Log key to watch (default ``"loss"``). - mode: ``"min"``, ``"max"``, or ``"auto"`` (inferred from ``monitor``). - patience: Epochs with no improvement before stopping. + mode: ``"min"``, ``"max"``, or ``"auto"`` (``min`` when ``monitor`` + ends with ``loss``). + patience: Non-improving epochs tolerated before stopping. min_delta: Minimum change to qualify as an improvement. - restore_best: If true, no-op placeholder for API parity (config is not - snapshotted); kept for forward compatibility. + restore_best: Restore the agent's ``compiled_config`` (prompt, params, + few-shot) from the best epoch when training ends. """ def __init__( @@ -173,17 +181,39 @@ def __init__( self.min_delta = abs(min_delta) self.restore_best = restore_best if mode == "auto": - mode = "min" if "loss" in monitor else "max" + mode = "min" if monitor.endswith("loss") else "max" self.mode = mode self._best: float | None = None + self._best_config: dict[str, Any] | None = None self._wait = 0 self.stopped_epoch: int | None = None def on_train_begin(self, logs: dict[str, float] | None = None) -> None: self._best = None + self._best_config = None self._wait = 0 self.stopped_epoch = None + def on_train_end(self, logs: dict[str, float] | None = None) -> None: + if not self.restore_best or self._best_config is None or self.agent is None: + return + current = dict(getattr(self.agent, "compiled_config", None) or {}) + if current == self._best_config: + return + self.agent.compiled_config = dict(self._best_config) + for key, value in self._best_config.items(): + if hasattr(self.agent, key): + try: + setattr(self.agent, key, value) + except (AttributeError, TypeError): + pass + invalidate = getattr(self.agent, "invalidate_graph", None) + if callable(invalidate): + invalidate() + logger.info( + f"EarlyStopping: restored the best epoch's config ({self.monitor}={self._best:.4f})" + ) + def _is_improvement(self, current: float) -> bool: if self._best is None: return True @@ -200,9 +230,15 @@ def on_epoch_end(self, epoch: int, logs: dict[str, float] | None = None) -> None if self._is_improvement(current): self._best = current self._wait = 0 + if self.restore_best and self.agent is not None: + import copy + + self._best_config = copy.deepcopy( + dict(getattr(self.agent, "compiled_config", None) or {}) + ) return self._wait += 1 - if self._wait > self.patience: + if self._wait >= self.patience: self.stopped_epoch = epoch if self.agent is not None: self.agent.stop_training = True diff --git a/src/agentomatic/agents/metrics.py b/src/agentomatic/agents/metrics.py index 937a2b60..0bf49d40 100644 --- a/src/agentomatic/agents/metrics.py +++ b/src/agentomatic/agents/metrics.py @@ -13,6 +13,8 @@ from __future__ import annotations import difflib +import weakref +from collections import OrderedDict from collections.abc import Callable, Sequence from typing import Any @@ -20,6 +22,15 @@ from .types import AgentExample +#: Per-metric cache of successful judge results, keyed by what was judged. +#: The same judge is routinely wrapped several times (as a compiled metric, +#: inside a WeightedMetric, inside the loss); without this every wrapper paid +#: for its own LLM call on the same (question, answer, reference). +_RESULT_CACHE: weakref.WeakKeyDictionary[Any, OrderedDict[tuple[Any, ...], Any]] = ( + weakref.WeakKeyDictionary() +) +_RESULT_CACHE_SIZE = 4096 + # --------------------------------------------------------------------------- # ResponseSimilarityMetric # --------------------------------------------------------------------------- @@ -469,24 +480,41 @@ def score( elif isinstance(raw_ctx, list) and raw_ctx: context = [str(c) for c in raw_ctx if c] - # --- serialise prediction as response string --- - response = str( - prediction.get("response") - or prediction.get("answer") - or _json.dumps(prediction, ensure_ascii=False) - ) + # --- the text judged: the same rule PromptFitter scores with --- + # (structured ``output`` dict as JSON, else ``response``/``answer``), + # so a metric reports on exactly what candidates were selected on. + from agentomatic.optimize.runner import _response_text + + if isinstance(prediction.get("output"), dict) and prediction.get("output"): + response = _response_text(prediction) + else: + response = str( + prediction.get("response") + or prediction.get("answer") + or _json.dumps(prediction, ensure_ascii=False) + ) - # --- run evaluate() synchronously --- - # Wrap the entire call (including coro creation) so that metrics whose - # evaluate() raises synchronously (non-coroutine callables that throw) - # are also handled gracefully. Use persistent-loop run_sync so OpenAI - # async clients survive across fit → evaluate. + # --- run evaluate() synchronously (cached per metric) --- + key = (query, response, expected, tuple(context or ())) try: - result = run_sync(self._metric.evaluate(query, response, expected, context)) - except Exception as exc: # noqa: BLE001 - one failed judge call must not abort fit - self.failures += 1 - logger.warning(f"Metric '{self.name}' failed ({exc}); scoring this example 0.0") - return 0.0 + cache = _RESULT_CACHE.setdefault(self._metric, OrderedDict()) + except TypeError: # not weak-referenceable: no caching + cache = OrderedDict() + result = cache.get(key) + if result is None: + # Wrap the entire call (including coro creation) so that metrics + # whose evaluate() raises synchronously are handled too. Use the + # persistent-loop run_sync so async clients survive fit → evaluate. + try: + result = run_sync(self._metric.evaluate(query, response, expected, context)) + except Exception as exc: # noqa: BLE001 - one failed judge call must not abort fit + self.failures += 1 + logger.warning(f"Metric '{self.name}' failed ({exc}); scoring this example 0.0") + return 0.0 + if not (getattr(result, "metadata", None) or {}).get("evaluation_failed"): + cache[key] = result + if len(cache) > _RESULT_CACHE_SIZE: + cache.popitem(last=False) self.last_result = result if (getattr(result, "metadata", None) or {}).get("evaluation_failed"): diff --git a/src/agentomatic/agents/types.py b/src/agentomatic/agents/types.py index f8047d30..f7fbfb7e 100644 --- a/src/agentomatic/agents/types.py +++ b/src/agentomatic/agents/types.py @@ -497,8 +497,17 @@ class ExampleResult: @property def passed(self) -> bool: - """Whether all scores are above 0.5.""" - return all(s >= 0.5 for s in self.scores.values()) + """Whether the example ran and every score is at least 0.5. + + A crashed example (``error`` set, no scores) used to count as passed — + ``all([])`` is ``True`` — so a run where every transform failed + reported a 100% pass rate. + """ + return ( + self.error is None + and bool(self.scores) + and all(s >= 0.5 for s in self.scores.values()) + ) @dataclass diff --git a/src/agentomatic/async_utils.py b/src/agentomatic/async_utils.py index edc23af0..23c2e7ca 100644 --- a/src/agentomatic/async_utils.py +++ b/src/agentomatic/async_utils.py @@ -60,11 +60,36 @@ def run_sync(coro: Coroutine[Any, Any, T]) -> T: except RuntimeError: return _thread_loop().run_until_complete(coro) - def _runner(c: Coroutine[Any, Any, T]) -> T: - return _thread_loop().run_until_complete(c) - - with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: - return pool.submit(_runner, coro).result() + if threading.current_thread() is _bridge_thread: + # Re-entrant call from code already running on the bridge loop: that + # loop is busy with our caller, so waiting on it would deadlock. + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(lambda: _thread_loop().run_until_complete(coro)).result() + + # Inside a running loop (FastAPI, notebooks): run on ONE long-lived + # background loop. A fresh worker thread per call used to create — and + # never close — a new event loop each time, so async clients bound to + # the first call's loop failed on the next. + return asyncio.run_coroutine_threadsafe(coro, _bridge_loop()).result() + + +_bridge_lock = threading.Lock() +_bridge_thread: threading.Thread | None = None +_bridge: asyncio.AbstractEventLoop | None = None + + +def _bridge_loop() -> asyncio.AbstractEventLoop: + """Return the process-wide background loop used by :func:`run_sync`.""" + global _bridge, _bridge_thread + with _bridge_lock: + if _bridge is None or _bridge.is_closed(): + loop = asyncio.new_event_loop() + thread = threading.Thread( + target=loop.run_forever, name="agentomatic-run-sync", daemon=True + ) + thread.start() + _bridge, _bridge_thread = loop, thread + return _bridge async def run_in_worker_thread(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T: diff --git a/src/agentomatic/optimize/fitter.py b/src/agentomatic/optimize/fitter.py index 9e35d9c2..0cf768bd 100644 --- a/src/agentomatic/optimize/fitter.py +++ b/src/agentomatic/optimize/fitter.py @@ -1862,15 +1862,19 @@ def _augment_metric_with_local_judges( panel: BaseMetric = judges[0] if len(judges) == 1 else MultiJudgePanel(judges=judges) if isinstance(metric, CompositeMetric): - metric._metrics.append( # noqa: SLF001 - intentional augmentation - WeightedMetric(name="local_judges", metric=panel, weight=0.35) - ) - metric._total_weight = sum(wm.weight for wm in metric._metrics) # noqa: SLF001 + # A new composite — appending to the caller's object added another + # judge entry on every fit (the bridge builds a fitter per epoch). logger.info( "Augmented composite metric with {} local judge(s)", len(judges), ) - return metric + return CompositeMetric( + [ + *metric.metrics, + WeightedMetric(name="local_judges", metric=panel, weight=0.35), + ], + name=metric.name, + ) augmented = CompositeMetric( metrics=[ diff --git a/src/agentomatic/optimize/judges.py b/src/agentomatic/optimize/judges.py index 84eaf8e3..7ac03d4b 100644 --- a/src/agentomatic/optimize/judges.py +++ b/src/agentomatic/optimize/judges.py @@ -19,11 +19,37 @@ from loguru import logger -from agentomatic.optimize.metrics import BaseMetric, EvalResult, MetricResult +from agentomatic.optimize.metrics import ( + _JUDGE_SCORE_KEYS, + BaseMetric, + EvalResult, + MetricResult, + coerce_judge_score, +) if TYPE_CHECKING: from agentomatic.optimize.llm_types import LLMSpec + +def _as_list(value: Any) -> list[str]: + """Coerce a judge field that should be a list of strings.""" + if value is None: + return [] + if isinstance(value, str): + return [value] if value.strip() else [] + if isinstance(value, (list, tuple)): + return [str(v) for v in value if str(v).strip()] + return [str(value)] + + +def _judge_failed(result: MetricResult) -> bool: + """True when a judge's ``MetricResult`` marks a failed evaluation.""" + flag = getattr(result, "_judge_failed", None) + if flag is not None: + return bool(flag) + return (result.feedback or "").startswith("Judge evaluation failed:") + + # ===================================================================== # Local SLM Judge # ===================================================================== @@ -56,12 +82,20 @@ def __init__( dimensions: list[str] | None = None, weight: float = 1.0, temperature: float = 0.0, + *, + base_url: str | None = None, + api_key: str | None = None, ) -> None: self.name = name self.model = model self.criteria = criteria self.dimensions = dimensions or ["correctness", "completeness", "relevance"] + #: Informational only — weight a judge inside ``CompositeMetric`` / + #: ``WeightedMetric`` (this value is not read by the judge itself). self.weight = weight + #: Endpoint for this judge only (else ``LLMCaller`` defaults / env). + self.base_url = base_url + self.api_key = api_key # Default 0.0 for reproducible scoring across epochs (reduces 0.33↔0.67 # oscillation from sampling noise at temp>0). self.temperature = temperature @@ -79,7 +113,7 @@ async def evaluate( the ``"metric_result"`` key. """ metric_result = await self.evaluate_rich(query, response, expected, context) - failed = metric_result.feedback.startswith("Judge evaluation failed:") + failed = bool(getattr(metric_result, "_judge_failed", False)) extras = getattr(metric_result, "_judge_extras", {}) or {} return EvalResult( metric_name=self.name, @@ -93,6 +127,8 @@ async def evaluate( "what_worked": extras.get("what_worked", []), "what_failed": extras.get("what_failed", []), "improvement_hints": extras.get("improvement_hints", []), + "score_source": extras.get("score_source", ""), + "raw_score": extras.get("raw_score"), }, ) @@ -154,22 +190,40 @@ async def evaluate_rich( model=self.model, prompt=prompt, temperature=self.temperature, + base_url=self.base_url, + api_key=self.api_key, ) - if not data or "overall_score" not in data: - raise ValueError("Judge returned no overall_score") + if not isinstance(data, dict) or not data: + raise ValueError("Judge returned no JSON object") + + # Per-dimension scores, each parsed on its own (one malformed + # dimension used to discard a perfectly good overall score). + dims: dict[str, float] = {} + raw_dims = data.get("dimensions") or data.get("scores") or {} + if isinstance(raw_dims, dict): + lowered = {str(k).lower(): v for k, v in raw_dims.items()} + for d in self.dimensions: + value = coerce_judge_score(lowered.get(d.lower())) + if value is not None: + dims[d] = value + + raw_overall = next((data[k] for k in _JUDGE_SCORE_KEYS if k in data), None) + overall = coerce_judge_score(raw_overall) + score_source = "overall" + if overall is None and dims: + # Small models often return only the dimension scores. + overall = sum(dims.values()) / len(dims) + score_source = "dimension_mean" + if overall is None: + raise ValueError( + f"Judge reply has no usable score (keys: {sorted(data)[:8]}, " + f"overall={raw_overall!r})" + ) - overall = max(0.0, min(1.0, float(data["overall_score"]))) feedback = str(data.get("feedback", "")) motivation = str(data.get("motivation", "")).strip() if motivation and motivation not in feedback: feedback = f"{feedback}\n\nMotivation: {motivation}".strip() - - dims: dict[str, float] = {} - raw_dims = data.get("dimensions", {}) - if isinstance(raw_dims, dict): - for d in self.dimensions: - if d in raw_dims: - dims[d] = max(0.0, min(1.0, float(raw_dims[d]))) # Missing dimensions inherit the overall score (not a fabricated 0.5). for d in self.dimensions: dims.setdefault(d, overall) @@ -178,23 +232,28 @@ async def evaluate_rich( # Attach rich judge fields for epoch learnings / rewrite briefings. rich_meta = { "motivation": motivation, - "what_worked": list(data.get("what_worked") or []), - "what_failed": list(data.get("what_failed") or []), - "improvement_hints": list(data.get("improvement_hints") or []), + "what_worked": _as_list(data.get("what_worked")), + "what_failed": _as_list(data.get("what_failed")), + "improvement_hints": _as_list(data.get("improvement_hints")), + "score_source": score_source, + "raw_score": raw_overall, } - # MetricResult may not have a metadata field — stash on feedback path - # via a dynamic attribute used by LocalJudgeMetric.evaluate(). + # MetricResult has no metadata field — stash via dynamic attributes + # read by LocalJudgeMetric.evaluate() / MultiJudgePanel. result._judge_extras = rich_meta # type: ignore[attr-defined] + result._judge_failed = False # type: ignore[attr-defined] return result except Exception as exc: logger.warning(f"LocalJudgeMetric '{self.name}' failed: {exc}") # Honest failure — never fabricate a mid-scale score. - return MetricResult( + failed = MetricResult( score=0.0, feedback=f"Judge evaluation failed: {exc}", dimensions={d: 0.0 for d in self.dimensions}, ) + failed._judge_failed = True # type: ignore[attr-defined] + return failed # ===================================================================== @@ -203,10 +262,15 @@ async def evaluate_rich( class MultiJudgePanel(BaseMetric): - """Run multiple judges in parallel and aggregate their results. + """Run several judges in parallel and aggregate their scores. + + A panel reduces the variance and self-preference of a single judge + ("mixture of experts"). Judges that fail are dropped; each remaining + judge keeps *its own* weight. - Supports aggregation by average (default) or majority vote. - Optionally weighted by judge calibration scores. + Aggregations: ``"average"`` (weighted mean, default), ``"median"`` + (robust to one outlier judge — ``"majority"`` is an alias), ``"min"`` + (pessimistic: every judge must be satisfied), ``"max"``. Example:: @@ -216,24 +280,39 @@ class MultiJudgePanel(BaseMetric): LocalJudgeMetric(name="judge_llama", model="ollama/llama3.1:8b"), ], aggregation="average", + weights=[2.0, 1.0], ) """ name = "multi_judge_panel" + _AGGREGATIONS = ("average", "median", "min", "max") + def __init__( self, judges: list[LocalJudgeMetric], aggregation: str = "average", weights: list[float] | None = None, + *, + name: str = "multi_judge_panel", ) -> None: if not judges: raise ValueError("MultiJudgePanel requires at least one judge") + aggregation = {"majority": "median", "majority_vote": "median"}.get( + aggregation, aggregation + ) + if aggregation not in self._AGGREGATIONS: + raise ValueError( + f"Unknown aggregation '{aggregation}'. Choose from {list(self._AGGREGATIONS)}." + ) + self.name = name self._judges = judges self._aggregation = aggregation - self._weights = weights or [1.0] * len(judges) + self._weights = list(weights) if weights is not None else [1.0] * len(judges) if len(self._weights) != len(judges): raise ValueError("Number of weights must match number of judges") + if any(w < 0 for w in self._weights) or sum(self._weights) <= 0: + raise ValueError("Judge weights must be >= 0 with a positive total") async def evaluate( self, @@ -246,92 +325,75 @@ async def evaluate( tasks = [judge.evaluate_rich(query, response, expected, context) for judge in self._judges] results = await asyncio.gather(*tasks, return_exceptions=True) - valid_results: list[MetricResult] = [] - for r in results: - if isinstance(r, MetricResult): - valid_results.append(r) - elif isinstance(r, Exception): - logger.warning(f"MultiJudgePanel: judge failed: {r}") - - if not valid_results: - return EvalResult( - metric_name=self.name, - score=0.0, - reason="All judges failed", - metadata={"evaluation_failed": True}, - ) - - # LocalJudgeMetric soft-fails into MetricResult; treat those as failures - # so fitter/composite metrics can skip dishonest zero scores. - failed_flags = [ - (r.feedback or "").startswith("Judge evaluation failed:") for r in valid_results - ] - if all(failed_flags): + # Keep each judge's weight attached to its own result: dropping failed + # judges used to shift the weights onto the wrong judges. + usable: list[tuple[MetricResult, float, str]] = [] + failures: list[str] = [] + for judge, weight, r in zip(self._judges, self._weights, results, strict=True): + judge_name = getattr(judge, "name", "judge") + if isinstance(r, BaseException): + logger.warning(f"MultiJudgePanel: judge '{judge_name}' raised: {r}") + failures.append(judge_name) + elif isinstance(r, MetricResult) and not _judge_failed(r): + usable.append((r, weight, judge_name)) + else: + failures.append(judge_name) + + if not usable or sum(w for _, w, _ in usable) <= 0: return EvalResult( metric_name=self.name, score=0.0, - reason="All judges failed", - metadata={ - "evaluation_failed": True, - "individual_scores": [r.score for r in valid_results], - "metric_result": valid_results[0], - }, + reason="All judges failed" if not usable else "All usable judges have weight 0", + metadata={"evaluation_failed": True, "failed_judges": failures}, ) - usable = [r for r, failed in zip(valid_results, failed_flags) if not failed] - if not usable: - usable = valid_results - - # Aggregate - if self._aggregation == "average": - aggregated = self._aggregate_average(usable) - else: - aggregated = self._aggregate_average(usable) - - # Collect all feedback - feedback_parts = [r.feedback for r in usable if r.feedback] + score, dimensions = self._aggregate(usable) + feedback_parts = [f"[{name}] {r.feedback}" for r, _, name in usable if r.feedback] combined_feedback = " | ".join(feedback_parts) - metric_result = MetricResult( - score=aggregated["score"], + score=score, feedback=combined_feedback, - dimensions=aggregated["dimensions"], + dimensions=dimensions, ) - return EvalResult( metric_name=self.name, - score=aggregated["score"], + score=score, reason=combined_feedback, metadata={ - "individual_scores": [r.score for r in usable], + "individual_scores": {name: r.score for r, _, name in usable}, + "failed_judges": failures, + "aggregation": self._aggregation, + "dimensions": dimensions, "metric_result": metric_result, "evaluation_failed": False, }, ) - def _aggregate_average(self, results: list[MetricResult]) -> dict[str, Any]: - """Weighted average aggregation.""" - weights = self._weights[: len(results)] - total_w = sum(weights) - - weighted_score = sum(r.score * w for r, w in zip(results, weights)) / total_w - - # Aggregate dimensions - all_dim_keys: set[str] = set() - for r in results: - all_dim_keys.update(r.dimensions.keys()) + def _aggregate( + self, usable: list[tuple[MetricResult, float, str]] + ) -> tuple[float, dict[str, float]]: + """Aggregate scores (per ``aggregation``) and dimensions (weighted mean).""" + import statistics + + scores = [r.score for r, _, _ in usable] + if self._aggregation == "median": + score = float(statistics.median(scores)) + elif self._aggregation == "min": + score = min(scores) + elif self._aggregation == "max": + score = max(scores) + else: + total_w = sum(w for _, w, _ in usable) + score = sum(r.score * w for r, w, _ in usable) / total_w dimensions: dict[str, float] = {} - for key in all_dim_keys: - dim_vals = [ - (r.dimensions.get(key, 0.0), w) - for r, w in zip(results, weights) - if key in r.dimensions - ] - if dim_vals: - dimensions[key] = sum(v * w for v, w in dim_vals) / sum(w for _, w in dim_vals) - - return {"score": weighted_score, "dimensions": dimensions} + keys = {k for r, _, _ in usable for k in r.dimensions} + for key in keys: + pairs = [(r.dimensions[key], w) for r, w, _ in usable if key in r.dimensions] + weight = sum(w for _, w in pairs) + if weight > 0: + dimensions[key] = sum(v * w for v, w in pairs) / weight + return score, dimensions # ===================================================================== diff --git a/src/agentomatic/optimize/metrics.py b/src/agentomatic/optimize/metrics.py index a68ca8b6..0c71b4bc 100644 --- a/src/agentomatic/optimize/metrics.py +++ b/src/agentomatic/optimize/metrics.py @@ -109,6 +109,66 @@ async def evaluate( # ===================================================================== +#: Keys a judge may use for its overall score (first match wins). +_JUDGE_SCORE_KEYS = ("overall_score", "score", "overall", "final_score", "rating") + +_FRACTION = re.compile(r"^\s*(-?\d+(?:\.\d+)?)\s*/\s*(\d+(?:\.\d+)?)\s*$") +_PERCENT = re.compile(r"^\s*(-?\d+(?:\.\d+)?)\s*%\s*$") + + +def coerce_judge_score(value: Any) -> float | None: + """Normalise a judge's score to ``[0, 1]`` — or ``None`` when unusable. + + Small local judges routinely ignore "score 0.0–1.0" and answer on another + scale. Clamping ``7`` (out of 10) or ``85`` (out of 100) to ``1.0`` made + every such reply a perfect score; they are rescaled instead: + + * numbers in ``[0, 1]`` are kept; ``(1, 10]`` are divided by 10 and + ``(10, 100]`` by 100; anything else is unusable; + * strings: ``"0.8"``, ``"8/10"``, ``"80%"``; + * ``{"score": x}`` objects are unwrapped. + + Args: + value: The raw score from the judge's JSON. + + Returns: + The normalised score, or ``None`` (treat as a failed evaluation). + """ + if isinstance(value, bool) or value is None: + return None + if isinstance(value, dict): + for key in ("score", "value", "overall_score"): + if key in value: + return coerce_judge_score(value[key]) + return None + if isinstance(value, str): + text = value.strip() + fraction = _FRACTION.match(text) + if fraction: + num, den = float(fraction.group(1)), float(fraction.group(2)) + return coerce_judge_score(num / den) if den > 0 else None + percent = _PERCENT.match(text) + if percent: + return coerce_judge_score(float(percent.group(1)) / 100.0) + try: + value = float(text) + except ValueError: + return None + try: + number = float(value) + except (TypeError, ValueError): + return None + if number != number or number < 0: # NaN or negative + return None + if number <= 1.0: + return number + if number <= 10.0: + return number / 10.0 + if number <= 100.0: + return number / 100.0 + return None + + #: Header that opens the plain answer inside a rich expected reference. _EXPECTED_ANSWER_HEADER = re.compile( r"^[ \t]*##[ \t]*Expected answer[ \t]*$", re.MULTILINE | re.IGNORECASE @@ -235,10 +295,16 @@ def __init__( model: LLMSpec = "ollama/mistral:7b", name: str = "llm_judge", temperature: float = 0.0, + *, + base_url: str | None = None, + api_key: str | None = None, ): self.criteria = criteria self.model = model self.name = name + #: Endpoint for this judge only (else LLMCaller defaults / env). + self.base_url = base_url + self.api_key = api_key # Default 0.0 for reproducible scoring across epochs (avoids 0.33↔0.67 # oscillation from sampling noise at temp>0). self.temperature = temperature @@ -253,7 +319,7 @@ async def evaluate( # Skip deepeval for local OpenAI-compatible / oMLX specs — DeepEval # cannot route those models and its retries burn minutes before # falling through to the raw-LLM judge. - if _prefer_raw_llm_judge(self.model): + if self.base_url or _prefer_raw_llm_judge(self.model): return await self._eval_llm(query, response, expected, context) # Try deepeval first; any failure (missing key, bad model, …) @@ -287,6 +353,8 @@ async def _eval_deepeval( evaluation_params=[ evaluation_params_type.INPUT, evaluation_params_type.ACTUAL_OUTPUT, + # Without it GEval never looked at the reference answer. + *([evaluation_params_type.EXPECTED_OUTPUT] if expected else []), ], model=self.model, # type: ignore[arg-type] ) @@ -297,9 +365,16 @@ async def _eval_deepeval( retrieval_context=context or [], # type: ignore[arg-type] ) metric.measure(test_case) + if metric.score is None: + return EvalResult( + metric_name=self.name, + score=0.0, + reason=metric.reason or "DeepEval returned no score", + metadata={"evaluation_failed": True}, + ) return EvalResult( metric_name=self.name, - score=metric.score or 0.0, + score=max(0.0, min(1.0, float(metric.score))), reason=metric.reason or "", ) @@ -323,18 +398,35 @@ async def _eval_llm( prompt += f"CONTEXT:\n{chr(10).join(context[:3])}\n\n" prompt += 'Reply with ONLY a JSON object: {"score": 0.X, "reason": "..."}\n' - data = await call_llm_json(self.model, prompt, temperature=self.temperature) - if not data or "score" not in data: + if isinstance(self.model, str): + from agentomatic.optimize.llm_caller import LLMCaller + + data = await LLMCaller.call_with_json( + self.model, + prompt, + temperature=self.temperature, + base_url=self.base_url, + api_key=self.api_key, + ) + else: + data = await call_llm_json(self.model, prompt, temperature=self.temperature) + raw = next( + (data[k] for k in _JUDGE_SCORE_KEYS if isinstance(data, dict) and k in data), + None, + ) + score = coerce_judge_score(raw) + if score is None: return EvalResult( metric_name=self.name, score=0.0, - reason="LLM judge returned no parseable score", + reason=f"LLM judge returned no usable score ({raw!r})", metadata={"evaluation_failed": True}, ) return EvalResult( metric_name=self.name, - score=max(0.0, min(1.0, float(data.get("score", 0.0)))), - reason=str(data.get("reason", "")), + score=score, + reason=str(data.get("reason") or data.get("feedback") or ""), + metadata={"raw_score": raw}, ) except Exception as exc: logger.warning(f"LLM judge fallback failed: {exc}") @@ -376,9 +468,19 @@ async def evaluate( else: score = await asyncio.to_thread(self.fn, query, response, expected, context) + value = float(score) if score is not None else float("nan") + if value != value or value in (float("inf"), float("-inf")): + # NaN compares False with everything: one NaN baseline used to + # block every candidate from ever being promoted. + return EvalResult( + metric_name=self.name, + score=0.0, + reason=f"Custom metric '{self.name}' returned {score!r}", + metadata={"evaluation_failed": True}, + ) return EvalResult( metric_name=self.name, - score=float(score), + score=max(0.0, min(1.0, value)), reason=f"Custom metric '{self.name}'", ) @@ -436,7 +538,11 @@ async def evaluate( from deepeval.metrics import GEval from deepeval.test_case import LLMTestCase, LLMTestCaseParams - params = [getattr(LLMTestCaseParams, "ACTUAL_OUTPUT")] + # INPUT too: judging relevance without the question is guesswork. + params = [ + getattr(LLMTestCaseParams, "INPUT"), + getattr(LLMTestCaseParams, "ACTUAL_OUTPUT"), + ] if expected: params.append(getattr(LLMTestCaseParams, "EXPECTED_OUTPUT")) @@ -455,14 +561,21 @@ async def evaluate( retrieval_context=context or [], # type: ignore[arg-type] ) metric.measure(test_case) + if metric.score is None: + return EvalResult( + metric_name=self.name, + score=0.0, + reason=metric.reason or "DeepEval returned no score", + metadata={"evaluation_failed": True}, + ) return EvalResult( metric_name=self.name, - score=metric.score or 0.0, + score=max(0.0, min(1.0, float(metric.score))), reason=metric.reason or "", ) except ImportError: logger.debug( - "deepeval not installed — falling back to raw LLM judge for GEvalMetric '%s'", + "deepeval not installed — falling back to raw LLM judge for GEvalMetric '{}'", self.name, ) except Exception as exc: # noqa: BLE001 @@ -508,20 +621,26 @@ async def _fallback_eval( ) data = await call_llm_json(self.model, prompt, temperature=self.temperature) - if not data or "score" not in data: + raw = next( + (data[k] for k in _JUDGE_SCORE_KEYS if isinstance(data, dict) and k in data), + None, + ) + score = coerce_judge_score(raw) + if score is None: return EvalResult( metric_name=self.name, score=0.0, - reason="GEval evaluation failed — no parseable score", + reason=f"GEval evaluation failed — no usable score ({raw!r})", metadata={"evaluation_failed": True}, ) return EvalResult( metric_name=self.name, - score=max(0.0, min(1.0, float(data["score"]))), + score=score, reason=str(data.get("reason", "")), + metadata={"raw_score": raw}, ) except Exception as exc: - logger.warning("GEvalMetric fallback failed: %s", exc) + logger.warning("GEvalMetric fallback failed: {}", exc) return EvalResult( metric_name=self.name, score=0.0, @@ -530,9 +649,29 @@ async def _fallback_eval( ) +#: DeepEval metrics where a HIGHER score is WORSE (``success = score <= threshold``). +_LOWER_IS_BETTER_DEEPEVAL = frozenset({"BiasMetric", "ToxicityMetric", "HallucinationMetric"}) + + +def _higher_is_better(deepeval_metric: Any, score: float, flag: bool | None = None) -> float: + """Orient a DeepEval score so higher always means better (optimizers maximise).""" + lower_is_better = ( + not flag + if flag is not None + else type(deepeval_metric).__name__ in _LOWER_IS_BETTER_DEEPEVAL + ) + score = max(0.0, min(1.0, float(score))) + return 1.0 - score if lower_is_better else score + + class DeepEvalMetric(BaseMetric): """Wrap ANY DeepEval metric instance as an agentomatic BaseMetric. + Scores are oriented so **higher is better**: DeepEval's bias, toxicity and + hallucination metrics (where a higher score is worse) are inverted + automatically — maximising them used to push the optimizer toward toxic + or hallucinated answers. Override with ``higher_is_better=``. + This is the universal adapter: pass in a fully-configured deepeval metric object and it will be called through our ``BaseMetric`` interface. @@ -542,8 +681,15 @@ class DeepEvalMetric(BaseMetric): metric = DeepEvalMetric(AnswerRelevancyMetric(model="ollama/mistral:7b")) """ - def __init__(self, deepeval_metric: Any, name: str | None = None): + def __init__( + self, + deepeval_metric: Any, + name: str | None = None, + *, + higher_is_better: bool | None = None, + ): self._metric = deepeval_metric + self._higher_is_better = higher_is_better self.name: str = ( name or getattr( @@ -576,10 +722,19 @@ async def evaluate( retrieval_context=context or [], # type: ignore[arg-type] ) self._metric.measure(test_case) + raw = getattr(self._metric, "score", None) + if raw is None: + return EvalResult( + metric_name=self.name, + score=0.0, + reason=getattr(self._metric, "reason", "") or "DeepEval returned no score", + metadata={"evaluation_failed": True}, + ) return EvalResult( metric_name=self.name, - score=self._metric.score or 0.0, + score=_higher_is_better(self._metric, raw, self._higher_is_better), reason=getattr(self._metric, "reason", "") or "", + metadata={"raw_score": raw}, ) @@ -654,9 +809,9 @@ async def _eval_deepeval( bias_score = bias_metric.score or 0.0 toxicity_score = toxicity_metric.score or 0.0 - # For red-team safety: high DeepEval scores = safe = good - # Combine as average safety score - combined = (bias_score + toxicity_score) / 2.0 + # DeepEval bias/toxicity: HIGHER = worse. Safety is the complement + # (averaging them as "safety" used to rate toxic answers as safest). + combined = 1.0 - (bias_score + toxicity_score) / 2.0 reasons = [] if bias_metric.reason: @@ -784,23 +939,37 @@ async def evaluate( md = results[0].metrics_data if md: first = md[0] + if first.score is None: + return EvalResult( + metric_name=self.name, + score=0.0, + reason=first.reason or "DeepEval returned no score", + metadata={"evaluation_failed": True}, + ) return EvalResult( metric_name=self.name, - score=first.score if first.score is not None else 0.0, + score=_higher_is_better(self._metric, first.score), reason=first.reason or "", ) except (ImportError, TypeError, AttributeError, Exception) as exc: logger.debug( - "deepeval.evaluate() unavailable or failed (%s), " - "falling back to metric.measure()", + "deepeval.evaluate() unavailable or failed ({}), falling back to measure()", exc, ) # Fallback: direct measure call self._metric.measure(test_case) + raw = getattr(self._metric, "score", None) + if raw is None: + return EvalResult( + metric_name=self.name, + score=0.0, + reason=getattr(self._metric, "reason", "") or "DeepEval returned no score", + metadata={"evaluation_failed": True}, + ) return EvalResult( metric_name=self.name, - score=self._metric.score or 0.0, + score=_higher_is_better(self._metric, raw), reason=getattr(self._metric, "reason", "") or "", ) @@ -966,9 +1135,19 @@ class CompositeMetric(BaseMetric): name = "composite" - def __init__(self, metrics: list[WeightedMetric]) -> None: + def __init__(self, metrics: list[WeightedMetric], *, name: str = "composite") -> None: if not metrics: raise ValueError("CompositeMetric requires at least one WeightedMetric") + negative = [m.name for m in metrics if m.weight < 0] + if negative: + # Every metric scores higher-is-better (LatencyMetric / CostMetric + # included), so a negative weight *rewards* the worse outcome. + raise ValueError( + f"CompositeMetric weights must be >= 0 (got negative for {negative}); " + "all metrics are higher-is-better — give efficiency terms a small " + "positive weight instead." + ) + self.name = name self._metrics = metrics total_weight = sum(m.weight for m in metrics) if total_weight <= 0: @@ -997,30 +1176,35 @@ async def evaluate( dimensions: dict[str, float] = {} feedback_parts: list[str] = [] weighted_sum = 0.0 - active_weight = 0.0 - failed_count = 0 + failed: list[str] = [] for wm in self._metrics: try: result = await wm.metric.evaluate(query, response, expected, context) if (result.metadata or {}).get("evaluation_failed"): - failed_count += 1 + failed.append(wm.name) dimensions[wm.name] = 0.0 if result.reason: feedback_parts.append(f"[{wm.name}] {result.reason}") continue dimensions[wm.name] = result.score weighted_sum += result.score * wm.weight - active_weight += wm.weight if result.reason: feedback_parts.append(f"[{wm.name}] {result.reason}") except Exception as exc: logger.warning(f"CompositeMetric: sub-metric '{wm.name}' failed: {exc}") dimensions[wm.name] = 0.0 - failed_count += 1 + failed.append(wm.name) feedback = " | ".join(feedback_parts) - if failed_count == len(self._metrics) or active_weight == 0: + failed_count = len(failed) + failed_weight = sum(wm.weight for wm in self._metrics if wm.name in failed) + # A failed component counts as 0 against the FULL weight. Dropping it + # from the denominator made a composite *rise* when its judge failed + # (judge 0.8 + format 1.0 → 0.83 working, 1.00 with the judge down). + # When the failed share is the majority, the result is not a + # measurement at all. + if failed_count == len(self._metrics) or failed_weight * 2 >= self._total_weight: return EvalResult( metric_name=self.name, score=0.0, @@ -1032,7 +1216,7 @@ async def evaluate( }, ) - composite_score = weighted_sum / active_weight + composite_score = weighted_sum / self._total_weight metric_result = MetricResult( score=composite_score, feedback=feedback, @@ -1047,6 +1231,7 @@ async def evaluate( "dimensions": dimensions, "feedback": feedback, "metric_result": metric_result, + "failed_components": failed, }, ) @@ -1064,51 +1249,23 @@ async def evaluate_rich( def score(self, example: Any, prediction: Any) -> float: """Sync bridge for the ``agents.Metric`` protocol. - Allows ``optimize.CompositeMetric`` to be used directly as a - component in ``agents.WeightedMetric`` or ``agents.MetricLoss`` - without wrapping in ``OptimizeMetricAdapter``. - - Extracts ``query``, ``response``, and ``expected`` from - *example* / *prediction* and runs :meth:`evaluate` synchronously - via :func:`agentomatic.async_utils.run_sync` (persistent loop). + Lets ``CompositeMetric`` sit directly in ``compile(metrics=...)``, + ``agents.WeightedMetric`` or ``MetricLoss``. Delegates to + :class:`~agentomatic.agents.OptimizeMetricAdapter`, so the question, + response text and reference are extracted exactly as everywhere else + (this used to be a second, divergent bridge that judged the label and + the whole prediction JSON). Args: - example: An ``AgentExample`` with ``.input`` and - ``.expected_output``. + example: An ``AgentExample``. prediction: The agent's output dict. Returns: - Composite score in ``[0, 1]``. + Composite score in ``[0, 1]`` (``0.0`` when the evaluation failed). """ - import json as _json - - from agentomatic.async_utils import run_sync - - query = "" - inp = getattr(example, "input", example) - if hasattr(inp, "get"): - query = inp.get("query", inp.get("current_query", "")) - else: - query = str(inp) + from agentomatic.agents.metrics import OptimizeMetricAdapter - response = ( - _json.dumps(prediction, ensure_ascii=False) - if isinstance(prediction, dict) - else str(prediction) - ) - - exp_out = getattr(example, "expected_output", None) - expected = ( - _json.dumps(exp_out, ensure_ascii=False) - if isinstance(exp_out, dict) - else (str(exp_out) if exp_out is not None else None) - ) - - try: - result = run_sync(self.evaluate(query, response, expected)) - except Exception: - return 0.0 - return float(getattr(result, "score", 0.0)) + return OptimizeMetricAdapter(self, name=self.name).score(example, prediction) class DeterministicMetric(BaseMetric): @@ -1227,9 +1384,12 @@ async def evaluate( class LatencyMetric(BaseMetric): """Deployment-aware latency metric that penalises slow responses. - Returns a score between 0.0 and 1.0 based on response latency. - Designed for use with **negative weight** in ``CompositeMetric`` - to create latency pressure during optimization. + Returns a score between 0.0 and 1.0 based on response latency — + **higher is better** (faster), like every other metric. Give it a small + *positive* weight in ``CompositeMetric`` to add latency pressure. + + Latency comes from ``context`` (``"latency:2.35"``) or, inside + ``PromptFitter``, from the measured duration of the agent call. Score mapping (default thresholds): - < 1s → 1.0 (excellent) @@ -1245,10 +1405,10 @@ class LatencyMetric(BaseMetric): max_seconds=10.0, ) - # In CompositeMetric with negative weight: + # In CompositeMetric — positive weight, higher = faster: CompositeMetric(metrics=[ - WeightedMetric("quality", judge, weight=0.80), - WeightedMetric("latency", LatencyMetric(), weight=-0.10), + WeightedMetric("quality", judge, weight=0.90), + WeightedMetric("latency", LatencyMetric(), weight=0.10), ]) """ @@ -1271,18 +1431,24 @@ async def evaluate( ) -> EvalResult: """Score based on latency metadata. - The actual latency must be passed via ``context`` as the first - element in format ``"latency:2.35"`` or via the response metadata. - If no latency data is available, returns 0.5 (neutral). + Latency is read from ``context`` (``"latency:2.35"``), else from the + run being scored by ``PromptFitter``. Without either, the evaluation + is reported as failed (it used to return a neutral 0.5 that silently + diluted every composite). """ latency = self._extract_latency(response, context) + if latency is None: + run = current_scoring_run() + duration_ms = getattr(run, "duration_ms", None) if run is not None else None + if duration_ms: + latency = float(duration_ms) / 1000.0 if latency is None: return EvalResult( metric_name=self.name, - score=0.5, + score=0.0, reason="No latency data available", - metadata={"latency_seconds": None}, + metadata={"latency_seconds": None, "evaluation_failed": True}, ) if latency <= self.target_seconds: @@ -1321,8 +1487,9 @@ def _extract_latency( class CostMetric(BaseMetric): """Deployment-aware cost metric that penalises expensive responses. - Returns a score between 0.0 and 1.0 based on token usage / cost. - Designed for use with **negative weight** in ``CompositeMetric``. + Returns a score between 0.0 and 1.0 based on token usage / cost — + **higher is better** (cheaper). Give it a small *positive* weight in + ``CompositeMetric``. Score mapping: - < target_tokens → 1.0 @@ -1339,8 +1506,8 @@ class CostMetric(BaseMetric): # In CompositeMetric: CompositeMetric(metrics=[ - WeightedMetric("quality", judge, weight=0.85), - WeightedMetric("cost", CostMetric(), weight=-0.05), + WeightedMetric("quality", judge, weight=0.95), + WeightedMetric("cost", CostMetric(), weight=0.05), ]) """ diff --git a/src/agentomatic/optimize/train_api.py b/src/agentomatic/optimize/train_api.py index 9cbcc9e5..75994187 100644 --- a/src/agentomatic/optimize/train_api.py +++ b/src/agentomatic/optimize/train_api.py @@ -537,7 +537,12 @@ def build_default_metrics( judge_dimensions: Sequence[str], judge_weight: float = 0.30, ) -> tuple[list[Any], Any, Any]: - """Build agent metrics, loss, and optimize-fit CustomMetric. + """Build agent metrics, loss, and the fit objective. + + ``fit_metric`` (what PromptFitter *selects* candidates on) is the same + weighted blend the ``loss`` reports — judge included. It used to be a + judge-free structured score, so the optimizer could pick a candidate that + made the reported loss worse. Returns: ``(metrics, loss, fit_metric)`` ready for :func:`compile_agent`. @@ -554,7 +559,6 @@ def build_default_metrics( agent_field_f1, agent_keyword_score, agent_schema_quality, - make_structured_fit_metric, ) keys = list(required_keys) @@ -590,7 +594,9 @@ def build_default_metrics( name="composite_loss", ) ) - fit_metric = make_structured_fit_metric(keys, name="composite") + from agentomatic.optimize.metrics import ScoreMetricAdapter + + fit_metric = ScoreMetricAdapter(loss.metric, name="objective") return metrics, loss, fit_metric @@ -847,7 +853,10 @@ def fit_agent( if callbacks is not None: cbs = list(callbacks) else: - cbs = [EarlyStopping(monitor="val_loss", patience=stop_patience, mode="min")] + # Without validation data ``val_loss`` never appears in the logs and + # the default callback silently never fired. + monitor = "val_loss" if val else "loss" + cbs = [EarlyStopping(monitor=monitor, patience=stop_patience, mode="min")] return agent.fit( dataset, diff --git a/tests/test_all_methods_extensive.py b/tests/test_all_methods_extensive.py index b022534c..d5e9ab2f 100644 --- a/tests/test_all_methods_extensive.py +++ b/tests/test_all_methods_extensive.py @@ -667,15 +667,27 @@ async def evaluate(self, *a, **k): metadata={"evaluation_failed": True}, ) + # A minority component failing counts as 0 at its full weight — it must + # never *raise* the composite (dropping it from the denominator did). comp = CompositeMetric( metrics=[ - OptWeightedMetric("ok", ok, weight=0.5), - OptWeightedMetric("bad", _Fail(criteria="x"), weight=0.5), + OptWeightedMetric("ok", ok, weight=0.8), + OptWeightedMetric("bad", _Fail(criteria="x"), weight=0.2), ] ) r = await comp.evaluate("q", "yes", expected="yes") - assert r.score == pytest.approx(1.0) + assert r.score == pytest.approx(0.8) assert not r.metadata.get("evaluation_failed") + assert r.metadata["failed_components"] == ["bad"] + + # Half the weight failing is not a measurement any more. + half = CompositeMetric( + metrics=[ + OptWeightedMetric("ok", ok, weight=0.5), + OptWeightedMetric("bad", _Fail(criteria="x"), weight=0.5), + ] + ) + assert (await half.evaluate("q", "yes", expected="yes")).metadata.get("evaluation_failed") all_bad = CompositeMetric( metrics=[ diff --git a/tests/test_fitter.py b/tests/test_fitter.py index 4195d1b0..145404f3 100644 --- a/tests/test_fitter.py +++ b/tests/test_fitter.py @@ -1326,7 +1326,9 @@ async def test_no_latency_data(self): m = LatencyMetric() result = await m.evaluate("q", "resp") - assert result.score == 0.5 + # No data is a failed evaluation, not a neutral 0.5 diluting composites. + assert result.score == 0.0 + assert result.metadata["evaluation_failed"] is True assert "No latency data" in result.reason diff --git a/tests/test_metric_honesty.py b/tests/test_metric_honesty.py new file mode 100644 index 00000000..f9468c17 --- /dev/null +++ b/tests/test_metric_honesty.py @@ -0,0 +1,388 @@ +# pyright: reportMissingParameterType=none +# pyright: reportAttributeAccessIssue=none +"""Scores must mean what they say — no clamped scales, no score *rising* on failure. + +Covers the judge-parsing, aggregation and training-loop defects found by +auditing the optimization metrics: 0–10 judge scores clamped to a perfect 1.0, +``{"score": …}`` replies rejected, a failed judge raising a composite score, +panel weights attached to the wrong judge, lower-is-better DeepEval metrics +maximised, Keras-incompatible EarlyStopping, crashed examples "passing", and +the same judge being called several times per example. +""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from agentomatic.agents import ( + AgentExample, + CallableMetric, + EarlyStopping, + OptimizeMetricAdapter, +) +from agentomatic.agents.types import ExampleResult +from agentomatic.optimize import ( + BaseMetric, + CompositeMetric, + CustomMetric, + LatencyMetric, + LLMJudgeMetric, + LocalJudgeMetric, + MultiJudgePanel, +) +from agentomatic.optimize.llm_caller import LLMCaller +from agentomatic.optimize.metrics import ( + EvalResult, + WeightedMetric, + coerce_judge_score, + scoring_run, +) +from agentomatic.optimize.runner import RunResult + + +class TestCoerceJudgeScore: + @pytest.mark.parametrize( + ("raw", "expected"), + [ + (0.8, 0.8), + (1, 1.0), + (7, 0.7), + (85, 0.85), + ("0.6", 0.6), + ("8/10", 0.8), + ("80%", 0.8), + ({"score": 0.4}, 0.4), + ], + ) + def test_scales_are_normalised(self, raw: Any, expected: float) -> None: + assert coerce_judge_score(raw) == pytest.approx(expected) + + @pytest.mark.parametrize("raw", [None, True, -0.1, 250, "great", float("nan"), {}]) + def test_unusable_values(self, raw: Any) -> None: + assert coerce_judge_score(raw) is None + + +def _judge_reply(monkeypatch, reply: dict[str, Any]) -> None: + async def fake(*args: Any, **kwargs: Any) -> dict[str, Any]: + return reply + + monkeypatch.setattr(LLMCaller, "call_with_json", staticmethod(fake)) + + +class TestLocalJudgeParsing: + def _run(self, monkeypatch, reply: dict[str, Any]) -> EvalResult: + _judge_reply(monkeypatch, reply) + judge = LocalJudgeMetric(name="j", model="omlx/x", dimensions=["correctness", "relevance"]) + return asyncio.run(judge.evaluate("q", "r", "e")) + + def test_score_key_is_accepted(self, monkeypatch) -> None: + result = self._run(monkeypatch, {"score": 0.8}) + assert result.score == pytest.approx(0.8) + assert not result.metadata["evaluation_failed"] + + def test_ten_point_scale_is_not_a_perfect_score(self, monkeypatch) -> None: + assert self._run(monkeypatch, {"overall_score": 2}).score == pytest.approx(0.2) + + def test_dimension_only_reply_uses_their_mean(self, monkeypatch) -> None: + result = self._run(monkeypatch, {"dimensions": {"correctness": 0.9, "relevance": 0.7}}) + assert result.score == pytest.approx(0.8) + assert result.metadata["score_source"] == "dimension_mean" + + def test_nested_dimension_does_not_discard_the_overall(self, monkeypatch) -> None: + result = self._run( + monkeypatch, + {"overall_score": 0.7, "dimensions": {"correctness": {"score": 0.9, "why": "…"}}}, + ) + assert result.score == pytest.approx(0.7) + assert result.metadata["dimensions"]["correctness"] == pytest.approx(0.9) + + def test_string_fields_are_not_exploded_into_characters(self, monkeypatch) -> None: + result = self._run(monkeypatch, {"score": 0.5, "what_worked": "clear answer"}) + assert result.metadata["what_worked"] == ["clear answer"] + + def test_unusable_reply_is_a_failed_evaluation(self, monkeypatch) -> None: + result = self._run(monkeypatch, {"verdict": "good"}) + assert result.score == 0.0 + assert result.metadata["evaluation_failed"] is True + + def test_feedback_text_does_not_decide_failure(self, monkeypatch) -> None: + result = self._run( + monkeypatch, {"score": 0.9, "feedback": "Judge evaluation failed: not really"} + ) + assert result.metadata["evaluation_failed"] is False + + def test_per_judge_endpoint_is_forwarded(self, monkeypatch) -> None: + seen: dict[str, Any] = {} + + async def fake(*args: Any, **kwargs: Any) -> dict[str, Any]: + seen.update(kwargs) + return {"score": 1} + + monkeypatch.setattr(LLMCaller, "call_with_json", staticmethod(fake)) + judge = LocalJudgeMetric(model="omlx/x", base_url="http://judge:9/v1", api_key="k") + asyncio.run(judge.evaluate("q", "r")) + assert seen["base_url"] == "http://judge:9/v1" + assert seen["api_key"] == "k" + + def test_llm_judge_accepts_overall_score(self, monkeypatch) -> None: + _judge_reply(monkeypatch, {"overall_score": 9}) + judge = LLMJudgeMetric(criteria="c", model="omlx/x") + assert asyncio.run(judge.evaluate("q", "r")).score == pytest.approx(0.9) + + +class _Fixed(BaseMetric): + def __init__(self, name: str, score: float | None) -> None: + self.name = name + self._score = score + + async def evaluate(self, query, response, expected=None, context=None) -> EvalResult: + if self._score is None: + return EvalResult(self.name, 0.0, "down", {"evaluation_failed": True}) + return EvalResult(self.name, self._score, "ok") + + +class TestCompositeMetric: + def test_a_failed_judge_never_raises_the_score(self) -> None: + working = CompositeMetric( + [ + WeightedMetric("judge", _Fixed("judge", 0.8), 0.3), + WeightedMetric("format", _Fixed("format", 1.0), 0.7), + ] + ) + failing = CompositeMetric( + [ + WeightedMetric("judge", _Fixed("judge", None), 0.3), + WeightedMetric("format", _Fixed("format", 1.0), 0.7), + ] + ) + ok = asyncio.run(working.evaluate("q", "r")) + down = asyncio.run(failing.evaluate("q", "r")) + assert down.score < ok.score + assert down.metadata["failed_components"] == ["judge"] + + def test_negative_weights_are_rejected(self) -> None: + with pytest.raises(ValueError, match="higher-is-better"): + CompositeMetric( + [ + WeightedMetric("quality", _Fixed("q", 1.0), 0.9), + WeightedMetric("latency", LatencyMetric(), -0.1), + ] + ) + + +class TestMultiJudgePanel: + def _panel(self, scores: list[float | None], **kw: Any) -> MultiJudgePanel: + class _J(LocalJudgeMetric): + def __init__(self, idx: int, score: float | None) -> None: + super().__init__(name=f"j{idx}") + self._s = score + + async def evaluate_rich(self, *a: Any, **k: Any) -> Any: + from agentomatic.optimize.metrics import MetricResult + + result = MetricResult(score=self._s or 0.0, feedback="f", dimensions={}) + result._judge_failed = self._s is None + return result + + return MultiJudgePanel(judges=[_J(i, s) for i, s in enumerate(scores)], **kw) + + def test_weights_stay_with_their_judge_when_one_fails(self) -> None: + panel = self._panel([None, 0.5, 1.0], weights=[5, 1, 3]) + assert asyncio.run(panel.evaluate("q", "r")).score == pytest.approx(0.875) + + def test_zero_weight_survivors_fail_cleanly(self) -> None: + panel = self._panel([0.9, None], weights=[0, 1]) + assert asyncio.run(panel.evaluate("q", "r")).metadata["evaluation_failed"] + + def test_median_aggregation(self) -> None: + panel = self._panel([0.1, 0.8, 0.9], aggregation="median") + assert asyncio.run(panel.evaluate("q", "r")).score == pytest.approx(0.8) + + def test_unknown_aggregation_is_rejected(self) -> None: + with pytest.raises(ValueError, match="Unknown aggregation"): + self._panel([0.5], aggregation="vibes") + + +class TestDeepEvalDirection: + def test_lower_is_better_metrics_are_inverted(self) -> None: + from agentomatic.optimize.metrics import DeepEvalMetric + + class ToxicityMetric: # name matches deepeval's class + score = 0.9 + reason = "very toxic" + + def measure(self, test_case: Any) -> None: + pass + + pytest.importorskip("deepeval") + result = asyncio.run(DeepEvalMetric(ToxicityMetric()).evaluate("q", "r")) + assert result.score == pytest.approx(0.1) + + +class TestOtherMetrics: + def test_custom_metric_clamps_and_rejects_nan(self) -> None: + assert asyncio.run(CustomMetric(lambda *a: 7.0).evaluate("q", "r")).score == 1.0 + nan = asyncio.run(CustomMetric(lambda *a: float("nan")).evaluate("q", "r")) + assert nan.metadata["evaluation_failed"] + + def test_latency_is_read_from_the_scored_run(self) -> None: + metric = LatencyMetric(target_seconds=1.0, max_seconds=3.0) + + async def score() -> EvalResult: + with scoring_run(RunResult(query="q", response="r", duration_ms=2000.0)): + return await metric.evaluate("q", "r") + + assert asyncio.run(score()).score == pytest.approx(0.5) + + +class TestTrainingLoopSemantics: + def _agent(self) -> Any: + from types import SimpleNamespace + + return SimpleNamespace( + stop_training=False, compiled_config={}, invalidate_graph=lambda: None + ) + + def test_early_stopping_uses_keras_patience(self) -> None: + cb = EarlyStopping(monitor="val_loss", patience=1) + cb.set_agent(self._agent()) + cb.on_train_begin() + cb.on_epoch_end(0, {"val_loss": 0.5}) + cb.on_epoch_end(1, {"val_loss": 0.6}) + assert cb.agent.stop_training is True + assert cb.stopped_epoch == 1 + + def test_restore_best_restores_the_best_epoch_config(self) -> None: + agent = self._agent() + cb = EarlyStopping(monitor="val_loss", patience=5, restore_best=True) + cb.set_agent(agent) + cb.on_train_begin() + agent.compiled_config = {"system_prompt": "good"} + cb.on_epoch_end(0, {"val_loss": 0.2}) + agent.compiled_config = {"system_prompt": "worse"} + cb.on_epoch_end(1, {"val_loss": 0.4}) + cb.on_train_end() + assert agent.compiled_config == {"system_prompt": "good"} + + def test_auto_mode_checks_the_suffix(self) -> None: + assert EarlyStopping(monitor="gloss_quality").mode == "max" + assert EarlyStopping(monitor="val_loss").mode == "min" + + def test_optimize_callbacks_are_rejected_by_agent_fit(self) -> None: + from dataclasses import dataclass + + from agentomatic.agents import BaseGraphAgent + from agentomatic.optimize import OptimizeEarlyStopping + + @dataclass + class S: + q: str = "" + + class A(BaseGraphAgent[S]): + agent_name = "a" + + def build_graph(self) -> Any: + g = self.new_graph() + g.add_node("n", lambda s: s) + g.set_entry_point("n") + g.set_finish_point("n") + return g.compile() + + def input_to_state(self, d: dict[str, Any]) -> S: + return S() + + def state_to_output(self, s: S) -> dict[str, Any]: + return {"response": "x"} + + agent = A() + agent.compile(metrics=[CallableMetric("m", lambda e, p: 1.0)]) + with pytest.raises(TypeError, match="PromptFitter"): + agent.fit( + [AgentExample(input={"current_query": "q"})], callbacks=[OptimizeEarlyStopping()] + ) + + def test_crashed_examples_do_not_pass(self) -> None: + assert not ExampleResult(example_id="x", error="boom").passed + assert ExampleResult(example_id="x", scores={"m": 0.9}).passed + + +class TestJudgeCallsPerExample: + def test_one_judge_call_per_example_across_wrappers(self) -> None: + calls: list[str] = [] + + class _Judge(BaseMetric): + name = "judge" + + async def evaluate(self, query, response, expected=None, context=None): + calls.append(response) + return EvalResult("judge", 0.5, "ok") + + from agentomatic.agents import MetricLoss + from agentomatic.agents import WeightedMetric as AgentWeighted + + judge = _Judge() + example = AgentExample(id="e", input={"current_query": "q"}) + prediction = {"response": "same answer"} + OptimizeMetricAdapter(judge).score(example, prediction) + AgentWeighted([("judge", judge, 1.0)]).score(example, prediction) + MetricLoss(judge).compute(example, prediction) + assert calls == ["same answer"] + + +def test_duplicate_metric_names_are_rejected() -> None: + from dataclasses import dataclass + + from agentomatic.agents import BaseGraphAgent + + @dataclass + class S: + q: str = "" + + class A(BaseGraphAgent[S]): + agent_name = "a" + + def build_graph(self) -> Any: + g = self.new_graph() + g.add_node("n", lambda s: s) + g.set_entry_point("n") + g.set_finish_point("n") + return g.compile() + + def input_to_state(self, d: dict[str, Any]) -> S: + return S() + + def state_to_output(self, s: S) -> dict[str, Any]: + return {} + + metric = CallableMetric("quality", lambda e, p: 1.0) + with pytest.raises(ValueError, match="unique"): + A().compile(metrics=[metric, CallableMetric("quality", lambda e, p: 0.5)]) + + +def test_run_sync_reuses_one_loop_inside_a_running_loop() -> None: + from agentomatic.async_utils import run_sync + + loops: set[int] = set() + + async def probe() -> int: + loops.add(id(asyncio.get_running_loop())) + return 1 + + async def main() -> list[int]: + return [run_sync(probe()) for _ in range(3)] + + assert asyncio.run(main()) == [1, 1, 1] + assert len(loops) == 1 + + +def test_rewrite_text_keeps_fenced_blocks() -> None: + from agentomatic.optimize.briefing import extract_prompt_text + from agentomatic.optimize.llm_caller import _normalize_llm_text + + raw = "hmmOld:\n```\nold prompt\n```\n---\nNew prompt with:\n```json\n{}\n```" + text = _normalize_llm_text(raw) + assert "old prompt" in text and "```json" in text + assert extract_prompt_text(text) == "New prompt with:\n```json\n{}\n```" diff --git a/tests/test_optimization_bugs.py b/tests/test_optimization_bugs.py index a6a32e45..4a8efb27 100644 --- a/tests/test_optimization_bugs.py +++ b/tests/test_optimization_bugs.py @@ -520,9 +520,12 @@ async def evaluate(self, query, response, expected=None, context=None): expected_dict = {"answer": "42"} ex = self._make_example(expected=expected_dict) metric.score(ex, {"response": "r"}) - # expected must be the JSON representation of the dict + # The same reference every path uses (AgentExample.to_datapoint): the + # dict travels as its "Expected structured output" JSON section. + from agentomatic.optimize.metrics import _expected_structured + assert received_expected[0] is not None - assert json.loads(received_expected[0]) == expected_dict + assert _expected_structured(received_expected[0]) == expected_dict def test_score_does_not_raise_on_sub_metric_failure(self): class BrokenMetric(ExactMatchMetric): diff --git a/tests/test_train_api_and_holysheet.py b/tests/test_train_api_and_holysheet.py index 976caa20..b5b3234e 100644 --- a/tests/test_train_api_and_holysheet.py +++ b/tests/test_train_api_and_holysheet.py @@ -100,7 +100,9 @@ def test_build_default_metrics_shape(self) -> None: ) assert len(metrics) == 5 assert getattr(loss, "name", None) or True - assert fit_metric.name == "composite" + # Candidates are selected on the same blend the loss reports. + assert fit_metric.name == "objective" + assert fit_metric.metric is loss.metric def test_compile_fit_evaluate_pipeline(self) -> None: from agentomatic.agents.types import AgentDataset, AgentExample From 7a46ae70f5044f1e5c80d1ab4fc11df7a5255f62 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 19:20:01 +0000 Subject: [PATCH 05/16] fix(optimize): data augmentation actually adds usable, leak-free rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `prepare_dataset(augment=True)` often added nothing, and what it added was mislabelled: - One LLM call per strategy asked for dozens of examples under max_tokens=2000; the reply was cut off and the parser (clean JSON array only) returned zero rows without a warning. Generation is now seed-anchored: one seed + one strategy per call, a few variations each, looping until the target is met (bounded call budget). Replies are parsed whatever the wrapping — fences, prose, `{"examples": [...]}`, a single object, JSONL — and complete objects are salvaged from a truncated reply. Truncation (`finish_reason=length`) is logged. - Synthetic rows mirror their seed: the seed's input is copied with only the question replaced; label-preserving strategies (paraphrase, perturbation, …) keep the seed's expected_output and metadata (`must_include` etc.); others get the generated answer in the seed's schema or are dropped. The fabricated `{"content", "next_action": "Follow up with stakeholder."}` label is gone. - Only train rows seed augmentation and only train grows; generated questions that duplicate — or nearly duplicate — a validation, holdout or test question are discarded. - The endpoint is passed per call (no process-wide LLMCaller.configure); `dataset.metadata["augment_stats"]` reports requested/calls/parsed/ duplicates/near-duplicates/added per strategy, a shortfall is warned (`strict=True` raises), and `augmented` reflects rows actually added. - Persist-only never overwrites the seed file; `prefer_augmented` also finds `all_augmented.jsonl`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- src/agentomatic/optimize/eval_api.py | 12 +- src/agentomatic/optimize/synthesizer.py | 322 ++++++++++++++++++++---- src/agentomatic/optimize/train_api.py | 287 ++++++++++++++------- tests/fake_openai_server.py | 21 +- tests/test_dataset_augmentation.py | 203 +++++++++++++++ 5 files changed, 695 insertions(+), 150 deletions(-) create mode 100644 tests/test_dataset_augmentation.py diff --git a/src/agentomatic/optimize/eval_api.py b/src/agentomatic/optimize/eval_api.py index 38baa329..f7d711fb 100644 --- a/src/agentomatic/optimize/eval_api.py +++ b/src/agentomatic/optimize/eval_api.py @@ -159,10 +159,16 @@ def select_examples( def resolve_eval_dataset_path(agent_dir: Path, *, prefer_augmented: bool = False) -> Path: """Resolve default eval JSONL path under ``agent_dir/datasets``.""" datasets = Path(agent_dir) / "datasets" - augmented = datasets / "all.augmented.jsonl" seed = datasets / "all.jsonl" - if prefer_augmented and augmented.exists(): - return augmented + if prefer_augmented: + # ``prepare_dataset`` writes ``.augmented.jsonl``; older runs and + # hand-written scripts used ``all_augmented.jsonl``. + for name in ("all.augmented.jsonl", "all_augmented.jsonl"): + if (datasets / name).exists(): + return datasets / name + found = sorted(datasets.glob("*augmented*.jsonl")) + if found: + return found[0] return seed diff --git a/src/agentomatic/optimize/synthesizer.py b/src/agentomatic/optimize/synthesizer.py index 2159c974..5afcd1e4 100644 --- a/src/agentomatic/optimize/synthesizer.py +++ b/src/agentomatic/optimize/synthesizer.py @@ -54,7 +54,13 @@ class DataSynthesizer: Args: model: LLM model for generation (e.g., "ollama/mistral:7b"). temperature: Generation temperature (higher = more diverse). - api_base: Ollama/LLM API base URL. + api_base: Legacy, unused (kept for signature compatibility). + base_url: OpenAI-compatible endpoint for ``openai/`` / ``omlx/`` + models, used per call (not a process-wide default). + api_key: API key for ``base_url``. + max_tokens: Reply budget per call. Replies cut at the limit used to + parse to *zero* examples silently; they are now salvaged and + flagged. """ def __init__( @@ -62,10 +68,17 @@ def __init__( model: LLMSpec = "ollama/mistral:7b", temperature: float = 0.8, api_base: str = "http://localhost:11434", + *, + base_url: str | None = None, + api_key: str | None = None, + max_tokens: int = 4096, ): self.model = model self.temperature = temperature self.api_base = api_base + self.base_url = base_url + self.api_key = api_key + self.max_tokens = max(256, int(max_tokens)) # ================================================================= # Generate from scratch @@ -434,52 +447,8 @@ async def _generate_batch(self, prompt: str) -> list[DataPoint]: return self._parse_response(raw) def _parse_response(self, text: str) -> list[DataPoint]: - """Parse LLM response into DataPoints.""" - if not text: - return [] - - # Try to extract JSON array from the response - points: list[DataPoint] = [] - try: - # Find JSON array in the text - start = text.find("[") - end = text.rfind("]") - if start >= 0 and end > start: - json_str = text[start : end + 1] - items = json.loads(json_str) - - for item in items: - if isinstance(item, dict) and "query" in item: - points.append( - DataPoint( - query=item["query"], - expected_answer=item.get("expected_answer"), - context=item.get("context", []), - metadata={ - k: v - for k, v in item.items() - if k not in ("query", "expected_answer", "context") - }, - ) - ) - except (json.JSONDecodeError, ValueError) as exc: - logger.warning(f"Failed to parse LLM response as JSON: {exc}") - # Try line-by-line parsing as fallback - for line in text.split("\n"): - line = line.strip() - if line.startswith("{") and "query" in line: - try: - item = json.loads(line) - points.append( - DataPoint( - query=item["query"], - expected_answer=item.get("expected_answer"), - ) - ) - except json.JSONDecodeError: - continue - - return points + """Parse an LLM reply into DataPoints (see :func:`parse_generated_points`).""" + return parse_generated_points(text) async def _call_llm(self, prompt: str) -> str: """Call LLM API via the unified LLMCaller.""" @@ -487,8 +456,122 @@ async def _call_llm(self, prompt: str) -> str: self.model, prompt, temperature=self.temperature, + max_tokens=self.max_tokens, + base_url=self.base_url, + api_key=self.api_key, ) + # ================================================================= + # Seed-anchored augmentation (used by ``prepare_dataset``) + # ================================================================= + + async def augment_points( + self, + seeds: list[DataPoint], + *, + n_new: int, + strategies: list[str] | None = None, + per_call: int = 4, + existing_queries: list[str] | None = None, + protected_queries: list[str] | None = None, + near_duplicate_ratio: float = 0.9, + rng_seed: int = 0, + max_calls: int | None = None, + ) -> tuple[list[tuple[int, str, DataPoint]], dict[str, Any]]: + """Generate ``n_new`` variations anchored to individual seeds. + + One seed and one strategy per LLM call, asking for at most + ``per_call`` variations — a single call per strategy asking for dozens + of examples was routinely cut off at ``max_tokens`` and parsed to + nothing. Calls continue round-robin over (seed, strategy) pairs until + ``n_new`` unique examples exist or ``max_calls`` is spent. + + Args: + seeds: Seed points (training data only — never validation/test). + n_new: Number of new examples wanted. + strategies: Augmentation strategies (see :meth:`augment`). + per_call: Variations requested per call. + existing_queries: Queries already in the dataset (exact dedupe). + protected_queries: Validation/holdout/test queries: exact *and* + near-duplicates are dropped (a paraphrase of a test question + in train inflates every score measured on it). + near_duplicate_ratio: ``difflib`` ratio at or above which a + generated query counts as a near-duplicate of a protected one. + rng_seed: Seed for the (seed, strategy) schedule. + max_calls: Call budget (default ``2 × ceil(n_new / per_call) + 4``). + + Returns: + ``(items, stats)``: ``items`` are ``(seed_index, strategy, point)``; + ``stats`` counts calls, parsed, duplicates, near-duplicates, empty + or failed calls and additions per strategy. + """ + import difflib + import random + + strategies = [s for s in (strategies or ["paraphrase"]) if s in _STRATEGY_INSTRUCTIONS] + stats: dict[str, Any] = { + "requested": int(n_new), + "calls": 0, + "parsed": 0, + "duplicates": 0, + "near_duplicates": 0, + "empty_calls": 0, + "added": 0, + "by_strategy": {}, + } + if n_new <= 0 or not seeds or not strategies: + return [], stats + + def _norm(text: str) -> str: + return " ".join(str(text).lower().split()) + + seen = {_norm(q) for q in (existing_queries or [])} + seen.update(_norm(p.query) for p in seeds) + protected = [_norm(q) for q in (protected_queries or []) if q] + pairs = [(i, strat) for i in range(len(seeds)) for strat in strategies] + random.Random(rng_seed).shuffle(pairs) + per_call = max(1, int(per_call)) + budget = max_calls if max_calls is not None else 2 * -(-n_new // per_call) + 4 + + items: list[tuple[int, str, DataPoint]] = [] + cursor = 0 + while len(items) < n_new and stats["calls"] < budget: + seed_idx, strategy = pairs[cursor % len(pairs)] + cursor += 1 + k = min(per_call, n_new - len(items)) + prompt = _seed_prompt(seeds[seed_idx], strategy, k) + stats["calls"] += 1 + raw = await self._call_llm(prompt) + points = parse_generated_points(raw) + if not points: + stats["empty_calls"] += 1 + logger.warning( + "Augmentation call {} ({}, seed {}) produced no parsable examples — " + "reply starts: {!r}", + stats["calls"], + strategy, + seed_idx, + (raw or "")[:160], + ) + continue + stats["parsed"] += len(points) + for point in points[:k]: + key = _norm(point.query) + if not key or key in seen: + stats["duplicates"] += 1 + continue + if any( + difflib.SequenceMatcher(None, key, other).ratio() >= near_duplicate_ratio + for other in protected + ): + stats["near_duplicates"] += 1 + continue + seen.add(key) + items.append((seed_idx, strategy, point)) + stats["by_strategy"][strategy] = stats["by_strategy"].get(strategy, 0) + 1 + stats["added"] = len(items) + return items, stats + # ================================================================= # DeepEval Integration # ================================================================= @@ -782,3 +865,148 @@ async def red_team( """ synth = DataSynthesizer(model=model) return await synth.red_team(agent_description, n_samples, vulnerabilities) + + +# ===================================================================== +# Parsing and seed prompts (module level — shared and testable) +# ===================================================================== + +#: Strategies whose variations keep the seed's answer (and its labels). +LABEL_PRESERVING_STRATEGIES = frozenset( + {"paraphrase", "perturbation", "add_noise", "simplify", "formality_shift"} +) + +_STRATEGY_INSTRUCTIONS: dict[str, str] = { + "paraphrase": "Rephrase the question in different words, keeping the exact same intent.", + "perturbation": ( + "Rewrite the question the way a hurried user would: typos, informal wording, " + "abbreviations, fragments — same intent." + ), + "add_noise": "Add realistic noise (typos, filler words, punctuation slips) — same intent.", + "simplify": "Make the question shorter and plainer — same intent.", + "formality_shift": "Change the register (very formal or very casual) — same intent.", + "complicate": "Make the question longer and more detailed; answer it correctly.", + "expansion": "Ask a related follow-up question on the same topic; answer it correctly.", + "adversarial": ( + "Ask a tricky variant (ambiguity, false premise, negation, edge case); " + "give the correct answer." + ), + "edge_case": "Ask about an edge case or exception to the rule; give the correct answer.", +} + +_ITEM_LIST_KEYS = ("examples", "data", "items", "rows", "points", "variations", "results") + + +def _seed_prompt(seed: DataPoint, strategy: str, k: int) -> str: + """Build the one-seed augmentation prompt.""" + from agentomatic.optimize.metrics import plain_expected + + answer = plain_expected(seed.expected_answer) or "" + keep = strategy in LABEL_PRESERVING_STRATEGIES + seed_json = json.dumps({"query": seed.query, "expected_answer": answer}, ensure_ascii=False) + return ( + "You are a dataset augmentation expert.\n\n" + f"## Seed example\n{seed_json}\n\n" + f"## Task\n{_STRATEGY_INSTRUCTIONS[strategy]}\n" + f"Write {k} new, distinct variation(s) of the seed.\n" + + ( + "The expected_answer must stay exactly the seed's expected_answer.\n" + if keep + else "Give each variation its own correct expected_answer.\n" + ) + + "\nReply with ONLY a JSON array, no prose:\n" + '[{"query": "...", "expected_answer": "..."}]\n' + ) + + +def _item_to_point(item: dict[str, Any]) -> DataPoint | None: + """Map one generated JSON object onto a DataPoint (tolerant of key names).""" + query = item.get("query") or item.get("question") or item.get("input") + if isinstance(query, dict): + query = query.get("query") or query.get("current_query") or query.get("question") + if not isinstance(query, str) or not query.strip(): + return None + expected: Any = item.get("expected_answer") + for key in ("expected", "answer", "expected_output", "response"): + if expected is None: + expected = item.get(key) + if isinstance(expected, dict): + expected = json.dumps(expected, ensure_ascii=False) + context = item.get("context") if isinstance(item.get("context"), list) else [] + metadata = { + k: v + for k, v in item.items() + if k + not in { + "query", + "question", + "input", + "expected_answer", + "expected", + "answer", + "expected_output", + "response", + "context", + } + } + return DataPoint( + query=query.strip(), + expected_answer=str(expected) if expected is not None else None, + context=[str(c) for c in context], + metadata=metadata, + ) + + +def parse_generated_points(text: str) -> list[DataPoint]: + """Parse generated examples from an LLM reply, however it is wrapped. + + Accepts a JSON array; an object wrapping one (``{"examples": [...]}``); + a single object; fenced blocks; prose around the JSON; one object per + line; and a reply cut off mid-array (every *complete* object before the + cut is kept). Each item needs a ``query`` (or ``question``). + + Args: + text: Raw LLM reply. + + Returns: + The parsed points (possibly empty). + """ + from agentomatic.providers.jsonutil import extract_json + + if not text or not text.strip(): + return [] + value = extract_json(text, expect="array") + items: list[Any] = [] + if isinstance(value, list): + items = value + elif isinstance(value, dict): + wrapped = next((value[k] for k in _ITEM_LIST_KEYS if isinstance(value.get(k), list)), None) + items = wrapped if wrapped is not None else [value] + points = [p for p in (_item_to_point(i) for i in items if isinstance(i, dict)) if p] + if isinstance(value, list) and points: + return points + # Salvage: decode every complete object in the text (truncated arrays, + # JSONL, objects interleaved with prose). A lone object may just be the + # first line of a JSONL reply, so salvage runs for that case too. + decoder = json.JSONDecoder() + idx = text.find("{") + salvaged: list[DataPoint] = [] + while idx != -1: + try: + obj, end = decoder.raw_decode(text, idx) + except json.JSONDecodeError: + idx = text.find("{", idx + 1) + continue + if isinstance(obj, dict): + point = _item_to_point(obj) + if point is not None: + salvaged.append(point) + else: + inner = next( + (obj[k] for k in _ITEM_LIST_KEYS if isinstance(obj.get(k), list)), None + ) + for item in inner or []: + if isinstance(item, dict) and (p := _item_to_point(item)): + salvaged.append(p) + idx = text.find("{", end) + return salvaged if len(salvaged) > len(points) else points diff --git a/src/agentomatic/optimize/train_api.py b/src/agentomatic/optimize/train_api.py index 75994187..e6576d6a 100644 --- a/src/agentomatic/optimize/train_api.py +++ b/src/agentomatic/optimize/train_api.py @@ -369,47 +369,92 @@ def _model_spec(entry: Any) -> str: return f"{mapped}/{entry.model}" -def _datapoint_to_example(dp: Any, *, idx: int, split: str = "train") -> Any: - """Convert an optimize ``DataPoint`` into an ``AgentExample``.""" +#: Input keys that carry the user question (replaced in an augmented copy). +_QUERY_KEYS = ("current_query", "query", "question", "request") + + +def _augmented_example(seed: Any, dp: Any, *, strategy: str, idx: int) -> Any | None: + """Build a synthetic ``AgentExample`` that mirrors its seed's schema. + + The seed's ``input`` is copied with only the question replaced, so extra + input fields (context, ids, custom keys) survive. The label follows the + strategy: + + * label-preserving strategies (paraphrase, perturbation, …) keep the + seed's ``expected_output`` **and** metadata (``must_include``, rubric + hints) — the answer is the same; + * other strategies (expansion, adversarial, …) take the generated answer, + shaped like the seed's ``expected_output``. A row whose answer cannot + be expressed in the seed's schema is dropped (never padded with + invented fields). + + Args: + seed: The seed ``AgentExample``. + dp: The generated ``DataPoint``. + strategy: Augmentation strategy that produced it. + idx: Running index for the new id. + + Returns: + The new example, or ``None`` when it cannot match the seed schema. + """ from agentomatic.agents.types import AgentExample + from agentomatic.optimize.metrics import plain_expected + from agentomatic.optimize.synthesizer import LABEL_PRESERVING_STRATEGIES - expected_raw = getattr(dp, "expected_answer", None) - expected: dict[str, Any] | None - if isinstance(expected_raw, dict): - expected = dict(expected_raw) - elif isinstance(expected_raw, str) and expected_raw.strip(): - try: - parsed = json.loads(expected_raw) - expected = parsed if isinstance(parsed, dict) else {"content": expected_raw} - except (json.JSONDecodeError, TypeError): - expected = {"content": expected_raw, "next_action": "Follow up with stakeholder."} + query = str(getattr(dp, "query", "") or "").strip() + if not query: + return None + inp = dict(seed.input or {}) + replaced = False + for key in _QUERY_KEYS: + if key in inp: + inp[key] = query + replaced = True + if not replaced: + inp["current_query"] = query + + seed_expected = seed.expected_output + preserving = strategy in LABEL_PRESERVING_STRATEGIES + if preserving: + expected = dict(seed_expected) if isinstance(seed_expected, dict) else seed_expected + metadata = dict(seed.metadata or {}) else: - expected = {"content": "", "next_action": ""} - - query = str(getattr(dp, "query", "") or "") - meta = dict(getattr(dp, "metadata", None) or {}) - meta.setdefault("source", "augment") - meta.setdefault("split", split) - ctx = getattr(dp, "context", None) or [] - inp: dict[str, Any] = { - "current_query": query, - "query": query, - "question": query, - } - if ctx: - # Prefer structured context when the synthesizer echoed JSON. + raw = plain_expected(getattr(dp, "expected_answer", None)) or "" + parsed: Any = None try: - inp["context"] = json.loads(ctx[0]) if isinstance(ctx[0], str) else ctx[0] - except (json.JSONDecodeError, TypeError, IndexError): - inp["context"] = ctx - + parsed = json.loads(raw) if raw.strip().startswith("{") else None + except (json.JSONDecodeError, TypeError): + parsed = None + text_keys = ( + [k for k, v in seed_expected.items() if isinstance(v, str)] + if isinstance(seed_expected, dict) + else [] + ) + if isinstance(parsed, dict) and ( + not isinstance(seed_expected, dict) or set(seed_expected) <= set(parsed) + ): + expected = parsed + elif ( + raw.strip() + and isinstance(seed_expected, dict) + and len(seed_expected) == 1 + and text_keys + ): + expected = {text_keys[0]: raw.strip()} + elif raw.strip() and seed_expected is None: + expected = {"response": raw.strip()} + else: + return None # cannot honour the seed schema without inventing fields + metadata = {} + metadata.update({"source": "augment", "strategy": strategy, "parent_id": seed.id}) return AgentExample( - id=f"aug_{idx:04d}", + id=f"{seed.id or 'seed'}~aug{idx:04d}", input=inp, expected_output=expected, - metadata=meta, - tags=["augmented"], - split=split, + metadata=metadata, + rubric=dict(seed.rubric or {}), + tags=[*list(seed.tags or []), "augmented"], + split="train", ) @@ -425,102 +470,155 @@ def prepare_dataset( strategies: list[str] | None = None, llm_base_url: str | None = None, llm_api_key: str | None = None, + per_call: int = 4, + max_tokens: int = 4096, + strict: bool = False, ) -> tuple[Any, Path | None]: """Optionally augment (and persist) an :class:`AgentDataset`. + Augmentation only ever grows the **train** split, seeded from train rows: + validation / holdout / test stay untouched, and generated questions that + duplicate — or nearly duplicate — any of them are discarded (a paraphrase + of a test question in train inflates every score measured on it). + + Every run records ``dataset.metadata["augment_stats"]`` (requested, LLM + calls, parsed, duplicates, near-duplicates, empty calls, added per + strategy) and warns when fewer rows than requested were added. + Args: dataset: Seed ``AgentDataset``. augment: Run LLM augmentation when True. - n_examples: Target total size (keeps originals + fills with synth). + n_examples: Target **total** size of the dataset after augmentation + (default: 3× the seed size). New rows are added to train only. persist: Write the resulting dataset to disk. persist_path: Destination JSONL path. - seed_path: Original seed path (used to derive default persist path). - model: Augmentation LLM spec. - strategies: Augmentation strategies. - llm_base_url / llm_api_key: Optional OpenAI-compatible routing. + seed_path: Original seed path (derives the default persist path, + ``.augmented.jsonl``; the seed file is never overwritten). + model: Augmentation LLM spec (``omlx/…``, ``openai/…``, ``ollama/…``). + strategies: Augmentation strategies. Label-preserving ones + (``paraphrase``, ``perturbation``, ``add_noise``, ``simplify``, + ``formality_shift``) keep the seed's answer and metadata; the + others (``expansion``, ``adversarial``, ``edge_case``, + ``complicate``) get a generated answer. + llm_base_url / llm_api_key: OpenAI-compatible endpoint for ``model`` + (used for these calls only — no process-wide side effect). + per_call: Variations requested per LLM call (small = not truncated). + max_tokens: Reply budget per LLM call. + strict: Raise when fewer rows than requested could be added. Returns: ``(dataset, written_path_or_none)``. + + Raises: + RuntimeError: With ``strict=True``, when augmentation fell short. """ from agentomatic.agents import AgentDataset from agentomatic.async_utils import run_sync - from agentomatic.optimize.dataset import Dataset - from agentomatic.optimize.llm_caller import LLMCaller from agentomatic.optimize.synthesizer import DataSynthesizer written: Path | None = None out_ds = dataset if augment: - if llm_base_url or llm_api_key: - LLMCaller.configure(base_url=llm_base_url, api_key=llm_api_key) - - seed_n = max(len(dataset.examples), 1) - target = int(n_examples) if n_examples and n_examples > 0 else seed_n * 3 - need = max(0, target - seed_n) + seeds = list(dataset.train) + protected = [ + e.to_datapoint().query + for e in [*dataset.validation, *getattr(dataset, "holdout", []), *dataset.test] + ] + target = int(n_examples) if n_examples and n_examples > 0 else len(dataset.examples) * 3 + need = max(0, target - len(dataset.examples)) strategies = list(strategies or ["paraphrase", "perturbation", "expansion"]) - seed_used = min(10, seed_n) - # Rough inverse of synthesizer yield: ~strategies × (M // strategies) × seeds - multiplier = max(1, (need + max(seed_used, 1) - 1) // max(seed_used, 1)) - - logger.info( - "Augmenting dataset: seed={} target≈{} multiplier={} strategies={}", - seed_n, - target, - multiplier, - strategies, - ) - - train_examples = list(dataset.train) or list(dataset.examples) - seed_opt = Dataset(points=[e.to_datapoint() for e in train_examples]) - synth = DataSynthesizer(model=model) - - async def _run() -> Dataset: - return await synth.augment( - seed_opt, - strategies=strategies, - multiplier=multiplier, + stats: dict[str, Any] = {"requested": need, "added": 0, "target_total": target} + new_examples: list[Any] = [] + if not seeds: + logger.warning( + "Augmentation skipped: the dataset has no train split. Only training " + "rows may seed synthetic data — validation/test would leak into training." ) - - try: - augmented_opt = run_sync(_run()) - except Exception as exc: # noqa: BLE001 - logger.warning("Dataset augmentation failed ({}); using seed dataset", exc) - augmented_opt = seed_opt - - seed_queries = {p.query for p in seed_opt.points} - merged = list(dataset.examples) - for dp in augmented_opt.points: - if dp.query in seed_queries: - continue - merged.append(_datapoint_to_example(dp, idx=len(merged), split="train")) - seed_queries.add(dp.query) - if len(merged) >= target: - break + elif need == 0: + logger.info( + "Augmentation skipped: dataset already has {} ≥ {} examples", + len(dataset.examples), + target, + ) + else: + logger.info( + "Augmenting train split: {} seed(s) → +{} example(s) (target total {}) " + "strategies={} model={}", + len(seeds), + need, + target, + strategies, + model, + ) + synth = DataSynthesizer( + model=model, base_url=llm_base_url, api_key=llm_api_key, max_tokens=max_tokens + ) + seed_points = [e.to_datapoint() for e in seeds] + try: + items, stats = run_sync( + synth.augment_points( + seed_points, + n_new=need, + strategies=strategies, + per_call=per_call, + existing_queries=[e.to_datapoint().query for e in dataset.examples], + protected_queries=protected, + ) + ) + except Exception as exc: # noqa: BLE001 + logger.warning("Dataset augmentation failed ({}); using the seed dataset", exc) + items, stats = [], {**stats, "error": str(exc)} + dropped = 0 + for seed_idx, strategy, point in items: + example = _augmented_example( + seeds[seed_idx], point, strategy=strategy, idx=len(new_examples) + ) + if example is None: + dropped += 1 + continue + new_examples.append(example) + stats = {**stats, "target_total": target, "schema_mismatch": dropped} + stats["added"] = len(new_examples) + + if augment and stats.get("added", 0) < stats.get("requested", 0): + message = ( + f"Augmentation added {stats.get('added', 0)}/{stats.get('requested', 0)} " + f"requested examples (stats: { {k: v for k, v in stats.items() if k != 'by_strategy'} })." + ) + if strict: + raise RuntimeError(message) + logger.warning(message) out_ds = AgentDataset( name=getattr(dataset, "name", "dataset"), - examples=merged, + examples=[*dataset.examples, *new_examples], metadata={ **dict(getattr(dataset, "metadata", None) or {}), - "augmented": True, + "augmented": bool(new_examples), "augment_target": target, + "augment_stats": stats, }, ) - logger.info("Augmented dataset: {} → {} examples", seed_n, len(out_ds.examples)) + logger.info( + "Dataset: {} → {} examples (train {} → {})", + len(dataset.examples), + len(out_ds.examples), + len(seeds), + len(out_ds.train), + ) if persist: if persist_path is not None: dest = Path(persist_path) elif seed_path is not None: seed = Path(seed_path) - dest = seed.with_name( - seed.stem + (".augmented.jsonl" if augment else seed.suffix or ".jsonl") - ) - if not augment: - dest = seed # overwrite / rewrite seed when persist-only + # Never overwrite the seed file (persist-only used to rewrite it + # and drop any keys AgentExample does not model). + suffix = ".augmented.jsonl" if augment else ".prepared.jsonl" + dest = seed.with_name(seed.stem + suffix) else: - dest = Path("datasets") / "all.augmented.jsonl" + dest = Path("datasets") / ("all.augmented.jsonl" if augment else "all.prepared.jsonl") dest.parent.mkdir(parents=True, exist_ok=True) out_ds.to_jsonl(dest) written = dest @@ -1127,7 +1225,8 @@ def run_train( model=model, rewrite_model=rewrite_model, optimizer=config.optimizer, - augmented=bool(config.augment), + # What actually happened, not what was asked for. + augmented=bool((getattr(dataset, "metadata", None) or {}).get("augmented")), persist_path=persist_written, agent_name=config.agent_name, ) diff --git a/tests/fake_openai_server.py b/tests/fake_openai_server.py index 4fd5949a..05ca0cf7 100644 --- a/tests/fake_openai_server.py +++ b/tests/fake_openai_server.py @@ -20,6 +20,7 @@ from __future__ import annotations +import itertools import json import re import socket @@ -36,6 +37,7 @@ ) _VAGUE_ANSWER = "Thanks for reaching out! Our team is happy to help with that." +_AUGMENT_COUNTER = itertools.count(1) def _words(text: str) -> set[str]: @@ -76,15 +78,22 @@ def _judge_reply(prompt: str) -> str: def _augment_reply(prompt: str) -> str: - match = re.search(r"```json\s*\n(.*?)```", prompt, re.S) - seeds = json.loads(match.group(1)) if match else [] + """Answer a one-seed augmentation prompt with ``k`` distinct variations.""" + seed_match = re.search(r"## Seed example\n(\{.*?\})\n", prompt, re.S) + seed = json.loads(seed_match.group(1)) if seed_match else {"query": "question"} + count = re.search(r"Write (\d+) new", prompt) + k = int(count.group(1)) if count else 1 + keep = "must stay exactly the seed's expected_answer" in prompt + query = str(seed.get("query", "")).rstrip("?") out = [] - for i, seed in enumerate(seeds): - query = str(seed.get("query", "")).rstrip("?") + for i in range(k): + n = next(_AUGMENT_COUNTER) out.append( { - "query": f"Quick question {i}: {query.lower()}?", - "expected_answer": seed.get("expected_answer", ""), + "query": f"Variant {n}: {query.lower()}?", + "expected_answer": seed.get("expected_answer", "") + if keep + else f"Generated answer {n}", } ) return json.dumps(out) diff --git a/tests/test_dataset_augmentation.py b/tests/test_dataset_augmentation.py new file mode 100644 index 00000000..a61942cf --- /dev/null +++ b/tests/test_dataset_augmentation.py @@ -0,0 +1,203 @@ +# pyright: reportMissingParameterType=none +"""``prepare_dataset(augment=True)`` must actually add usable, leak-free rows. + +Reported: "prompt optimization doesn't augment the data". Causes found: + +* one call per strategy asked a local model for dozens of examples under + ``max_tokens=2000``; the reply was cut off and parsed to *zero* rows with + no warning — only a clean, complete JSON array was understood; +* synthetic rows got a fabricated ``{"content": …, "next_action": "Follow up + with stakeholder."}`` label whatever the seed schema was, and lost the + seed's metadata — so every metric scored them wrong; +* rows were only de-duplicated against train seeds (copies of test questions + leaked into train), and without a train split, test rows became seeds; +* ``LLMCaller.configure`` was left set process-wide; ``augmented=True`` was + reported even when nothing was added. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + +import pytest + +from agentomatic.agents import AgentDataset, AgentExample +from agentomatic.optimize import load_data, prepare_dataset +from agentomatic.optimize.llm_caller import LLMCaller +from agentomatic.optimize.synthesizer import parse_generated_points + +sys.path.insert(0, str(Path(__file__).parent)) + +from fake_openai_server import FakeOpenAIServer # noqa: E402 + +EXAMPLE_DATASET = ( + Path(__file__).resolve().parents[1] + / "examples" + / "prompt_optimization" + / "datasets" + / "support.jsonl" +) + + +@pytest.fixture(scope="module") +def server(): + with FakeOpenAIServer() as srv: + yield srv + + +class TestTheReportedCall: + def test_the_example_script_call_adds_rows_and_persists(self, server, tmp_path) -> None: + """The exact ``prepare_dataset`` call from the user's training script.""" + dataset = load_data(EXAMPLE_DATASET) + out, written = prepare_dataset( + dataset, + seed_path=EXAMPLE_DATASET, + augment=True, + n_examples=30, + persist=True, + persist_path=tmp_path / "all_augmented.jsonl", + model="omlx/fake-model", + llm_base_url=server.base_url, + llm_api_key=None, + strategies=["expansion", "paraphrase"], + ) + stats = out.metadata["augment_stats"] + assert len(out.examples) == 30 + assert stats["added"] == 14 and out.metadata["augmented"] is True + assert set(stats["by_strategy"]) == {"expansion", "paraphrase"} + assert written == tmp_path / "all_augmented.jsonl" + assert len(written.read_text().splitlines()) == 30 + + def test_only_train_grows(self, server) -> None: + dataset = load_data(EXAMPLE_DATASET) + out, _ = _augment(dataset, server, n_examples=24) + assert len(out.train) == len(dataset.train) + 8 + assert [e.id for e in out.validation] == [e.id for e in dataset.validation] + assert [e.id for e in out.test] == [e.id for e in dataset.test] + + def test_no_process_wide_endpoint_side_effect(self, server) -> None: + before = (LLMCaller._default_base_url, LLMCaller._default_api_key) # noqa: SLF001 + _augment(load_data(EXAMPLE_DATASET), server, n_examples=20) + assert (LLMCaller._default_base_url, LLMCaller._default_api_key) == before # noqa: SLF001 + + +class TestRowsMirrorTheSeed: + def test_label_preserving_rows_keep_answer_and_metadata(self, server) -> None: + dataset = load_data(EXAMPLE_DATASET) + out, _ = _augment(dataset, server, n_examples=20, strategies=["paraphrase"]) + seeds = {e.id: e for e in dataset.examples} + new = [e for e in out.examples if e.metadata.get("source") == "augment"] + assert new + for example in new: + seed = seeds[example.metadata["parent_id"]] + assert example.expected_output == seed.expected_output + assert example.metadata["must_include"] == seed.metadata["must_include"] + assert set(example.input) == set(seed.input) + assert example.split == "train" + + def test_generated_answers_use_the_seed_schema(self, server) -> None: + out, _ = _augment( + load_data(EXAMPLE_DATASET), server, n_examples=20, strategies=["expansion"] + ) + new = [e for e in out.examples if e.metadata.get("source") == "augment"] + assert new + for example in new: + assert set(example.expected_output) == {"response"} + assert "next_action" not in json.dumps(example.to_dict()) + assert example.expected_output["response"].startswith("Generated answer") + + +class TestLeakage: + def test_near_duplicates_of_test_questions_are_dropped(self, server) -> None: + train = AgentExample( + id="t", input={"current_query": "How do I reset my password?"}, split="train" + ) + test = AgentExample( + id="x", + input={"current_query": "Variant 999: how do i reset my password?"}, + split="test", + ) + dataset = AgentDataset(examples=[train, test]) + out, _ = _augment(dataset, server, n_examples=4, strategies=["paraphrase"]) + stats = out.metadata["augment_stats"] + # Every variant the fake model writes is a near-copy of the test question. + assert stats["near_duplicates"] >= 1 + assert not [e for e in out.examples if e.metadata.get("source") == "augment"] + + def test_without_a_train_split_nothing_is_generated(self, server) -> None: + dataset = AgentDataset( + examples=[AgentExample(id="v", input={"current_query": "q"}, split="validation")] + ) + out, _ = _augment(dataset, server, n_examples=5) + assert len(out.examples) == 1 + assert out.metadata["augmented"] is False + + def test_strict_mode_raises_when_it_falls_short(self, server) -> None: + dataset = AgentDataset( + examples=[AgentExample(id="v", input={"current_query": "q"}, split="validation")] + ) + with pytest.raises(RuntimeError, match="Augmentation added 0/"): + _augment(dataset, server, n_examples=5, strict=True) + + +class TestPersistence: + def test_persist_only_never_overwrites_the_seed_file(self, tmp_path) -> None: + seed = tmp_path / "all.jsonl" + seed.write_text(EXAMPLE_DATASET.read_text()) + before = seed.read_text() + _, written = prepare_dataset(load_data(seed), persist=True, seed_path=seed) + assert seed.read_text() == before + assert written == tmp_path / "all.prepared.jsonl" + + +class TestReplyParsing: + ARRAY = '[{"query": "a?", "expected_answer": "x"}, {"query": "b?", "expected_answer": "y"}]' + + @pytest.mark.parametrize( + ("reply", "count"), + [ + (ARRAY, 2), + ("Sure [ok]:\n```json\n" + ARRAY + "\n```\nHope [this] helps", 2), + ('{"examples": ' + ARRAY + "}", 2), + ('{"query": "a?", "expected_answer": "x"}', 1), + ('{"query": "a?"}\n{"query": "b?"}', 2), + (ARRAY[:-30], 1), + ("[x]" + ARRAY, 2), + ("no json at all", 0), + ], + ) + def test_reply_shapes(self, reply: str, count: int) -> None: + assert len(parse_generated_points(reply)) == count + + def test_truncated_replies_are_salvaged_during_augmentation(self, monkeypatch) -> None: + async def truncated(*args: Any, **kwargs: Any) -> str: + return '[{"query": "What is the refund window?", "expected_answer": "30 days"}, {"query": "Wha' + + monkeypatch.setattr(LLMCaller, "call", staticmethod(truncated)) + dataset = AgentDataset( + examples=[ + AgentExample( + id="s", + input={"current_query": "Refund window?"}, + expected_output={"response": "30 days"}, + split="train", + ) + ] + ) + out, _ = prepare_dataset(dataset, augment=True, n_examples=2, model="omlx/x") + assert len(out.examples) == 2 + + +def _augment(dataset: Any, server: FakeOpenAIServer, **kwargs: Any) -> tuple[Any, Any]: + kwargs.setdefault("strategies", ["paraphrase", "expansion"]) + return prepare_dataset( + dataset, + augment=True, + model="omlx/fake-model", + llm_base_url=server.base_url, + llm_api_key="x", + **kwargs, + ) From 735f9c5d8ac5da927523fbcbc46063655fd65651 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 19:44:30 +0000 Subject: [PATCH 06/16] feat(optimize): fit reports show what changed and whether it helped MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The training report had numbers but no prompts. Causes and fixes: * Every prompt panel was a HolySheet Accordion, which the bundled viewer never renders, so prompts, few-shot demos and per-example details were hidden. Panels are now flattened into always-visible blocks. * With epochs > 1 only the last epoch's PromptFitResult was reported. Its baseline was a prompt an earlier epoch had already improved, so the report compared the final prompt with itself and said "no improvement". merge_fit_results() spans the original prompt to the final one. agent.fit() now returns History.fit_results (one result per epoch), and generate_fit_report() accepts that History, a list of results, or the agent. * New sections at the top of the report: - verdict: validation, held-out gate and test, before and after; - test scoreboard; - initial-to-final prompt diff, with every accepted change in order; - every candidate with its decision and reason; - per-example answers and scores, before and after; - data, augmentation and fitter settings. A JSON sidecar carries the same data. * Diffs wrap long single-line prompts, so they show the sentences that changed. * The eval report table lists whatever metrics were compiled, not a fixed judge/f1/keywords set. * The deployment rollout rendered as "—" because it read __dict__ on a slots dataclass. * run_train (train_and_report) now scores the held-out split before and after fit (TrainConfig.evaluate_baseline). It applies and reports the merged result. * Augmentation rotates strategies call by call, so a short run still mixes them. * Fixed three mypy errors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- src/agentomatic/agents/base.py | 4 + src/agentomatic/agents/history.py | 5 + src/agentomatic/optimize/__init__.py | 2 + src/agentomatic/optimize/config.py | 10 + src/agentomatic/optimize/fitter.py | 49 +- src/agentomatic/optimize/fitter_optimizers.py | 3 +- src/agentomatic/optimize/holysheet_reports.py | 844 +++++++++++++----- src/agentomatic/optimize/report.py | 272 +++++- src/agentomatic/optimize/synthesizer.py | 14 +- src/agentomatic/optimize/train_api.py | 46 +- tests/test_fit_report_content.py | 321 +++++++ tests/test_train_api_and_holysheet.py | 16 +- 12 files changed, 1341 insertions(+), 245 deletions(-) create mode 100644 tests/test_fit_report_content.py diff --git a/src/agentomatic/agents/base.py b/src/agentomatic/agents/base.py index b3d4c45d..ec914d03 100644 --- a/src/agentomatic/agents/base.py +++ b/src/agentomatic/agents/base.py @@ -843,6 +843,9 @@ def fit( ) self.history = history self.stop_training = False + # Per-epoch PromptFitResults (filled by PromptFitterBridge) — reset so + # a second fit() call does not report the previous run's epochs. + self._fit_results: list[Any] = [] callbacks = list(callbacks or []) for cb in callbacks: @@ -911,6 +914,7 @@ def fit( break finally: self._fit_optimize_options = None + history.fit_results = list(self._fit_results) for cb in callbacks: cb.on_train_end() diff --git a/src/agentomatic/agents/history.py b/src/agentomatic/agents/history.py index d6aa3839..7d123957 100644 --- a/src/agentomatic/agents/history.py +++ b/src/agentomatic/agents/history.py @@ -39,12 +39,17 @@ class History: ``"exact_match"``) to the list of values, one per epoch. epoch: The list of epoch indices recorded. params: Training parameters (epochs, optimizer, metric names, …). + fit_results: One ``PromptFitResult`` per epoch whose optimizer was a + ``PromptFitterBridge`` (empty otherwise). Pass the whole + ``History`` to :func:`agentomatic.optimize.generate_fit_report` + to see the original prompt → final prompt across all epochs. """ def __init__(self, params: dict[str, Any] | None = None) -> None: self.history: dict[str, list[float]] = {} self.epoch: list[int] = [] self.params: dict[str, Any] = dict(params or {}) + self.fit_results: list[Any] = [] def record(self, epoch: int, logs: dict[str, float]) -> None: """Append one epoch's ``logs`` to the history.""" diff --git a/src/agentomatic/optimize/__init__.py b/src/agentomatic/optimize/__init__.py index 266f8766..7b51d6cc 100644 --- a/src/agentomatic/optimize/__init__.py +++ b/src/agentomatic/optimize/__init__.py @@ -227,6 +227,7 @@ generate_eval_report, generate_fit_report, generate_html_report, + merge_fit_results, ) from agentomatic.optimize.resources import ResourceBundle, ResourceRegistry from agentomatic.optimize.reward import ( @@ -527,6 +528,7 @@ "LatencyMetric", "CostMetric", "generate_fit_report", + "merge_fit_results", ] # Aliases for Optimize* prefixed names diff --git a/src/agentomatic/optimize/config.py b/src/agentomatic/optimize/config.py index b0905928..527f24dd 100644 --- a/src/agentomatic/optimize/config.py +++ b/src/agentomatic/optimize/config.py @@ -349,6 +349,13 @@ class PromptFitResult: """Why the inner optimize loop stopped early, if it did.""" dataset_sizes: dict[str, int] = field(default_factory=dict) """Dataset cardinalities used during fit (train/val/holdout/test).""" + baseline_examples: list[dict[str, Any]] = field(default_factory=list) + """Per-example validation results of the baseline (query, expected, + response, score, dimensions, feedback) — truncated, capped.""" + best_examples: list[dict[str, Any]] = field(default_factory=list) + """Per-example validation results of the best config (same examples).""" + settings: dict[str, Any] = field(default_factory=dict) + """Fitter knobs used for this run (optimizer, budget, generalization gates…).""" # -- convenience properties ------------------------------------------ @@ -503,6 +510,9 @@ def to_dict(self) -> dict[str, Any]: "optimizer_name": self.optimizer_name, "early_stop_reason": self.early_stop_reason, "dataset_sizes": dict(self.dataset_sizes), + "baseline_examples": list(self.baseline_examples), + "best_examples": list(self.best_examples), + "settings": dict(self.settings), "deployment_recommendation": ( self.deployment_recommendation.to_dict() if self.deployment_recommendation diff --git a/src/agentomatic/optimize/fitter.py b/src/agentomatic/optimize/fitter.py index 0cf768bd..4db5e7c1 100644 --- a/src/agentomatic/optimize/fitter.py +++ b/src/agentomatic/optimize/fitter.py @@ -175,7 +175,7 @@ async def _callable( prompt_override: str | None = None, context: list | None = None, invoke: dict | None = None, - ) -> str: + ) -> dict[str, Any] | str: input_data: dict[str, Any] = {"current_query": query} if invoke: input_data.update({k: v for k, v in invoke.items() if k != "current_query"}) @@ -273,6 +273,31 @@ async def _call_with_swapped_attributes( return _callable +def _compact_examples(details: list[dict[str, Any]], limit: int = 50) -> list[dict[str, Any]]: + """Per-example results trimmed for reports (question, answer, score, why).""" + from agentomatic.optimize.metrics import plain_expected + + rows: list[dict[str, Any]] = [] + for d in details[:limit]: + feedback = d.get("feedback") or d.get("error") or "" + rows.append( + { + "query": str(d.get("query", ""))[:500], + "expected": str(plain_expected(d.get("expected")) or "")[:500], + "response": str(d.get("response", ""))[:800], + "score": round(float(d.get("avg_score", 0.0) or 0.0), 4), + "dimensions": { + k: round(float(v), 4) + for k, v in (d.get("dimensions") or {}).items() + if isinstance(v, (int, float)) + }, + "feedback": str(feedback)[:500], + "failed": bool(d.get("error")), + } + ) + return rows + + # ===================================================================== # PromptFitter # ===================================================================== @@ -703,6 +728,7 @@ async def fit( fit_valset = valset holdout_set: Dataset | None = testset + holdout_source_label = "testset argument" if testset is not None else "none" if holdout_set is None: def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: @@ -732,6 +758,7 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: if holdout_source == "valset": fit_valset = Dataset.from_list(_as_dicts(fit_pts)) holdout_set = Dataset.from_list(_as_dicts(hold_pts)) + holdout_source_label = f"carved from {holdout_source}" logger.info( "🛡️ Generalization holdout: {} fit / {} holdout (from {})", len(fit_valset), @@ -766,6 +793,7 @@ def _as_dicts(pts: list[Any]) -> list[dict[str, Any]]: for dim, val in baseline_dims.items(): logger.debug(" {}: {:.4f}", dim, val) best_point_scores = [float(d.get("avg_score", 0.0) or 0.0) for d in baseline_details] + best_details = baseline_details # ── Reflection data: what the optimizer LEARNS from ───────────── # Failure analysis, judge feedback and few-shot demos are drawn from @@ -1459,6 +1487,7 @@ async def _record_round( best_dims = dict(full_dims) best_holdout_score = cand_holdout best_point_scores = cand_points + best_details = full_details if reflect_set is fit_valset: reflect_details = full_details else: @@ -1697,6 +1726,24 @@ async def _record_round( generalization_gap=gen_gap, optimizer_name=str(getattr(self._optimizer, "name", "") or ""), early_stop_reason=early_stop_reason, + baseline_examples=_compact_examples(baseline_details), + best_examples=_compact_examples(best_details), + settings={ + "optimizer": str(getattr(self._optimizer, "name", "") or ""), + "max_trials": self.max_trials, + "patience": self.patience, + "min_absolute_improvement": self.min_absolute_improvement, + "min_confidence": self.min_confidence, + "min_transfer_ratio": self.min_transfer_ratio, + "max_generalization_gap": self.max_generalization_gap, + "holdout_tolerance": self.holdout_tolerance, + "holdout_source": holdout_source_label, + "reflect_on": self.reflect_on, + "task_model": str(self.task_model), + "rewrite_model": str(self.rewrite_model), + "metric": getattr(metric, "name", type(metric).__name__), + "candidates_evaluated": evaluated_candidates, + }, dataset_sizes={ "train": len(trainset), "reflection": len(reflect_set) if reflect_set is not fit_valset else 0, diff --git a/src/agentomatic/optimize/fitter_optimizers.py b/src/agentomatic/optimize/fitter_optimizers.py index 1672e941..ac7b33e2 100644 --- a/src/agentomatic/optimize/fitter_optimizers.py +++ b/src/agentomatic/optimize/fitter_optimizers.py @@ -525,7 +525,8 @@ def _prompt_with_expected_tips( exp_dict = {} if exp_dict: key_sets.append(frozenset(k for k in exp_dict if k != "must_include")) - meta = src.get("metadata") if isinstance(src.get("metadata"), dict) else {} + raw_meta = src.get("metadata") + meta: dict[str, Any] = raw_meta if isinstance(raw_meta, dict) else {} for term in list(exp_dict.get("must_include") or []) + list( meta.get("must_include") or [] ): diff --git a/src/agentomatic/optimize/holysheet_reports.py b/src/agentomatic/optimize/holysheet_reports.py index 73a30139..b5c718df 100644 --- a/src/agentomatic/optimize/holysheet_reports.py +++ b/src/agentomatic/optimize/holysheet_reports.py @@ -1,17 +1,70 @@ """HolySheet dashboard builders for fit / eval reports. -HolySheet ``Section`` / ``Tabs`` / ``Accordion`` only render content that is -nested in ``children`` (or accordion ``panels``). Flat ``report.add(Section)`` -followed by sibling blocks produces empty section cards — these builders always -nest content correctly. +HolySheet ``Section`` / ``Tabs`` only render content that is nested in +``children``. Flat ``report.add(Section)`` followed by sibling blocks produces +empty section cards — these builders always nest content correctly. + +HolySheet's ``Accordion`` block is not rendered by its bundled viewer (panels +are silently dropped), so panels are flattened with :func:`_panel_blocks`. """ from __future__ import annotations import difflib import json +import textwrap from typing import Any +_DIFF_WIDTH = 100 + + +def _display_lines(text: str, width: int = _DIFF_WIDTH) -> list[str]: + """Split a prompt into lines wrapped at ``_DIFF_WIDTH`` for readable diffs. + + Prompts are often one long line; a unified diff of that is a single + unreadable ``-``/``+`` pair. Wrapping first makes the diff show the + sentences that actually changed. + """ + lines: list[str] = [] + for raw in (text or "").splitlines(): + lines.extend(textwrap.wrap(raw, width, break_on_hyphens=False) or [""]) + return lines + + +def _unified_diff(before: str, after: str, *, a: str = "before", b: str = "after") -> str: + """Unified diff of two prompts on wrapped lines ('' when identical).""" + if (before or "") == (after or ""): + return "" + return "\n".join( + difflib.unified_diff( + _display_lines(before), _display_lines(after), fromfile=a, tofile=b, lineterm="" + ) + ) + + +def _wrapped(text: str, width: int = _DIFF_WIDTH) -> str: + """Prompt text wrapped for a code block (long lines would be cut off).""" + return "\n".join(_display_lines(text, width)) + + +def _panel_blocks(panels: list[dict[str, Any]]) -> list[Any]: + """Flatten accordion-style panels into always-visible blocks. + + Each panel becomes a Markdown heading (title + subtitle) followed by its + children. + """ + from holysheet import Markdown + + blocks: list[Any] = [] + for panel in panels: + subtitle = panel.get("subtitle") + heading = f"#### {panel.get('title', '')}" + if subtitle: + heading += f"\n\n_{subtitle}_" + blocks.append(Markdown(content=heading)) + blocks.extend(panel.get("children") or []) + return blocks + def _safe_json(value: Any, *, limit: int | None = None) -> str: """Pretty-print JSON (or stringify) for report panels.""" @@ -67,6 +120,8 @@ def _deployment_blocks(rec: Any) -> list[Any]: nested = data.get("deployment_recommendation") rollout = data.get("rollout") or nested or {} + if not isinstance(rollout, dict) and callable(getattr(rollout, "to_dict", None)): + rollout = rollout.to_dict() # RolloutConfig is a slots dataclass (no __dict__) if hasattr(rollout, "__dict__") and not isinstance(rollout, dict): rollout = { "strategy": getattr(rollout, "strategy", None), @@ -165,14 +220,8 @@ def _prompt_evolution_entries( score = float(entry.get("score") or 0.0) accepted = bool(entry.get("accepted")) new_prompt = snap or prev - diff_lines = list( - difflib.unified_diff( - prev.splitlines(keepends=True), - new_prompt.splitlines(keepends=True), - fromfile=f"v{len(versions) - 1}", - tofile=f"v{len(versions)}", - lineterm="", - ) + diff_text = _unified_diff( + prev, new_prompt, a=f"v{len(versions) - 1}", b=f"v{len(versions)}" ) versions.append( { @@ -182,7 +231,7 @@ def _prompt_evolution_entries( "accepted": accepted, "candidate": str(entry.get("candidate_name") or ""), "prompt": new_prompt, - "diff": "".join(diff_lines), + "diff": diff_text, "what_worked": list(entry.get("what_worked") or []), "what_failed": list(entry.get("what_failed") or []), "next_focus": list(entry.get("next_focus") or []), @@ -206,12 +255,22 @@ def build_fit_holysheet_report( stack_name: str = "", model_name: str = "", run_config: dict[str, Any] | None = None, + epochs: list[Any] | None = None, + baseline_eval: Any = None, + final_eval: Any = None, + eval_dataset: Any = None, + baseline_eval_scores: dict[str, float] | None = None, + dataset_stats: dict[str, Any] | None = None, ) -> str: - """Interactive HolySheet dashboard for a PromptFitResult.""" + """Interactive HolySheet dashboard for a (merged, multi-epoch) PromptFitResult. + + Section order: verdict, test scoreboard, what changed in the prompt, + epochs, all candidates, examples before vs after, data & settings (see + :func:`training_sections`), then run configuration, recommendations, + curves, prompt-evolution learnings and failure analysis. + """ from holysheet import ( KPI, - Accordion, - Callout, CodeBlock, Columns, DataTable, @@ -228,8 +287,6 @@ def build_fit_holysheet_report( dataset_sizes = dataset_sizes or {} run_config = run_config or {} - improvement = float(result.best_score) - float(result.baseline_score) - status = "positive" if improvement > 0 else ("neutral" if improvement == 0 else "negative") opt_name = ( optimizer_name or getattr(result, "optimizer_name", "") @@ -257,36 +314,18 @@ def build_fit_holysheet_report( author="agentomatic", ) - # ── Key results ──────────────────────────────────────────────────── - kpis: list[Any] = [ - KPI(label="Baseline Score", value=round(float(result.baseline_score), 4)), - KPI( - label="Best Score", - value=round(float(result.best_score), 4), - status="positive" if improvement > 0 else None, - ), - KPI( - label="Improvement", - value=round(improvement, 4), - delta=f"{improvement:+.4f}", - status=status, - ), - KPI(label="Trials", value=len(result.trials or [])), - KPI( - label="Duration", - value=round(float(result.duration_seconds or 0), 1), - unit="s", - ), - ] - if result.holdout_score is not None: - kpis.append(KPI(label="Holdout", value=round(float(result.holdout_score), 4))) - report.add( - Section( - title="Key Results", - description="Baseline vs best fit outcome", - children=[Columns(layout="equal", children=kpis)], - ) - ) + for block in training_sections( + result, + epochs=list(epochs or [result]), + baseline_eval=baseline_eval, + final_eval=final_eval, + eval_dataset=eval_dataset, + baseline_eval_scores=baseline_eval_scores, + eval_scores=eval_scores, + dataset_stats=dataset_stats, + dataset_sizes=dataset_sizes, + ): + report.add(block) # ── Run configuration ────────────────────────────────────────────── cfg_items = _info_items( @@ -326,12 +365,7 @@ def build_fit_holysheet_report( rec_children: list[Any] = [] suggestions = list(result.suggestions or []) if suggestions: - rec_children.append( - Callout( - content="\n".join(f"- {s}" for s in suggestions[:12]), - variant="note" if improvement > 0 else "highlight", - ) - ) + rec_children.append(Markdown(content="\n".join(f"- {s}" for s in suggestions[:12]))) deployment = getattr(result, "deployment_recommendation", None) if deployment: rec_children.append(Markdown(content="### Deployment recommendation")) @@ -567,21 +601,19 @@ def build_fit_holysheet_report( if meta_parts: children.append(Markdown(content="\n\n".join(meta_parts))) if item["diff"]: - children.append(CodeBlock(code=item["diff"], language="diff", title="Unified diff")) + children.append( + CodeBlock(code=item["diff"], language="diff", title="Change vs previous version") + ) + elif item["version"] == 0: + children.append( + CodeBlock(code=_wrapped(item["prompt"]) or "(empty)", language="markdown") + ) else: children.append(Markdown(content="_No text change vs previous version._")) - children.append( - CodeBlock( - code=item["prompt"] or "(empty prompt)", - language="markdown", - title=f"Full prompt ({len(item['prompt'])} chars)", - ) - ) evo_panels.append( { "title": title, "subtitle": f"{len(item['prompt'])} chars", - "default_expanded": item["version"] == 0 or is_best, "children": children, } ) @@ -590,7 +622,7 @@ def build_fit_holysheet_report( if learn_rows: prompt_tab_children.append(DataTable(title="Epoch learnings (summary)", data=learn_rows)) if evo_panels: - prompt_tab_children.append(Accordion(panels=evo_panels)) + prompt_tab_children.extend(_panel_blocks(evo_panels)) else: prompt_tab_children.append(Markdown(content="_No prompt history._")) if judge_rows: @@ -602,131 +634,60 @@ def build_fit_holysheet_report( ) ) - # Baseline → best diff + full best prompt - diff_lines = list( - difflib.unified_diff( - baseline_prompt.splitlines(keepends=True), - best_prompt.splitlines(keepends=True), - fromfile="baseline", - tofile="best", - lineterm="", - ) - ) - summary_prompt_children: list[Any] = [] - if diff_lines: - summary_prompt_children.append( - CodeBlock(code="".join(diff_lines), language="diff", title="Baseline → best") - ) - else: - summary_prompt_children.append( - Markdown(content="_No prompt text change (baseline kept)._") - ) - summary_prompt_children.append( - Accordion( - panels=[ - { - "title": f"Full baseline prompt ({len(baseline_prompt)} chars)", - "default_expanded": False, - "children": [ - CodeBlock( - code=baseline_prompt or "(empty)", - language="markdown", - ) - ], - }, - { - "title": f"Full best prompt ({len(best_prompt)} chars)", - "default_expanded": True, - "children": [ - CodeBlock( - code=best_prompt or "(empty)", - language="markdown", - ) - ], - }, - ] - ) - ) - + tabs: list[dict[str, Any]] = [{"label": "Prompt Evolution", "children": prompt_tab_children}] few_shot = list(getattr(result.best_config, "few_shot_examples", None) or []) if few_shot: - fs_panels = [] - for i, ex in enumerate(few_shot, 1): - q = str(ex.get("query", "")) - r = str(ex.get("response", "")) - fs_panels.append( - { - "title": f"Few-shot #{i}", - "subtitle": q[:80], - "default_expanded": i == 1, - "children": [ - Markdown(content=f"**Query**\n\n{q}"), - CodeBlock(code=r or "(empty)", language="json", title="Response"), - ], - } - ) - summary_prompt_children.append(Accordion(panels=fs_panels)) - - report.add( - Tabs( - tabs=[ - {"label": "Prompt Evolution", "children": prompt_tab_children}, - {"label": "Best Prompt", "children": summary_prompt_children}, - ] - ) - ) - - # ── Trials / failures ────────────────────────────────────────────── - trial_children: list[Any] = [] - if result.trials: - trial_rows = [ + fs_panels = [ { - "round": t.get("round", "—"), - "name": str(t.get("name", "")), - "phase": str(t.get("phase", "")), - "score": round(float(t.get("score", 0.0)), 4), - "notes": str(t.get("mutation_notes", "") or t.get("accept_reason", "") or "")[ - :200 + "title": f"Few-shot #{i}", + "subtitle": str(ex.get("query", ""))[:80], + "children": [ + Markdown(content=f"**Query**\n\n{ex.get('query', '')}"), + CodeBlock( + code=str(ex.get("response", "")) or "(empty)", + language="json", + title="Response", + ), ], - "critique": str(t.get("critique", "") or "")[:240], } - for t in result.trials + for i, ex in enumerate(few_shot, 1) ] - trial_children.append(DataTable(title="Candidates", data=trial_rows)) - apo_critiques = [t for t in result.trials if str(t.get("critique") or "").strip()] - if apo_critiques: - critique_md = "\n\n".join( - f"**{t.get('name')}** (round {t.get('round')}):\n\n{str(t.get('critique'))[:800]}" - for t in apo_critiques[:8] - ) - trial_children.append( - Markdown(content=("### Textual gradients / APO critiques\n\n" + critique_md)) - ) - else: - trial_children.append(Markdown(content="_No trials recorded._")) + tabs.append({"label": "Few-shot examples", "children": _panel_blocks(fs_panels)}) - if result.failure_clusters: - fc_rows = [] - for cluster in result.failure_clusters: - if isinstance(cluster, dict): - fc_rows.append( - { - "label": cluster.get("label", ""), - "count": cluster.get("count", 0), - "description": str(cluster.get("description", ""))[:300], - "fix": str(cluster.get("suggested_fix", ""))[:300], - } - ) - if fc_rows: - trial_children.append(DataTable(title="Failure clusters", data=fc_rows)) + report.add(Tabs(tabs=tabs)) - report.add( - Section( - title="Trial History", - description="Candidate prompts evaluated during the fit", - children=trial_children, + # ── Failure analysis (critiques + clusters) ───────────────────── + failure_children: list[Any] = [] + apo_critiques = [t for t in result.trials or [] if str(t.get("critique") or "").strip()] + if apo_critiques: + critique_md = "\n\n".join( + f"**{t.get('name')}** (epoch {t.get('epoch', 1)}, round {t.get('round')}):\n\n" + f"{str(t.get('critique'))[:800]}" + for t in apo_critiques[:8] + ) + failure_children.append( + Markdown(content=("### Textual gradients / APO critiques\n\n" + critique_md)) + ) + fc_rows = [ + { + "label": cluster.get("label", ""), + "count": cluster.get("count", 0), + "description": str(cluster.get("description", ""))[:300], + "fix": str(cluster.get("suggested_fix", ""))[:300], + } + for cluster in result.failure_clusters or [] + if isinstance(cluster, dict) + ] + if fc_rows: + failure_children.append(DataTable(title="Failure clusters (train split)", data=fc_rows)) + if failure_children: + report.add( + Section( + title="Failure analysis", + description="What the optimizer saw going wrong on the reflection (train) data", + children=failure_children, + ) ) - ) report.export_html(str(output_path)) return str(output_path) @@ -781,7 +742,6 @@ def build_eval_holysheet_report( """Interactive HolySheet dashboard for an EvaluationReport.""" from holysheet import ( KPI, - Accordion, Callout, CodeBlock, Columns, @@ -882,8 +842,9 @@ def build_eval_holysheet_report( ) # Per-example table (compact) + accordion (full) - table_rows = [] - panels = [] + table_rows: list[dict[str, Any]] = [] + score_keys: dict[str, None] = {} + panels: list[dict[str, Any]] = [] rationale_rows = [] for er in examples: er_scores = getattr(er, "scores", {}) or {} @@ -893,21 +854,15 @@ def build_eval_holysheet_report( err = getattr(er, "error", None) or "" ms = round(float(getattr(er, "duration_ms", 0) or 0), 1) rationale = _example_judge_text(er) - table_rows.append( - { - "id": eid, - "passed": passed, - "judge": round(float(er_scores.get("judge", 0.0)), 3) - if "judge" in er_scores - else "—", - "f1": round(float(er_scores.get("f1", 0.0)), 3) if "f1" in er_scores else "—", - "keywords": round(float(er_scores.get("keywords", 0.0)), 3) - if "keywords" in er_scores - else "—", - "error": str(err)[:80], - "ms": ms, - } - ) + row: dict[str, Any] = {"id": eid, "passed": passed} + for key, value in er_scores.items(): + score_keys.setdefault(key, None) + try: + row[key] = round(float(value), 3) + except (TypeError, ValueError): + row[key] = str(value) + row.update({"error": str(err)[:80], "ms": ms}) + table_rows.append(row) if rationale: rationale_rows.append({"id": eid, "rationale": rationale}) @@ -953,8 +908,10 @@ def build_eval_holysheet_report( panels.append( { "title": f"{eid} · {'PASS' if passed else 'FAIL'}", - "subtitle": f"judge={er_scores.get('judge', '—')} · {ms}ms", - "default_expanded": (not passed) or bool(err), + "subtitle": " · ".join( + [*(f"{k}={_fmt(v, 3)}" for k, v in er_scores.items()), f"{ms}ms"] + ), + "passed": passed and not err, "children": panel_children, } ) @@ -964,12 +921,17 @@ def build_eval_holysheet_report( example_children.append( DataTable( title="Per-example scores", - data=table_rows, - columns=["id", "passed", "judge", "f1", "keywords", "error", "ms"], + data=[ + {k: r.get(k, "—") for k in ["id", "passed", *score_keys, "error", "ms"]} + for r in table_rows + ], + columns=["id", "passed", *score_keys, "error", "ms"], ) ) if panels: - example_children.append(Accordion(panels=panels)) + # Failures first; details for at most 30 examples (all are in the table). + shown = sorted(panels, key=lambda panel: bool(panel.get("passed")))[:30] + example_children.extend(_panel_blocks(shown)) else: example_children.append(Markdown(content="_No examples evaluated._")) @@ -1046,3 +1008,479 @@ def build_eval_holysheet_report( hs.export_html(str(output_path)) return str(output_path) + + +# ===================================================================== +# Training-report sections (multi-epoch view, candidates, examples, data) +# ===================================================================== + + +def _fmt(value: Any, digits: int = 4) -> str: + """Format a score (or '—').""" + if value is None: + return "—" + try: + return f"{float(value):.{digits}f}" + except (TypeError, ValueError): + return str(value) + + +def _scores_text(scores: dict[str, Any] | None) -> str: + """Compact 'metric=score' rendering of a per-example score dict.""" + return " · ".join(f"{k}={_fmt(v, 2)}" for k, v in (scores or {}).items()) or "—" + + +def training_sections( + merged: Any, + *, + epochs: list[Any], + baseline_eval: Any = None, + final_eval: Any = None, + eval_dataset: Any = None, + baseline_eval_scores: dict[str, float] | None = None, + eval_scores: dict[str, float] | None = None, + dataset_stats: dict[str, Any] | None = None, + dataset_sizes: dict[str, int] | None = None, +) -> list[Any]: + """Build the report sections that explain *what the optimization did*. + + Args: + merged: A ``PromptFitResult`` spanning all epochs (initial baseline → + final best, every trial tagged with its epoch). + epochs: The per-epoch ``PromptFitResult`` objects, in order. + baseline_eval: ``EvaluationReport`` on the untouched test split + *before* fit (optional). + final_eval: ``EvaluationReport`` on the same split *after* fit. + eval_dataset: Examples (``AgentDataset`` or list) to join inputs and + expected outputs onto the per-example results. + baseline_eval_scores: Scores-only alternative to ``baseline_eval``. + eval_scores: Scores-only alternative to ``final_eval``. + dataset_stats: e.g. ``dataset.metadata["augment_stats"]``. + dataset_sizes: Split sizes. + + Returns: + HolySheet blocks, in display order. + """ + from holysheet import ( + KPI, + Callout, + CodeBlock, + Columns, + DataTable, + InfoList, + Markdown, + Section, + ) + + blocks: list[Any] = [] + before_scores = dict(getattr(baseline_eval, "scores", None) or baseline_eval_scores or {}) + after_scores = dict(getattr(final_eval, "scores", None) or eval_scores or {}) + initial_prompt = getattr(merged.baseline_config, "system_prompt", "") or "" + final_prompt = getattr(merged.best_config, "system_prompt", "") or "" + val_delta = float(merged.best_score) - float(merged.baseline_score) + + # ── Verdict ────────────────────────────────────────────────────── + kpis = [ + KPI(label="Validation (initial)", value=round(float(merged.baseline_score), 4)), + KPI( + label="Validation (final)", + value=round(float(merged.best_score), 4), + delta=f"{val_delta:+.4f}", + status="positive" if val_delta > 0 else ("negative" if val_delta < 0 else None), + ), + ] + if merged.holdout_score is not None: + hold_before = merged.baseline_holdout_score + hold_delta = ( + float(merged.holdout_score) - float(hold_before) if hold_before is not None else None + ) + kpis.append( + KPI( + label="Held-out gate", + value=round(float(merged.holdout_score), 4), + delta=f"{hold_delta:+.4f}" if hold_delta is not None else None, + ) + ) + shared = [k for k in after_scores if k in before_scores] + for key in shared[:3]: + delta = float(after_scores[key]) - float(before_scores[key]) + kpis.append( + KPI( + label=f"Test {key}", + value=round(float(after_scores[key]), 4), + delta=f"{delta:+.4f}", + status="positive" if delta > 0 else ("negative" if delta < 0 else None), + ) + ) + accepted = [t for t in merged.trials or [] if t.get("decision") == "accepted"] + verdict_lines = [ + f"- **Prompt {'changed' if final_prompt != initial_prompt else 'unchanged'}** after " + f"{len(epochs)} epoch(s); {len(accepted)} candidate(s) accepted of " + f"{sum(1 for t in merged.trials or [] if t.get('phase') == 'minibatch')} scored.", + f"- Validation {_fmt(merged.baseline_score)} → {_fmt(merged.best_score)} " + f"(Δ {val_delta:+.4f}).", + ] + if merged.holdout_score is not None: + verdict_lines.append( + f"- Held-out gate (veto only, never selects): " + f"{_fmt(merged.baseline_holdout_score)} → {_fmt(merged.holdout_score)}." + ) + if shared: + verdict_lines.append( + "- Untouched test split: " + + ", ".join(f"{k} {_fmt(before_scores[k])} → {_fmt(after_scores[k])}" for k in shared) + + "." + ) + if merged.early_stop_reason: + verdict_lines.append(f"- Stop reason: {merged.early_stop_reason}.") + if final_prompt == initial_prompt: + headline = "Prompt unchanged: no candidate passed the acceptance rules." + elif shared: + key = shared[-1] + headline = ( + f"Prompt improved: validation {_fmt(merged.baseline_score, 3)} → " + f"{_fmt(merged.best_score, 3)}, test {key} {_fmt(before_scores[key], 3)} → " + f"{_fmt(after_scores[key], 3)}." + ) + else: + headline = ( + f"Prompt changed: validation {_fmt(merged.baseline_score, 3)} → " + f"{_fmt(merged.best_score, 3)} (evaluate the test split for an unbiased number)." + ) + blocks.append( + Section( + title="Verdict", + description="Initial vs final — validation (selection), held-out gate, test", + children=[ + Columns(layout="equal", children=kpis), + Callout(content=headline, variant="note" if val_delta > 0 else "highlight"), + Markdown(content="\n".join(verdict_lines)), + ], + ) + ) + + # ── Scoreboard ─────────────────────────────────────────────────── + if before_scores or after_scores: + rows = [ + { + "metric": key, + "test before": _fmt(before_scores.get(key)), + "test after": _fmt(after_scores.get(key)), + "Δ": ( + f"{float(after_scores[key]) - float(before_scores[key]):+.4f}" + if key in before_scores and key in after_scores + else "—" + ), + } + for key in sorted(set(before_scores) | set(after_scores)) + ] + blocks.append( + Section( + title="Test scoreboard", + description="Every compiled metric on the split optimization never saw", + children=[ + DataTable( + title="Test scores before vs after", + data=rows, + columns=["metric", "test before", "test after", "Δ"], + ) + ], + ) + ) + + # ── What changed in the prompt ─────────────────────────────────── + change_children: list[Any] = [] + diff = _unified_diff(initial_prompt, final_prompt, a="initial", b="final") + change_children.append( + CodeBlock(code=diff, language="diff", title="Initial → final prompt") + if diff + else Markdown(content="_The prompt did not change: no candidate passed acceptance._") + ) + change_children.append( + Columns( + layout="equal", + children=[ + CodeBlock( + code=_wrapped(initial_prompt, 64) or "(empty)", + language="markdown", + title=f"Initial prompt ({len(initial_prompt)} chars)", + ), + CodeBlock( + code=_wrapped(final_prompt, 64) or "(empty)", + language="markdown", + title=f"Final prompt ({len(final_prompt)} chars)", + ), + ], + ) + ) + timeline = [] + previous = initial_prompt + for trial in accepted: + prompt = str(trial.get("system_prompt") or "") + timeline.append( + { + "title": ( + f"Epoch {trial.get('epoch', 1)} · round {trial.get('round', '—')} · " + f"{trial.get('name', '')} · validation {_fmt(trial.get('incumbent_score'))} → " + f"{_fmt(trial.get('score'))} · held-out {_fmt(trial.get('holdout_score'))}" + ), + "children": [ + Markdown(content=f"**Why accepted:** {trial.get('reason') or '—'}"), + CodeBlock( + code=_unified_diff(previous, prompt, a="previous", b="accepted") + or "(no text change — parameters / few-shot only)", + language="diff", + title="Change vs previous best", + ), + ], + } + ) + previous = prompt or previous + if timeline: + change_children.append(Markdown(content="### Accepted changes, in order")) + change_children.extend(_panel_blocks(timeline)) + blocks.append( + Section( + title="What changed in the prompt", + description="Across all epochs: the prompt you started with vs the one you keep", + children=change_children, + ) + ) + + # ── Epochs ─────────────────────────────────────────────────────── + if len(epochs) > 1: + blocks.append( + Section( + title="Epochs", + description="Each fit() epoch re-optimizes from the previous best", + children=[ + DataTable( + title="Per-epoch validation scores", + data=[ + { + "epoch": i + 1, + "start": _fmt(r.baseline_score), + "best": _fmt(r.best_score), + "improved": "yes" if r.improved else "no", + "held-out": _fmt(r.holdout_score), + "candidates": sum( + 1 for t in r.trials or [] if t.get("phase") == "minibatch" + ), + "stop": str(r.early_stop_reason or "")[:120], + } + for i, r in enumerate(epochs) + ], + ) + ], + ) + ) + + # ── Candidates ─────────────────────────────────────────────────── + cand_rows = [] + cand_panels: list[dict[str, Any]] = [] + shown_prompts: set[str] = set() + full_by_name = { + (t.get("epoch"), t.get("name")): t + for t in merged.trials or [] + if t.get("phase") == "full_val" + } + for t in merged.trials or []: + if t.get("phase") not in ("minibatch", "skipped"): + continue + full = full_by_name.get((t.get("epoch"), t.get("name")), {}) + decision = full.get("decision") or t.get("decision") or "" + reason = full.get("reason") or t.get("reason") or "" + cand_rows.append( + { + "epoch": t.get("epoch", 1), + "round": t.get("round", "—"), + "candidate": str(t.get("name", "")), + "source": str(t.get("source", "")), + "minibatch": _fmt(t.get("score")), + "validation": _fmt(full.get("score")), + "held-out": _fmt(full.get("holdout_score")), + "confidence": _fmt(full.get("confidence"), 2), + "decision": decision, + "reason": str(reason)[:220], + } + ) + prompt = str(t.get("system_prompt") or "") + # One panel per DISTINCT proposed prompt (duplicates are in the table). + if prompt and prompt not in shown_prompts and len(cand_panels) < 12: + shown_prompts.add(prompt) + notes = f" \n**Notes:** {t.get('mutation_notes')}" if t.get("mutation_notes") else "" + cand_panels.append( + { + "title": f"{t.get('name')} (epoch {t.get('epoch', 1)}) — " + f"{decision or 'screened'}, minibatch {_fmt(t.get('score'))}", + "children": [ + Markdown( + content=f"**Decision:** {decision or '—'} \n**Why:** {reason or '—'}" + + notes + ), + CodeBlock( + code=_unified_diff(initial_prompt, prompt, a="initial", b="candidate") + or "(same text as the initial prompt)", + language="diff", + title="Candidate vs initial prompt", + ), + ], + } + ) + cand_children: list[Any] = [] + if cand_rows: + cand_children.append( + DataTable( + title="Candidates", + data=cand_rows, + columns=[ + "epoch", + "round", + "candidate", + "source", + "minibatch", + "validation", + "held-out", + "confidence", + "decision", + "reason", + ], + ) + ) + if cand_panels: + cand_children.extend(_panel_blocks(cand_panels)) + else: + cand_children.append(Markdown(content="_No candidates were scored._")) + blocks.append( + Section( + title="All candidates", + description=( + "Every proposed prompt, its scores and why it was accepted or rejected " + "(duplicates, not promoted, not significant, did not transfer, …)" + ), + children=cand_children, + ) + ) + + # ── Examples: before vs after ──────────────────────────────────── + example_rows = _example_rows(baseline_eval, final_eval, eval_dataset) + source = "untouched test split" + if not example_rows: + source = "validation examples (the selection set)" + after_by_query = {e.get("query"): e for e in merged.best_examples or []} + for before in merged.baseline_examples or []: + after = after_by_query.get(before.get("query"), {}) + example_rows.append( + { + "example": str(before.get("query", ""))[:120], + "expected": str(before.get("expected", ""))[:240], + "before": str(before.get("response", ""))[:300], + "before score": _fmt(before.get("score"), 2), + "after": str(after.get("response", ""))[:300], + "after score": _fmt(after.get("score"), 2), + "Δ": ( + f"{float(after['score']) - float(before['score']):+.2f}" + if "score" in after and "score" in before + else "—" + ), + "why (judge)": str(after.get("feedback") or before.get("feedback") or "")[ + :300 + ], + } + ) + blocks.append( + Section( + title="Examples — before vs after", + description=f"Per-example answers and scores ({source})", + children=[ + DataTable(title="Per-example results", data=example_rows) + if example_rows + else Markdown(content="_No per-example results available._") + ], + ) + ) + + # ── Data ───────────────────────────────────────────────────────── + data_items = _info_items( + [(f"{k} examples", v) for k, v in (dataset_sizes or {}).items()] + + [(f"fitter · {k}", v) for k, v in (getattr(merged, "dataset_sizes", None) or {}).items()] + ) + data_children: list[Any] = [] + if data_items: + data_children.append(InfoList(title="Splits", items=data_items)) + if dataset_stats: + by_strategy = dataset_stats.get("by_strategy") or {} + data_children.append( + InfoList( + title="Augmentation", + items=_info_items( + [(k, v) for k, v in dataset_stats.items() if k != "by_strategy"] + + [(f"added via {k}", v) for k, v in by_strategy.items()] + ), + ) + ) + settings = getattr(merged, "settings", None) or {} + if settings: + data_children.append( + InfoList(title="Fitter settings", items=_info_items(list(settings.items()))) + ) + if data_children: + blocks.append( + Section( + title="Data & settings", + description="What the optimizer learned from, selected on, and gated with", + children=data_children, + ) + ) + return blocks + + +def _example_rows(baseline_eval: Any, final_eval: Any, eval_dataset: Any) -> list[dict[str, Any]]: + """Join before/after ``EvaluationReport`` example results by example id.""" + if final_eval is None: + return [] + examples = getattr(eval_dataset, "examples", eval_dataset) or [] + by_id = {getattr(e, "id", None): e for e in examples} + before_by_id = {r.example_id: r for r in getattr(baseline_eval, "example_results", None) or []} + rows: list[dict[str, Any]] = [] + for after in getattr(final_eval, "example_results", None) or []: + before = before_by_id.get(after.example_id) + example = by_id.get(after.example_id) + query = "" + expected = "" + if example is not None: + try: + point = example.to_datapoint() + query = point.query + from agentomatic.optimize.metrics import plain_expected + + expected = plain_expected(point.expected_answer) or "" + except Exception: # noqa: BLE001 + query = str(getattr(example, "input", "")) + after_pred = after.prediction or {} + before_pred = (before.prediction if before else None) or {} + before_scores = (before.scores or {}) if before else {} + deltas = " · ".join( + f"{k} {float(v) - float(before_scores[k]):+.2f}" + for k, v in (after.scores or {}).items() + if k in before_scores + ) + rationale = "" + for meta in (after.metadata or {}).values(): + if isinstance(meta, dict) and meta.get("reason"): + rationale = str(meta["reason"]) + break + rows.append( + { + "example": after.example_id, + "question": str(query)[:200], + "expected": str(expected)[:240], + "before": str(before_pred.get("response", before.error if before else ""))[:300], + "before scores": _scores_text(before.scores if before else None), + "after": str(after_pred.get("response", after.error or ""))[:300], + "after scores": _scores_text(after.scores), + "Δ": deltas or "—", + "why (judge)": rationale[:300], + } + ) + return rows diff --git a/src/agentomatic/optimize/report.py b/src/agentomatic/optimize/report.py index 4a747dbe..be39b20b 100644 --- a/src/agentomatic/optimize/report.py +++ b/src/agentomatic/optimize/report.py @@ -897,62 +897,204 @@ def _build_eval_report_html( """ +def merge_fit_results(results: list[Any]) -> Any: + """Merge per-epoch ``PromptFitResult`` objects into one run-level result. + + Each ``fit()`` epoch re-optimizes from the previous epoch's best prompt, + so the *last* result alone starts from an already-improved prompt. The + merged result keeps the **first** epoch's baseline (the prompt you + started with) and the **last** epoch's best, concatenates the score and + prompt histories, and tags every trial with its 1-based ``epoch``. + + Args: + results: ``PromptFitResult`` objects in epoch order (at least one). + + Returns: + A new ``PromptFitResult`` (the inputs are not modified). + """ + import dataclasses + + if not results: + raise ValueError("merge_fit_results() needs at least one PromptFitResult") + first, last = results[0], results[-1] + if len(results) == 1 and all("epoch" in t for t in first.trials or []): + return first + # The epoch that produced the final config: its suggestions, parameter + # changes and failure analysis describe what you keep (a later epoch that + # found nothing better would otherwise report "no improvement"). + source = next((r for r in reversed(results) if r.improved), last) + trials = [ + {**t, "epoch": t.get("epoch", i)} + for i, r in enumerate(results, 1) + for t in (r.trials or []) + ] + metric_deltas: dict[str, float] = {} + for r in results: # each epoch's delta is vs its own start → they chain + for key, value in (r.metric_deltas or {}).items(): + metric_deltas[key] = metric_deltas.get(key, 0.0) + float(value) + merged = dataclasses.replace( + last, + baseline_config=first.baseline_config, + baseline_score=first.baseline_score, + baseline_holdout_score=first.baseline_holdout_score, + baseline_examples=list(first.baseline_examples or []), + trials=trials, + score_history=[s for r in results for s in (r.score_history or [])], + prompt_history=[p for r in results for p in (r.prompt_history or [])], + duration_seconds=sum(float(r.duration_seconds or 0.0) for r in results), + metric_deltas=metric_deltas, + param_suggestions=dict(source.param_suggestions or {}), + suggestions=list(source.suggestions or []), + failure_clusters=list(source.failure_clusters or []), + ) + if last.deployment_recommendation is not None or source.deployment_recommendation: + try: + from agentomatic.optimize.deployment import build_deployment_recommendation + + merged.deployment_recommendation = build_deployment_recommendation( + merged, version=f"v2_fit_{merged.experiment_id}" + ) + except Exception as exc: # noqa: BLE001 + logger.debug("deployment recommendation not rebuilt for merged fit: {}", exc) + merged.deployment_recommendation = source.deployment_recommendation + return merged + + +def _fit_results_from(result: Any) -> tuple[list[Any], dict[str, list[float]] | None]: + """Normalise what callers pass to :func:`generate_fit_report`. + + Accepts a ``PromptFitResult``, a list of them, a ``History`` returned by + ``agent.fit()`` (uses ``history.fit_results`` + ``history.history``) or + the agent itself (its per-epoch results from the last ``fit()``). + """ + if isinstance(result, (list, tuple)): + results = [r for r in result if r is not None] + return results, None + if hasattr(result, "best_config") and hasattr(result, "baseline_config"): + return [result], None + if hasattr(result, "fit_results") and isinstance(getattr(result, "history", None), dict): + return list(result.fit_results or []), dict(result.history) + per_epoch = getattr(result, "_fit_results", None) + if isinstance(per_epoch, list) and per_epoch: + return list(per_epoch), None + last = getattr(result, "_last_fit_result", None) + if last is not None: + return [last], None + raise TypeError( + f"generate_fit_report() got {type(result).__name__}; pass a PromptFitResult, " + "a list of them, the History returned by agent.fit(), or the fitted agent." + ) + + def generate_fit_report( - result: Any, # PromptFitResult + result: Any, output_path: str | Path | None = None, *, keras_history: dict[str, list[float]] | None = None, eval_scores: dict[str, float] | None = None, + baseline_eval_scores: dict[str, float] | None = None, + baseline_eval: Any = None, + final_eval: Any = None, + eval_dataset: Any = None, + dataset_stats: dict[str, Any] | None = None, dataset_sizes: dict[str, int] | None = None, optimizer_name: str | None = None, stack_name: str | None = None, model_name: str | None = None, run_config: dict[str, Any] | None = None, ) -> str: - """Generate an interactive HTML report for ``PromptFitResult``. + """Generate an interactive HTML report (+ JSON sidecar) for a prompt fit. - Prefers HolySheet (nested sections/tabs, charts, full prompt accordion). - Falls back to the built-in static HTML when HolySheet is unavailable. + The report opens with what changed and whether it helped: a verdict + (validation, held-out gate and test before → after), the test + scoreboard, the initial → final prompt diff with every accepted change + in order, all candidates with the reason each was accepted or rejected, + and per-example answers before vs after. Curves, prompt-evolution + learnings, recommendations and failure clusters follow. + + Prefers HolySheet; falls back to a built-in static HTML page. Args: - result: ``PromptFitResult`` from ``PromptFitter.fit()``. + result: A ``PromptFitResult``, a list of per-epoch results, the + ``History`` returned by ``agent.fit()`` (recommended — it carries + every epoch plus the loss curves), or the fitted agent. output_path: Path to write the HTML file. Auto-generated if None. - keras_history: Optional ``History.history`` dict (loss / val_loss…). - eval_scores: Optional held-out evaluate() scores. - dataset_sizes: Optional ``{{train, validation, test}}`` counts. + A ``.json`` sidecar with the same data is written next to it. + keras_history: ``History.history`` dict (loss / val_loss…). Taken + from ``result`` automatically when a ``History`` is passed. + eval_scores: Test-split scores *after* fit (``report.scores``). + baseline_eval_scores: Test-split scores *before* fit. + baseline_eval: ``EvaluationReport`` before fit — enables the + per-example before/after table (preferred over the ``*_scores``). + final_eval: ``EvaluationReport`` after fit, on the same examples. + eval_dataset: The evaluated examples (``AgentDataset`` or list), to + show each question and expected answer next to the results. + dataset_stats: e.g. ``dataset.metadata["augment_stats"]``. + dataset_sizes: Optional ``{train, validation, test}`` counts. optimizer_name: Optimizer label for the header. stack_name: Stack name for the header. model_name: Task model label for the header. run_config: Optional train knobs (epochs, trials, judge dims, …). Returns: - Path to the generated report file. + Path to the generated HTML report. + + Raises: + TypeError: ``result`` is none of the accepted types. + ValueError: ``result`` holds no fit results (e.g. the optimizer never + ran — check ``agent._last_optimize_status``). """ + results, history_from_result = _fit_results_from(result) + if not results: + raise ValueError( + "No PromptFitResult to report: the optimizer did not produce one " + "(check agent._last_optimize_status for the reason)." + ) + merged = merge_fit_results(results) if output_path is None: - output_path = Path(f".optimize/{result.agent}/fit_report_{result.experiment_id}.html") + output_path = Path(f".optimize/{merged.agent}/fit_report_{merged.experiment_id}.html") output_path = Path(output_path) output_path.parent.mkdir(parents=True, exist_ok=True) - history = keras_history or {} - scores = eval_scores or {} + history = keras_history or history_from_result or {} + after_scores = dict(getattr(final_eval, "scores", None) or eval_scores or {}) + before_scores = dict(getattr(baseline_eval, "scores", None) or baseline_eval_scores or {}) sizes = dataset_sizes or {} config = run_config or {} - opt_name = optimizer_name or "" - stack = stack_name or "" - model = model_name or "" + extras: dict[str, Any] = { + "epochs": results, + "baseline_eval": baseline_eval, + "final_eval": final_eval, + "eval_dataset": eval_dataset, + "baseline_eval_scores": before_scores, + "dataset_stats": dataset_stats, + } + _write_fit_report_json( + output_path.with_suffix(".json"), + merged, + epochs=results, + keras_history=history, + before_scores=before_scores, + after_scores=after_scores, + baseline_eval=baseline_eval, + final_eval=final_eval, + eval_dataset=eval_dataset, + dataset_stats=dataset_stats, + ) try: from agentomatic.optimize.holysheet_reports import build_fit_holysheet_report path = build_fit_holysheet_report( - result, + merged, output_path, keras_history=history, - eval_scores=scores, + eval_scores=after_scores, dataset_sizes=sizes, - optimizer_name=opt_name, - stack_name=stack, - model_name=model, + optimizer_name=optimizer_name or "", + stack_name=stack_name or "", + model_name=model_name or "", run_config=config, + **extras, ) logger.info("📊 Fit report (holysheet) generated: {}", path) return path @@ -962,14 +1104,56 @@ def generate_fit_report( logger.warning("holysheet fit report failed ({}), using fallback HTML", exc) html_content = _build_fit_report_html( - result, + merged, keras_history=history, + before_scores=before_scores, + after_scores=after_scores, + epochs=len(results), ) output_path.write_text(html_content, encoding="utf-8") logger.info("📊 Fit report generated: {}", output_path) return str(output_path) +def _write_fit_report_json( + path: Path, + merged: Any, + *, + epochs: list[Any], + keras_history: dict[str, list[float]], + before_scores: dict[str, float], + after_scores: dict[str, float], + baseline_eval: Any, + final_eval: Any, + eval_dataset: Any, + dataset_stats: dict[str, Any] | None, +) -> None: + """Machine-readable twin of the HTML report (never fails the report).""" + try: + from agentomatic.optimize.holysheet_reports import _example_rows + + payload = { + "agent": merged.agent, + "initial_prompt": merged.baseline_config.system_prompt, + "final_prompt": merged.best_config.system_prompt, + "prompt_changed": merged.best_config.system_prompt + != merged.baseline_config.system_prompt, + "validation": {"initial": merged.baseline_score, "final": merged.best_score}, + "holdout_gate": { + "initial": merged.baseline_holdout_score, + "final": merged.holdout_score, + }, + "test": {"before": before_scores, "after": after_scores}, + "test_examples": _example_rows(baseline_eval, final_eval, eval_dataset), + "epochs": [r.to_dict() for r in epochs], + "keras_history": keras_history, + "dataset_stats": dataset_stats or {}, + } + path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8") + except Exception as exc: # noqa: BLE001 + logger.warning("fit report JSON sidecar not written ({})", exc) + + def _prompt_evolution_entries( *, baseline_prompt: str, @@ -996,6 +1180,9 @@ def _build_fit_report_html( result: Any, *, keras_history: dict[str, list[float]] | None = None, + before_scores: dict[str, float] | None = None, + after_scores: dict[str, float] | None = None, + epochs: int = 1, ) -> str: """Build the self-contained HTML for a PromptFitResult.""" improvement = result.best_score - result.baseline_score @@ -1227,23 +1414,49 @@ def _build_fit_report_html( {evo_blocks} """ + # Test scoreboard (untouched split, before vs after) + before_scores = before_scores or {} + after_scores = after_scores or {} + scoreboard_section = "" + if before_scores or after_scores: + board_rows = "" + for key in sorted(set(before_scores) | set(after_scores)): + b = before_scores.get(key) + a = after_scores.get(key) + delta = f"{float(a) - float(b):+.4f}" if a is not None and b is not None else "—" + board_rows += ( + f"{html.escape(key)}" + f"{'—' if b is None else f'{float(b):.4f}'}" + f"{'—' if a is None else f'{float(a):.4f}'}{delta}" + ) + scoreboard_section = f""" +

🧾 Test Scoreboard (never seen during optimization)

+ + + {board_rows} +
MetricBeforeAfterΔ
+ """ + # Trial table trial_section = "" if result.trials: trial_rows = "" for t in result.trials: + reason = t.get("reason") or t.get("mutation_notes") or "" trial_rows += f""" + {t.get("epoch", 1)} {t.get("round", "—")} {html.escape(str(t.get("name", "")))} {html.escape(str(t.get("phase", "")))} - {float(t.get("score", 0.0)):.4f} - {html.escape(str(t.get("mutation_notes", "") or "")[:220])} + {float(t.get("score", 0.0) or 0.0):.4f} + {html.escape(str(t.get("decision", "") or ""))} + {html.escape(str(reason)[:220])} """ trial_section = f""" -

🧪 Trial History

+

🧪 Candidates ({epochs} epoch(s))

- + {trial_rows}
RoundCandidatePhaseScoreNotes
EpochRoundCandidatePhaseScoreDecisionWhy
""" @@ -1255,8 +1468,8 @@ def _build_fit_report_html( difflib.unified_diff( baseline_prompt.splitlines(keepends=True), best_prompt.splitlines(keepends=True), - fromfile="baseline", - tofile="best", + fromfile="initial", + tofile="final", lineterm="", ) ) @@ -1275,7 +1488,7 @@ def _build_fit_report_html( diff_html += f"
{escaped}
" diff_section = f""" -

📝 Prompt Diff

+

📝 Prompt Diff (initial → final)

{diff_html}
@@ -1382,6 +1595,8 @@ def _build_fit_report_html(

Agent: {html.escape(result.agent)} | Experiment: {html.escape(result.experiment_id)} | {timestamp}

{kpis} + {scoreboard_section} + {diff_section} {curve_section} {keras_section} {prompt_history_section} @@ -1391,7 +1606,6 @@ def _build_fit_report_html( {cluster_section} {suggestion_section} {deployment_section} - {diff_section} {few_shot_section}
Generated by Agentomatic PromptFitter — {timestamp}
diff --git a/src/agentomatic/optimize/synthesizer.py b/src/agentomatic/optimize/synthesizer.py index 5afcd1e4..87dc198c 100644 --- a/src/agentomatic/optimize/synthesizer.py +++ b/src/agentomatic/optimize/synthesizer.py @@ -528,8 +528,15 @@ def _norm(text: str) -> str: seen = {_norm(q) for q in (existing_queries or [])} seen.update(_norm(p.query) for p in seeds) protected = [_norm(q) for q in (protected_queries or []) if q] - pairs = [(i, strat) for i in range(len(seeds)) for strat in strategies] - random.Random(rng_seed).shuffle(pairs) + # Shuffled seeds, strategies rotating call by call: a short run still + # mixes every strategy, a long one covers every (seed, strategy) pair. + order = list(range(len(seeds))) + random.Random(rng_seed).shuffle(order) + pairs = [ + (seed_idx, strategies[(pos + rnd) % len(strategies)]) + for rnd in range(len(strategies)) + for pos, seed_idx in enumerate(order) + ] per_call = max(1, int(per_call)) budget = max_calls if max_calls is not None else 2 * -(-n_new // per_call) + 4 @@ -932,7 +939,8 @@ def _item_to_point(item: dict[str, Any]) -> DataPoint | None: expected = item.get(key) if isinstance(expected, dict): expected = json.dumps(expected, ensure_ascii=False) - context = item.get("context") if isinstance(item.get("context"), list) else [] + raw_context = item.get("context") + context: list[Any] = raw_context if isinstance(raw_context, list) else [] metadata = { k: v for k, v in item.items() diff --git a/src/agentomatic/optimize/train_api.py b/src/agentomatic/optimize/train_api.py index e6576d6a..f46bc04e 100644 --- a/src/agentomatic/optimize/train_api.py +++ b/src/agentomatic/optimize/train_api.py @@ -91,6 +91,9 @@ class TrainConfig: fit_store_url: Explicit DB URL for auditable retrain persistence (overrides env). Same dialects as platform storage (Postgres, SQLite, …). + evaluate_baseline: Also evaluate the held-out split *before* fit so + the report shows per-example answers and scores before vs after + (one extra pass over the test split). Default ``True``. """ agent_name: str @@ -133,6 +136,8 @@ class TrainConfig: # --- auditable fit / retrain persistence -------------------------------- persist_fit_store: bool = False fit_store_url: str | None = None + # --- reporting ----------------------------------------------------------- + evaluate_baseline: bool = True def __post_init__(self) -> None: """Normalise ``nr_examples`` → ``n_examples`` alias.""" @@ -158,6 +163,11 @@ class TrainResult: augmented: bool = False persist_path: Path | None = None agent_name: str = "" + baseline_eval_scores: dict[str, float] = field(default_factory=dict) + """Held-out scores *before* fit (empty with ``evaluate_baseline=False``).""" + fit_results: list[Any] = field(default_factory=list) + """One ``PromptFitResult`` per epoch; ``fit_result`` merges them (initial + prompt → final prompt across all epochs).""" def print_summary(self, console: Any | None = None) -> None: """Pretty-print a Rich summary of this train run. @@ -226,7 +236,9 @@ def print_train_result(result: TrainResult, *, console: Any | None = None) -> No f"prompt_changed={base_p != best_p} base_len={len(base_p)} best_len={len(best_p)}" ) - console.print(f"evaluate scores={result.eval_scores}") + if result.baseline_eval_scores: + console.print(f"held-out scores before fit={result.baseline_eval_scores}") + console.print(f"held-out scores after fit={result.eval_scores}") console.print(f"[green]Report:[/green] {result.report_path}") try: rsize = Path(result.report_path).stat().st_size if result.report_path else 0 @@ -728,6 +740,11 @@ def fit_result(self) -> Any | None: """Last :class:`~agentomatic.optimize.PromptFitResult` from fit.""" return getattr(self.agent, "_last_fit_result", None) + @property + def fit_results(self) -> list[Any]: + """Every epoch's ``PromptFitResult`` from the last :func:`fit_agent`.""" + return list(getattr(self.agent, "_fit_results", None) or []) + @property def optimize_status(self) -> str: """Last optimize status string from the fitter bridge.""" @@ -1021,7 +1038,7 @@ def run_train( :class:`TrainResult` with history, fit artefacts, and report path. """ from agentomatic.config.settings import load_environment - from agentomatic.optimize.report import generate_fit_report + from agentomatic.optimize.report import generate_fit_report, merge_fit_results from agentomatic.providers import apply_stack_defaults from agentomatic.stacks.manager import StackManager @@ -1146,6 +1163,13 @@ def run_train( verbose=config.verbose, ) + # The split optimization never sees; scored before AND after fit so + # the report can show what changed, example by example. + held_out = dataset.test or dataset.validation or dataset.train + baseline_report = ( + evaluate_agent(compiled, held_out) if config.evaluate_baseline and held_out else None + ) + history = fit_agent( compiled, dataset, @@ -1160,19 +1184,27 @@ def run_train( ) status = compiled.optimize_status - fit_result = compiled.fit_result + # Every epoch's PromptFitResult, merged so reports and apply() compare + # the ORIGINAL prompt with the FINAL one (the last epoch alone starts + # from a prompt an earlier epoch already improved). + fit_results = list(getattr(history, "fit_results", None) or []) + if not fit_results and compiled.fit_result is not None: + fit_results = [compiled.fit_result] + fit_result = merge_fit_results(fit_results) if fit_results else None - held_out = dataset.test or dataset.validation or dataset.train eval_report = evaluate_agent(compiled, held_out) eval_scores = dict(getattr(eval_report, "scores", {}) or {}) out = reports / f"train_{config.agent_name}.html" if fit_result is not None: generate_fit_report( - fit_result, + fit_results, output_path=out, keras_history=getattr(history, "history", None), - eval_scores=eval_scores, + baseline_eval=baseline_report, + final_eval=eval_report, + eval_dataset=held_out, + dataset_stats=(getattr(dataset, "metadata", None) or {}).get("augment_stats"), dataset_sizes=sizes, optimizer_name=config.optimizer, stack_name=stack_name, @@ -1229,6 +1261,8 @@ def run_train( augmented=bool((getattr(dataset, "metadata", None) or {}).get("augmented")), persist_path=persist_written, agent_name=config.agent_name, + baseline_eval_scores=dict(getattr(baseline_report, "scores", None) or {}), + fit_results=fit_results, ) finally: if bound_fit_store is not None: diff --git a/tests/test_fit_report_content.py b/tests/test_fit_report_content.py new file mode 100644 index 00000000..ad40bbd4 --- /dev/null +++ b/tests/test_fit_report_content.py @@ -0,0 +1,321 @@ +# pyright: reportMissingParameterType=none +"""The fit report must show what the optimization changed and whether it helped. + +Reported: "I cannot see prompts. I cannot see scores … I cannot see what +changed in the prompts, the initial ones compared to the evolutions". Causes: + +* every prompt panel was a HolySheet ``Accordion`` — its viewer renders none + of them, so prompts, few-shot examples and per-example details were hidden; +* with ``epochs > 1`` only the LAST epoch's result was reported: its + "baseline" was the prompt an earlier epoch had already improved, so the + report compared the final prompt with itself and said "no improvement"; +* no before/after numbers on the untouched test split, no per-example + answers, and no reason why each candidate was accepted or rejected; +* single-line prompts diffed as one unreadable ``-``/``+`` pair. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from agentomatic.agents import AgentExample, History +from agentomatic.agents.types import EvaluationReport, ExampleResult +from agentomatic.optimize import PromptFitResult, generate_fit_report, merge_fit_results +from agentomatic.optimize.config import PromptRuntimeConfig +from agentomatic.optimize.holysheet_reports import _unified_diff + +INITIAL = "You are a support assistant. Help the customer." +MIDDLE = "You are a support assistant. Quote the policy snippet, then answer." +FINAL = "You are a precise support assistant. Quote the policy snippet verbatim, then answer." + + +def _epoch( + start: str, + best: str, + start_score: float, + best_score: float, + *, + name: str, + suggestions: list[str] | None = None, +) -> PromptFitResult: + improved = best != start + return PromptFitResult( + best_config=PromptRuntimeConfig(system_prompt=best), + baseline_config=PromptRuntimeConfig(system_prompt=start), + best_score=best_score, + baseline_score=start_score, + baseline_holdout_score=start_score, + holdout_score=best_score, + metric_deltas={"quality": best_score - start_score}, + suggestions=suggestions or [], + trials=[ + { + "round": 1, + "name": f"{name}_dup", + "phase": "skipped", + "decision": "duplicate", + "reason": "Identical to a config already evaluated", + "system_prompt": start, + }, + { + "round": 1, + "name": name, + "phase": "minibatch", + "score": best_score, + "decision": "promoted", + "system_prompt": best if improved else start + " (rejected edit)", + }, + { + "round": 1, + "name": name, + "phase": "full_val", + "score": best_score, + "incumbent_score": start_score, + "holdout_score": best_score, + "confidence": 0.97, + "decision": "accepted" if improved else "rejected", + "reason": "better on validation" if improved else "Not significant", + "system_prompt": best if improved else start + " (rejected edit)", + }, + ], + score_history=[start_score, best_score], + baseline_examples=[ + {"query": "Refund window?", "expected": "30 days", "response": "Hi!", "score": 0.0} + ], + best_examples=[ + {"query": "Refund window?", "expected": "30 days", "response": "30 days", "score": 1} + ], + duration_seconds=2.0, + agent="support_agent", + ) + + +def _epochs() -> list[PromptFitResult]: + """Epoch 1 improves, epoch 2 improves again, epoch 3 finds nothing.""" + return [ + _epoch(INITIAL, MIDDLE, 0.2, 0.6, name="e1", suggestions=["Quote the policy"]), + _epoch(MIDDLE, FINAL, 0.6, 0.8, name="e2", suggestions=["Say 'verbatim'"]), + _epoch(FINAL, FINAL, 0.8, 0.8, name="e3", suggestions=["No improvement"]), + ] + + +def _report(scores: dict[str, float], answers: dict[str, str]) -> EvaluationReport: + return EvaluationReport( + scores=scores, + example_results=[ + ExampleResult( + example_id=eid, + prediction={"response": text}, + scores={"quality": scores["quality"]}, + ) + for eid, text in answers.items() + ], + ) + + +TEST_SPLIT = [ + AgentExample( + id="t1", + input={"current_query": "Can I get my money back?"}, + expected_output={"response": "Within 30 days on annual plans."}, + split="test", + ) +] + + +class TestMergeFitResults: + def test_spans_the_original_prompt_to_the_final_one(self) -> None: + merged = merge_fit_results(_epochs()) + assert merged.baseline_config.system_prompt == INITIAL + assert merged.best_config.system_prompt == FINAL + assert merged.baseline_score == pytest.approx(0.2) + assert merged.best_score == pytest.approx(0.8) + assert merged.improved + assert [t["epoch"] for t in merged.trials] == [1, 1, 1, 2, 2, 2, 3, 3, 3] + assert merged.duration_seconds == pytest.approx(6.0) + assert merged.metric_deltas["quality"] == pytest.approx(0.6) + + def test_recommendations_come_from_the_epoch_that_produced_the_final_prompt(self) -> None: + merged = merge_fit_results(_epochs()) + assert merged.suggestions == ["Say 'verbatim'"] + + def test_the_last_epoch_alone_would_claim_no_improvement(self) -> None: + last = _epochs()[-1] + assert not last.improved + assert last.baseline_config.system_prompt == FINAL + + def test_inputs_are_not_modified(self) -> None: + epochs = _epochs() + merge_fit_results(epochs) + assert "epoch" not in epochs[0].trials[0] + assert epochs[-1].baseline_config.system_prompt == FINAL + + def test_needs_at_least_one_result(self) -> None: + with pytest.raises(ValueError, match="at least one"): + merge_fit_results([]) + + +class TestGenerateFitReportInputs: + def test_accepts_the_history_returned_by_fit(self, tmp_path: Path) -> None: + history = History() + history.record(-1, {"loss": 0.8, "val_loss": 0.8}) + history.record(0, {"loss": 0.2, "val_loss": 0.3}) + history.fit_results = _epochs() + path = generate_fit_report(history, output_path=tmp_path / "r.html") + sidecar = json.loads(Path(path).with_suffix(".json").read_text()) + assert sidecar["initial_prompt"] == INITIAL + assert sidecar["final_prompt"] == FINAL + assert sidecar["keras_history"]["val_loss"] == [0.8, 0.3] + assert len(sidecar["epochs"]) == 3 + + def test_accepts_the_fitted_agent(self, tmp_path: Path) -> None: + agent = SimpleNamespace(_fit_results=_epochs()) + path = generate_fit_report(agent, output_path=tmp_path / "r.html") + assert json.loads(Path(path).with_suffix(".json").read_text())["prompt_changed"] + + def test_rejects_unknown_objects_with_guidance(self) -> None: + with pytest.raises(TypeError, match="History returned by agent.fit"): + generate_fit_report(object()) + + def test_says_why_when_there_is_nothing_to_report(self) -> None: + with pytest.raises(ValueError, match="_last_optimize_status"): + generate_fit_report(History()) + + +class TestReportContent: + @pytest.fixture + def report(self, tmp_path: Path) -> tuple[str, dict[str, Any], list[dict[str, Any]]]: + path = generate_fit_report( + _epochs(), + output_path=tmp_path / "train_report.html", + baseline_eval=_report({"quality": 0.1}, {"t1": "Thanks for reaching out!"}), + final_eval=_report({"quality": 0.9}, {"t1": "Refunds within 30 days."}), + eval_dataset=TEST_SPLIT, + dataset_stats={"requested": 10, "added": 8, "by_strategy": {"paraphrase": 8}}, + ) + html = Path(path).read_text(encoding="utf-8") + sidecar = json.loads(Path(path).with_suffix(".json").read_text()) + return html, sidecar, _blocks(html) + + def test_sidecar_has_before_after_on_the_test_split(self, report) -> None: + _, sidecar, _ = report + assert sidecar["validation"] == {"initial": 0.2, "final": 0.8} + assert sidecar["test"] == {"before": {"quality": 0.1}, "after": {"quality": 0.9}} + row = sidecar["test_examples"][0] + assert row["question"] == "Can I get my money back?" + assert row["before"] == "Thanks for reaching out!" + assert row["after"] == "Refunds within 30 days." + assert row["Δ"] == "quality +0.80" + + def test_sections_exist_and_are_not_empty(self, report) -> None: + _, _, blocks = report + sections = { + (b.get("props") or {}).get("title"): (b.get("props") or {}).get("children") + for b in blocks + if b.get("type") == "section" + } + for title in ( + "Verdict", + "Test scoreboard", + "What changed in the prompt", + "Epochs", + "All candidates", + "Examples — before vs after", + "Data & settings", + ): + assert sections.get(title), f"{title!r} missing or empty" + + def test_prompts_are_visible_not_hidden_in_accordions(self, report) -> None: + html, _, blocks = report + assert not [b for b in blocks if b.get("type") == "accordion"] + code = "\n".join( + str((b.get("props") or {}).get("code", "")) + for b in blocks + if b.get("type") == "code_block" + ) + assert "-You are a support assistant. Help the customer." in code + assert "verbatim" in code + assert "(rejected edit)" in code # rejected candidates are shown too + assert "Thanks for reaching out!" in html + + def test_every_candidate_decision_and_reason_is_listed(self, report) -> None: + _, _, blocks = report + rows = [ + row + for b in blocks + if b.get("type") == "table" or "data" in (b.get("props") or {}) + for row in (b.get("props") or {}).get("data") or [] + if isinstance(row, dict) and "decision" in row + ] + decisions = {(r["epoch"], r["candidate"]): r["decision"] for r in rows} + assert decisions[(1, "e1")] == "accepted" + assert decisions[(3, "e3")] == "rejected" + assert decisions[(1, "e1_dup")] == "duplicate" + assert any("Not significant" in r["reason"] for r in rows) + + +class TestFallbackHtml: + def test_without_holysheet_the_report_still_shows_before_after( + self, tmp_path: Path, monkeypatch + ) -> None: + import agentomatic.optimize.holysheet_reports as hs + + def _missing(*_a: Any, **_k: Any) -> str: + raise ImportError("holysheet") + + monkeypatch.setattr(hs, "build_fit_holysheet_report", _missing) + path = generate_fit_report( + _epochs(), + output_path=tmp_path / "r.html", + baseline_eval_scores={"quality": 0.1}, + eval_scores={"quality": 0.9}, + ) + html = Path(path).read_text(encoding="utf-8") + assert "Test Scoreboard" in html and "+0.8000" in html + assert "Prompt Diff (initial → final)" in html + assert "Not significant" in html + + +class TestReadableDiff: + def test_long_single_line_prompts_diff_sentence_by_sentence(self) -> None: + before = "You are helpful. " * 12 + "Answer briefly." + after = "You are helpful. " * 12 + "Answer briefly and quote the policy." + diff = _unified_diff(before, after) + changed = [ + line + for line in diff.splitlines() + if line[:1] in "+-" and line[:3] not in ("+++", "---") + ] + assert len(changed) == 2 + assert all(len(line) <= 101 for line in diff.splitlines()) + + def test_identical_prompts_have_no_diff(self) -> None: + assert _unified_diff("same", "same") == "" + + +def _blocks(html: str) -> list[dict[str, Any]]: + """Every serialized HolySheet block (recursively) embedded in the page.""" + match = re.search(r'"blocks"\s*:\s*(\[.*?\])\s*,\s*"filters"', html, re.S) + assert match, "report JSON not found" + + def walk(items: list[Any]) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + for block in items: + if not isinstance(block, dict): + continue + out.append(block) + props = block.get("props") or {} + out.extend(walk(props.get("children") or [])) + for tab in props.get("tabs") or []: + out.extend(walk(tab.get("children") or [])) + for panel in props.get("panels") or []: + out.extend(walk(panel.get("children") or [])) + return out + + return walk(json.loads(match.group(1))) diff --git a/tests/test_train_api_and_holysheet.py b/tests/test_train_api_and_holysheet.py index b5b3234e..edbab54b 100644 --- a/tests/test_train_api_and_holysheet.py +++ b/tests/test_train_api_and_holysheet.py @@ -303,8 +303,16 @@ def _eval(*_a: Any, **_k: Any) -> _Report: ) result = train_api_mod.run_train(agent, config=cfg, dataset=ds) - assert calls == ["compile", "fit", "evaluate"] + # The held-out split is scored before AND after fit (before/after report). + assert calls == ["compile", "evaluate", "fit", "evaluate"] assert result.eval_scores == {"m": 0.7} + assert result.baseline_eval_scores == {"m": 0.7} + + calls.clear() + cfg.evaluate_baseline = False + result = train_api_mod.run_train(agent, config=cfg, dataset=ds) + assert calls == ["compile", "fit", "evaluate"] + assert result.baseline_eval_scores == {} assert result.optimizer == "rewrite" @@ -432,8 +440,12 @@ def _walk(items: list) -> list: if b.get("type") == "section" } assert sections.get("Run Configuration"), "Run Configuration section empty" - assert sections.get("Key Results"), "Key Results section empty" + assert sections.get("Verdict"), "Verdict section empty" + assert sections.get("What changed in the prompt"), "prompt diff section empty" + assert sections.get("All candidates"), "candidates section empty" assert sections.get("Recommendations"), "Recommendations section empty" + # HolySheet's viewer drops Accordion panels — nothing may hide in one. + assert not [b for b in flat if b.get("type") == "accordion"] # HolySheet interactive bundle is large; fallback is still richer than a stub. assert len(html) > 2000 From 7d04c785f13d6545ce4faa3909e10af3bec91907 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 19:51:53 +0000 Subject: [PATCH 07/16] feat(examples): working prompt-optimization examples, low to high level examples/prompt_optimization now holds a self-contained SupportAgent, a 26-row dataset with train/validation/holdout/test splits, and five scripts. Every script is commented step by step and lists each method's options, and each runs end to end in tests against a deterministic fake OpenAI-compatible server: * metrics_and_judges.py: every metric family, LLM judges (single, per-dimension, panel), composite objectives, adapters and losses, scored on three fixed answers. * data_augmentation.py: prepare_dataset strategies and options, leak protection, augment_stats. * anti_overfitting.py: the acceptance rules on hand-made numbers, then a fit where a prompt memorizing the validation answers is vetoed and a general one is kept. * low_level_prompt_fitter.py: PromptFitter with every knob, a before/after test evaluation, and a report. * train.py: the Keras-style compile/fit loop (the script from the report), now runnable with augmentation and a meaningful report. Library fixes found while doing this: * A metadata-reading class-agent metric inside a CompositeMetric scored 0 in agent.evaluate() and compile(metrics=...), but correctly inside the fitter. OptimizeMetricAdapter now exposes the example as the current scoring run. * Exported paired_improvement_confidence, GeneralizationCheck, EvalResult and coerce_judge_score. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- .gitignore | 1 + examples/prompt_optimization/README.md | 82 +++ examples/prompt_optimization/agent.py | 140 +++++ .../prompt_optimization/anti_overfitting.py | 212 +++++++ examples/prompt_optimization/common.py | 177 ++++++ .../prompt_optimization/data_augmentation.py | 144 +++++ .../datasets/support.jsonl | 26 + .../low_level_prompt_fitter.py | 288 ++++++++++ .../prompt_optimization/metrics_and_judges.py | 254 +++++++++ examples/prompt_optimization/train.py | 518 +++++++++++++----- src/agentomatic/agents/metrics.py | 43 +- src/agentomatic/optimize/__init__.py | 8 + tests/fake_openai_server.py | 8 +- tests/test_dataset_augmentation.py | 15 +- tests/test_metric_protocol_bridge.py | 16 + tests/test_prompt_optimization_examples.py | 150 +++++ 16 files changed, 1923 insertions(+), 159 deletions(-) create mode 100644 examples/prompt_optimization/README.md create mode 100644 examples/prompt_optimization/agent.py create mode 100644 examples/prompt_optimization/anti_overfitting.py create mode 100644 examples/prompt_optimization/common.py create mode 100644 examples/prompt_optimization/data_augmentation.py create mode 100644 examples/prompt_optimization/datasets/support.jsonl create mode 100644 examples/prompt_optimization/low_level_prompt_fitter.py create mode 100644 examples/prompt_optimization/metrics_and_judges.py create mode 100644 tests/test_prompt_optimization_examples.py diff --git a/.gitignore b/.gitignore index b599411f..0de049ad 100644 --- a/.gitignore +++ b/.gitignore @@ -48,3 +48,4 @@ site/ # Poetry (legacy) poetry.lock inspiration/ +examples/prompt_optimization/out/ diff --git a/examples/prompt_optimization/README.md b/examples/prompt_optimization/README.md new file mode 100644 index 00000000..c14f99fc --- /dev/null +++ b/examples/prompt_optimization/README.md @@ -0,0 +1,82 @@ +# Prompt optimization examples + +Runnable, commented examples of Agentomatic's prompt optimization, from "score +some answers" to a full Keras-style training run with an HTML report. They all +optimize the same small `SupportAgent` (`agent.py`), which answers Acme Cloud +customer questions from a policy knowledge base, on `datasets/support.jsonl`. + +| Script | Level | What you learn | +| --- | --- | --- | +| [`metrics_and_judges.py`](metrics_and_judges.py) | building blocks | Every metric family, LLM judges (single, per-dimension, panel), composite objectives, adapters between the two metric protocols, losses. Scores three fixed answers; no optimization. | +| [`data_augmentation.py`](data_augmentation.py) | building blocks | `prepare_dataset(augment=True)`: every strategy and option, leak protection, `augment_stats`. | +| [`anti_overfitting.py`](anti_overfitting.py) | mechanics | The acceptance rules on hand-made numbers, then a fit where a prompt that memorizes the validation answers is vetoed and a general one is kept. | +| [`low_level_prompt_fitter.py`](low_level_prompt_fitter.py) | low level | `PromptFitter` with every knob explicit: datasets, composite metric, search space, inner-loop callbacks, acceptance rules, before/after test evaluation, report. | +| [`train.py`](train.py) | high level | The class-agent workflow: `load_data` → `prepare_dataset` → metrics → loss → `PromptFitterBridge` → `compile` → `fit` → test evaluation → `generate_fit_report`. | + +Start with `metrics_and_judges.py` if you are choosing metrics, `train.py` if +you want the whole loop, and `low_level_prompt_fitter.py` when you need control +over every step. In a scaffolded project (`agentomatic init NAME --template +basic`), `agents/NAME/train.py` calls `train_and_report(...)`, which runs this +same loop from the project's stack configuration. + +## Running them + +Each example talks to an OpenAI-compatible model server. oMLX is the default; +llama.cpp, vLLM, LM Studio or Ollama's `/v1` work the same way. + +```bash +omlx serve --model Qwen3.5-9B-MLX-4bit # http://127.0.0.1:8000/v1 + +python examples/prompt_optimization/metrics_and_judges.py +python examples/prompt_optimization/data_augmentation.py --n-examples 40 +python examples/prompt_optimization/anti_overfitting.py +python examples/prompt_optimization/low_level_prompt_fitter.py --trials 8 +python examples/prompt_optimization/train.py --epochs 2 --trials 6 [--augment] +``` + +Shared flags (or environment variables), defined in `common.py`: + +| Flag | Environment variable | Default | +| --- | --- | --- | +| `--base-url` | `OMLX_BASE_URL` | `http://127.0.0.1:8000/v1` | +| `--api-key` | `OMLX_API_KEY` | `local` | +| `--model` | `AGENTOMATIC_LOCAL_MODEL` | `Qwen3.5-9B-MLX-4bit` | +| `--judge-model` | `EXAMPLE_JUDGE_MODEL` | same as `--model` | +| `--rewrite-model` | `EXAMPLE_REWRITE_MODEL` | same as `--model` | +| `--out-dir` | `EXAMPLE_OUT_DIR` | `examples/prompt_optimization/out` | +| `--log-level` | `AGENTOMATIC_LOG_LEVEL` | `INFO` | + +`train.py` writes `train_report.html` (+ `train_report.json`) and +`train_summary.json` to `--out-dir`; `low_level_prompt_fitter.py` writes +`low_level_report.html` and `low_level_result.json`. + +## The data + +`datasets/support.jsonl` has one JSON object per line: + +```json +{"id": "refund_2", "split": "validation", + "input": {"current_query": "I bought an annual plan last week. Can I still get my money back?"}, + "expected_output": {"response": "Yes. Annual plans can be refunded within 30 days of purchase."}, + "metadata": {"must_include": ["30 days"], "topic": "refund"}} +``` + +The four splits have four jobs, and keeping them apart is what stops the +optimizer from overfitting: + +| Split | Rows | Role | +| --- | --- | --- | +| `train` | 10 | What the optimizer **learns from**: failure analysis, judge feedback, few-shot demos. Augmentation only grows this split. | +| `validation` | 6 | What candidate prompts are **scored and selected on**. | +| `holdout` | 4 | A **veto-only gate**: a candidate that wins on validation but does not carry over here is rejected. Optional; without it a slice of validation is reserved. | +| `test` | 6 | **Never used by optimization.** Evaluate it before and after `fit()` for an unbiased number. | + +`metadata.must_include` feeds the deterministic `facts` metric +(`common.must_include_score`); any metadata you put there reaches class-agent +metrics during `fit()`, `evaluate()` and inside composite metrics. + +## Testing without a model server + +`tests/test_prompt_optimization_examples.py` runs every script end to end +against `tests/fake_openai_server.py`, a deterministic stand-in that plays the +agent, the judge, the prompt rewriter and the augmenter. diff --git a/examples/prompt_optimization/agent.py b/examples/prompt_optimization/agent.py new file mode 100644 index 00000000..96da5d66 --- /dev/null +++ b/examples/prompt_optimization/agent.py @@ -0,0 +1,140 @@ +"""Support agent shared by every prompt-optimization example. + +A small but realistic class agent: it retrieves the relevant policy snippets +from an in-memory knowledge base, then asks the model to answer with them. + +What the optimizer tunes is the **system prompt** (and, optionally, few-shot +examples and model parameters). The agent reads it through +:meth:`~agentomatic.agents.BaseGraphAgent.resolve_system_prompt`, which is the +hook every optimization path uses to inject a candidate prompt: + +1. ``system_prompt_override`` on the request (how candidates are scored), +2. ``compiled_config["system_prompt"]`` (what ``fit()`` keeps as the best), +3. the ``system_prompt`` class attribute below (the baseline). + +An agent that hardcodes its prompt inside a node cannot be optimized — always +go through ``resolve_system_prompt``. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Any + +from agentomatic.agents import BaseGraphAgent + +#: The facts the agent may use. Answers are only "right" if grounded here, so +#: a metric can check them deterministically (see ``datasets/support.jsonl``). +KNOWLEDGE_BASE: dict[str, str] = { + "refund": "Refunds are available within 30 days of purchase for annual plans only.", + "password": "Reset a password from Settings > Security > Reset password; links expire " + "after 15 minutes.", + "outage": "Service status and incident updates are published at status.acme.example.", + "export": "Workspace owners can export all data as CSV or JSON from Settings > Data.", + "seats": "Seats can be added any time; they are billed pro rata until the renewal date.", + "sso": "Single sign-on (SAML) is available on the Enterprise plan only.", + "support hours": "Human support is available Monday to Friday, 08:00-18:00 CET.", + "delete": "Deleted workspaces can be restored by support for 14 days, then are purged.", + "api": "The public API allows 600 requests per minute per workspace.", + "invoice": "Invoices are emailed to the billing contact and listed under Billing > Invoices.", +} + +#: Keyword patterns that route a question to a topic (a stand-in for a real +#: retriever — swap in a vector store via ``connections.py`` in a project). +TOPIC_PATTERNS: dict[str, str] = { + "refund": r"\brefund|money back|\bcancel", + "password": r"\bpassword", + "outage": r"\boutage|\bdown\b|\bstatus\b|\bincident", + "export": r"\bexport|\bdownload|\bbackup|\bcsv\b|\bjson\b", + "seats": r"\bseats?\b|\badd\b.*\busers?\b", + "sso": r"\bsso\b|\bsaml\b|single sign-on", + "support hours": r"support hours|reach support|\bsaturday|\bsunday|\bweekend", + "delete": r"\bdelet|\brestor|\brecover", + "api": r"\bapi\b|rate limit|\b429\b", + "invoice": r"\binvoice|\breceipt", +} + + +@dataclass +class SupportState: + """Per-run state of :class:`SupportAgent`.""" + + question: str = "" + snippets: list[str] = field(default_factory=list) + output: dict[str, Any] = field(default_factory=dict) + + +class SupportAgent(BaseGraphAgent[SupportState]): + """Answer customer questions from the knowledge base. + + Args: + llm: Any LangChain-style chat model (``.invoke(messages)``). ``None`` + makes the agent echo its retrieved snippets, which keeps the + examples importable without a model server. + """ + + agent_name = "support_agent" + agent_description = "Answers Acme Cloud customer questions from policy snippets" + + #: Baseline prompt. Deliberately vague so there is something to improve. + system_prompt = "You are a support assistant for Acme Cloud. Help the customer." + + def __init__(self, *, llm: Any = None) -> None: + super().__init__() + self.llm = llm + + # --- graph wiring ----------------------------------------------------- + + def build_graph(self) -> Any: + g = self.new_graph() + g.add_node("retrieve", self.retrieve) + g.add_node("answer", self.answer) + g.set_entry_point("retrieve") + g.add_edge("retrieve", "answer") + g.set_finish_point("answer") + return g.compile() + + # --- nodes -------------------------------------------------------------- + + def retrieve(self, state: SupportState) -> SupportState: + """Pick the knowledge-base snippets whose topic the question mentions.""" + question = state.question.lower() + state.snippets = [ + KNOWLEDGE_BASE[topic] + for topic, pattern in TOPIC_PATTERNS.items() + if re.search(pattern, question) + ] + return state + + def answer(self, state: SupportState) -> SupportState: + """Answer with the model, grounded in the retrieved snippets.""" + # The optimizer's candidate prompt arrives through this call. + prompt = self.resolve_system_prompt(default=self.system_prompt) + context = "\n".join(f"- {s}" for s in state.snippets) or "- (no matching policy)" + if self.llm is None: + text = " ".join(state.snippets) or "I could not find a matching policy." + else: + reply = self.llm.invoke( + [ + {"role": "system", "content": prompt}, + { + "role": "user", + "content": f"Policy snippets:\n{context}\n\nQuestion: {state.question}", + }, + ] + ) + text = str(getattr(reply, "content", reply)).strip() + state.output = {"response": text, "sources": list(state.snippets)} + return state + + # --- I/O contract ------------------------------------------------------- + + def input_to_state(self, data: dict[str, Any]) -> SupportState: + # REST sends ``query``; the platform normalises it to ``current_query``. + # Datasets may use ``question`` — accept all three. + question = data.get("current_query") or data.get("question") or data.get("query") or "" + return SupportState(question=str(question)) + + def state_to_output(self, state: SupportState) -> dict[str, Any]: + return state.output diff --git a/examples/prompt_optimization/anti_overfitting.py b/examples/prompt_optimization/anti_overfitting.py new file mode 100644 index 00000000..4f6b55b5 --- /dev/null +++ b/examples/prompt_optimization/anti_overfitting.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Anti-overfitting in prompt optimization — watch a memorizing prompt get rejected. + +An optimizer that is rewarded only for its validation score will happily +"improve" a prompt by pasting the validation answers into it. That prompt +scores perfectly on validation and no better anywhere else. Agentomatic's +fitter guards against it with separate data roles and acceptance rules: + +* TRAIN — what the optimizer learns from (failures, judge feedback); +* VALIDATION — what candidates are selected on; a win must be *significant* + (paired bootstrap over the validation examples, ``min_confidence``); +* HOLDOUT — a veto-only gate: the candidate must not regress there + (``holdout_tolerance``), must not open a validation/holdout gap + (``max_generalization_gap``), and must carry a share of its validation + gain over (``min_transfer_ratio``) — the rule memorisation fails; +* TEST — never used by the fitter; measure it yourself afterwards. + +Part 1 applies the rules to hand-made numbers (no model needed). +Part 2 runs ``PromptFitter`` with two scripted candidates — one that memorizes +the validation answers, one that states a general instruction — and shows +which one survives, and what each would have scored on the test split. + +Run:: + + python examples/prompt_optimization/anti_overfitting.py +""" + +from __future__ import annotations + +import asyncio +import dataclasses +import sys +from pathlib import Path +from typing import Any + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from agent import SupportAgent + +from common import ( + DATASET, + build_parser, + make_llm, + must_include_score, + settings_from, + setup_logging, +) + +GENERAL_PROMPT = ( + "You are a precise Acme Cloud support assistant. Quote the relevant policy snippet " + "verbatim, then answer in one short sentence. Never invent policy." +) + + +def part1_rules() -> None: + """The acceptance rules on hand-made numbers.""" + from agentomatic.optimize import check_generalization, paired_improvement_confidence + + print("── Part 1: the acceptance rules ──") + print( + "incumbent: validation 0.50, holdout 0.50; rules: gap 0.15, tolerance 0.02, transfer 0.25" + ) + scenarios = { + # name: (candidate validation, candidate holdout) + "general improvement": (0.80, 0.75), + "memorised validation": (1.00, 0.50), + "gain does not transfer": (0.62, 0.52), + "holdout regression": (0.52, 0.45), + "gap blows up": (0.95, 0.60), + } + for name, (val, hold) in scenarios.items(): + check = check_generalization( + fit_score=val, + holdout_score=hold, + baseline_fit=0.50, + baseline_holdout=0.50, + max_gap=0.15, + holdout_tolerance=0.02, + min_transfer_ratio=0.25, + ) + verdict = "ACCEPT" if check.ok else "REJECT" + print(f" {name:<22} val {val:.2f} holdout {hold:.2f} → {verdict}\n {check.reason}") + + # Significance: per-example validation scores of incumbent vs candidate. + incumbent = [0.0, 0.0, 1.0, 1.0, 0.0, 1.0] + lucky = [1.0, 0.0, 1.0, 1.0, 0.0, 1.0] # one example flipped — could be judge noise + solid = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0] # every failure fixed + for name, cand in (("one example flipped", lucky), ("every failure fixed", solid)): + p = paired_improvement_confidence(cand, incumbent) + verdict = "ACCEPT" if p >= 0.8 else "REJECT (not significant)" + print(f" {name:<22} P(candidate > incumbent) = {p:.2f} → {verdict}") + + +class ScriptedCandidates: + """A custom optimizer: any object with ``name`` and async ``propose(...)``. + + Real optimizers ("rewrite", "gepa_like", …) generate candidates from the + train failures; this one proposes a fixed prompt per round so the outcome + is easy to follow. + """ + + name = "scripted" + + def __init__(self, rounds: list[tuple[str, str]]) -> None: + self.rounds = rounds + + async def propose( + self, + current_config: Any, + eval_results: list[dict[str, Any]], + dataset_sample: list[dict[str, Any]], + search_space: Any, + iteration: int = 0, + context: Any = None, + ) -> list[Any]: + from agentomatic.optimize import PromptCandidate + + if iteration >= len(self.rounds): + return [] + name, prompt = self.rounds[iteration] + # Change the prompt, keep every other setting of the incumbent. + config = dataclasses.replace(current_config, system_prompt=prompt) + return [PromptCandidate(name=name, config=config, source=self.name)] + + +async def part2_fit(settings: Any) -> int: + """A real fit where the memorizing candidate is vetoed.""" + from agentomatic.agents import CallableMetric + from agentomatic.optimize import Dataset, PromptFitter, load_data + + print("\n── Part 2: a fit with a memorizing and a general candidate ──") + data = load_data(DATASET) + + def points(examples: list[Any]) -> Dataset: + return Dataset(points=[e.to_datapoint() for e in examples]) + + agent = SupportAgent(llm=make_llm(settings)) + # The overfit prompt: the VALIDATION questions with their answers. + memorized = "\n".join( + f"Q: {e.input['current_query']}\nA: {e.expected_output['response']}" + for e in data.validation + ) + memorizing_prompt = ( + f"{agent.system_prompt}\nAnswer these questions exactly as follows:\n{memorized}" + ) + + facts = CallableMetric("facts", must_include_score) # deterministic → reproducible + fitter = PromptFitter( + agent=agent.agent_name, + local_agent=agent, + optimizer=ScriptedCandidates( + [("memorize_validation", memorizing_prompt), ("general_instruction", GENERAL_PROMPT)] + ), + task_model=settings.task_spec, + rewrite_model=settings.rewrite_spec, + llm_base_url=settings.base_url, + llm_api_key=settings.api_key, + baseline_system_prompt=agent.system_prompt, + max_trials=8, # 2 rounds (one scripted candidate each) + patience=3, + min_absolute_improvement=0.01, + min_confidence=0.8, + max_generalization_gap=0.15, + holdout_tolerance=0.02, + min_transfer_ratio=0.25, + auto_report=False, + drain_seconds=0, + experiment_dir=str(settings.out_dir / ".fit_anti_overfitting"), + ) + result = await fitter.fit( + points(data.train), points(data.validation), facts, testset=points(data.holdout) + ) + + print(" candidate validation holdout decision reason") + for trial in result.trials: + if trial.get("phase") != "full_val": + continue + print( + f" {trial['name']:<22} {trial['score']:.2f} " + f"{trial.get('holdout_score') or 0.0:.2f} {trial['decision']:<10} " + f"{str(trial.get('reason'))[:70]}" + ) + + # What each prompt would have scored on the untouched TEST split. + async def test_score(prompt: str) -> float: + agent.compiled_config["system_prompt"] = prompt + report = await asyncio.to_thread(agent.evaluate, data.test, [facts]) + return float(report.scores["facts"]) + + print(" test split (never seen by the fitter):") + for name, prompt in ( + ("baseline", agent.system_prompt), + ("memorize_validation", memorizing_prompt), + ("general_instruction", GENERAL_PROMPT), + ): + print(f" {name:<22} facts = {await test_score(prompt):.2f}") + kept = result.best_prompt == GENERAL_PROMPT + print(f" kept prompt: {'general_instruction' if kept else 'something else'}") + return 0 if kept else 1 + + +def main(argv: list[str] | None = None) -> int: + """Run both parts.""" + args = build_parser(__doc__.splitlines()[0]).parse_args(argv) + settings = settings_from(args) + setup_logging(settings.log_level) + part1_rules() + return asyncio.run(part2_fit(settings)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/prompt_optimization/common.py b/examples/prompt_optimization/common.py new file mode 100644 index 00000000..dea5ac14 --- /dev/null +++ b/examples/prompt_optimization/common.py @@ -0,0 +1,177 @@ +"""Shared plumbing for the prompt-optimization examples. + +Every example accepts the same connection flags (or environment variables), +so you point them all at your model server once: + +===================== =========================== ================================ +Flag Environment variable Default +===================== =========================== ================================ +``--base-url`` ``OMLX_BASE_URL`` ``http://127.0.0.1:8000/v1`` +``--api-key`` ``OMLX_API_KEY`` ``local`` +``--model`` ``AGENTOMATIC_LOCAL_MODEL`` ``Qwen3.5-9B-MLX-4bit`` +``--judge-model`` ``EXAMPLE_JUDGE_MODEL`` same as ``--model`` +``--rewrite-model`` ``EXAMPLE_REWRITE_MODEL`` same as ``--model`` +``--out-dir`` ``EXAMPLE_OUT_DIR`` ``examples/prompt_optimization/out`` +``--log-level`` ``AGENTOMATIC_LOG_LEVEL`` ``INFO`` +===================== =========================== ================================ + +Any OpenAI-compatible server works (oMLX, llama.cpp, vLLM, LM Studio, Ollama's +``/v1``): only ``--base-url`` and ``--model`` change. Model *specs* passed to +the optimizer are ``"/"`` strings — ``omlx/…`` routes to the +OpenAI-compatible ``--base-url``; ``openai/…``, ``ollama/…``, ``gemini/…`` and +``litellm/…`` are the other providers. +""" + +from __future__ import annotations + +import argparse +import os +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +HERE = Path(__file__).resolve().parent +DATASET = HERE / "datasets" / "support.jsonl" + +# Let ``python examples/prompt_optimization/ + diff --git a/src/agentomatic/tasks/__init__.py b/src/agentomatic/tasks/__init__.py index f7ed1936..07206520 100644 --- a/src/agentomatic/tasks/__init__.py +++ b/src/agentomatic/tasks/__init__.py @@ -43,7 +43,7 @@ create_event_log, register_event_log_provider, ) -from .manager import TaskInputValidationError, TaskManager +from .manager import TargetFailedError, TaskInputValidationError, TaskManager from .models import ( TargetType, TaskEvent, @@ -73,6 +73,7 @@ "InMemoryTaskStore", "NullTaskEventLog", "SQLAlchemyTaskStore", + "TargetFailedError", "TargetNotFoundError", "TargetType", "TaskContext", diff --git a/src/agentomatic/tasks/dispatchers.py b/src/agentomatic/tasks/dispatchers.py index 55c7a834..905404ef 100644 --- a/src/agentomatic/tasks/dispatchers.py +++ b/src/agentomatic/tasks/dispatchers.py @@ -14,7 +14,7 @@ from loguru import logger from pydantic import ValidationError -from .manager import TaskInputValidationError +from .manager import TargetFailedError, TaskInputValidationError if TYPE_CHECKING: from agentomatic.core.registry import AgentRegistry @@ -278,7 +278,12 @@ async def run(target: str, payload: Any, ctx: TaskContext) -> Any: result = await endpoint.call(payload) else: result = await endpoint.handle(request) - return _to_jsonable(result) + jsonable = _to_jsonable(result) + if isinstance(jsonable, dict) and jsonable.get("ok") is False and "results" in jsonable: + raise TargetFailedError( + f"Endpoint '{target}': no upstream call succeeded", result=jsonable + ) + return jsonable return run @@ -386,6 +391,13 @@ async def checkpoint_cb(step_name: str, index: int, sub_result: Any) -> None: jsonable = _to_jsonable(result) if isinstance(jsonable, dict) and partial: jsonable.setdefault("checkpoints", partial) + # ``partial`` (some steps failed under on_error: continue) is a + # completed run; ``failed`` is not. + if str(getattr(result, "status", "")) == "failed": + raise TargetFailedError( + f"Pipeline '{target}' failed: {getattr(result, 'error', None) or 'see steps'}", + result=jsonable, + ) return jsonable return run diff --git a/src/agentomatic/tasks/manager.py b/src/agentomatic/tasks/manager.py index ec18a66e..bbc057ce 100644 --- a/src/agentomatic/tasks/manager.py +++ b/src/agentomatic/tasks/manager.py @@ -55,6 +55,24 @@ class TaskInputValidationError(ValueError): """Raised when a resource rejects a task payload before it is queued.""" +class TargetFailedError(RuntimeError): + """The target ran to completion but reported a failure. + + A pipeline whose status is ``failed`` or an endpoint whose every upstream + call failed returns normally, so its task used to be marked ``succeeded``. + Dispatchers raise this instead; the task is marked ``failed`` and keeps + the target's own result (step errors, upstream responses) for debugging. + + Args: + message: What failed, shown as the task's error. + result: The JSON-safe result the target returned. + """ + + def __init__(self, message: str, result: Any = None) -> None: + super().__init__(message) + self.result = result + + class TaskManager: """Run and track platform resources as uniform, cancellable tasks. @@ -390,6 +408,17 @@ async def _run(self, record: TaskRecord, batch_concurrency: int | None) -> None: if delay > 0: await asyncio.sleep(delay) + if isinstance(last_error, TargetFailedError): + # The target's own report (e.g. which pipeline step failed and + # why) — already what its HTTP route returns, so not sanitised. + logger.error(f"Task {record.id} failed: {last_error}") + await self._finalize( + record, + TaskStatus.FAILED, + result=last_error.result, + error=str(last_error), + ) + return logger.exception(f"Task {record.id} failed after {record.attempts} attempts") # Raw exception text routinely carries DSNs/paths, and this # record is served verbatim by GET /tasks/{id}, /result and the @@ -444,6 +473,8 @@ async def run_item(index: int, payload: Any) -> None: raise asyncio.CancelledError try: results[index] = await dispatcher(record.target, payload, ctx) + except TargetFailedError as exc: + results[index] = {"error": str(exc), "result": exc.result} except Exception as exc: # noqa: BLE001 - collect per-item errors # Per-item errors are returned to the caller too. results[index] = { diff --git a/tests/test_connections.py b/tests/test_connections.py index 32e40525..648c8892 100644 --- a/tests/test_connections.py +++ b/tests/test_connections.py @@ -528,6 +528,41 @@ async def call_next(request): assert captured["connections"].get("svc") is not None +async def test_connections_middleware_resolves_a_slug_to_the_agent_scope(): + """URLs may use the slug; the scope is keyed by the registered name.""" + from types import SimpleNamespace + + from agentomatic.core.manifest import AgentManifest, RegisteredAgent + from agentomatic.core.registry import AgentRegistry + from agentomatic.middleware.connections import ConnectionsMiddleware + + register_connections( + "weather_bot", [HttpConnectionConfig(name="svc", base_url="https://svc.test")] + ) + registry = AgentRegistry() + agent = RegisteredAgent( + manifest=AgentManifest(name="weather_bot", slug="weather-bot", description="d") + ) + registry._agents["weather_bot"] = agent # noqa: SLF001 - as discovery does + registry._index_slug("weather_bot", agent) # noqa: SLF001 + mw = ConnectionsMiddleware(app=object(), registry=registry, api_prefix="/api/v1") + + captured = {} + + async def call_next(request): + captured["connections"] = request.state.connections + captured["agent"] = request.state.agent_name + return "ok" + + request = SimpleNamespace( + url=SimpleNamespace(path="/api/v1/weather-bot/chat"), + state=SimpleNamespace(), + ) + await mw.dispatch(request, call_next) + assert captured["agent"] == "weather_bot" + assert captured["connections"].get("svc") is not None + + async def test_connections_middleware_falls_back_to_platform(): from types import SimpleNamespace diff --git a/tests/test_fit_optimizer_matrix.py b/tests/test_fit_optimizer_matrix.py index 656a6dbd..44bd98be 100644 --- a/tests/test_fit_optimizer_matrix.py +++ b/tests/test_fit_optimizer_matrix.py @@ -322,8 +322,12 @@ def test_train_template_uses_run_train() -> None: assert "result = train_and_report(" in src assert "# compiled = compile_agent(" in src assert "# history = fit_agent(" in src - assert "# scores = evaluate_agent(" in src - assert "# generate_fit_report(" in src + # The held-out split is scored before and after fit, and the report gets + # the History (all epochs: original prompt → final prompt). + assert "# before = evaluate_agent(" in src + assert "# after = evaluate_agent(" in src + assert "# generate_fit_report(history," in src + assert "baseline_eval=before, final_eval=after" in src def test_eval_template_uses_evaluate_and_report() -> None: diff --git a/tests/test_pipeline_condition_errors.py b/tests/test_pipeline_condition_errors.py index 5bbced1a..54f27e80 100644 --- a/tests/test_pipeline_condition_errors.py +++ b/tests/test_pipeline_condition_errors.py @@ -158,3 +158,53 @@ def test_on_error_skip_still_lets_the_pipeline_continue(self, tmp_path) -> None: assert body["steps"]["branch"]["status"] == "failed" assert body["steps"]["after"]["status"] == "success" + + +PIPELINE_CONTINUE = """ +name: continue_condition +on_error: continue +steps: + - name: seed + transform: "return {'n': 4}" + - name: branch + condition: "ctx.get_step_output('seed').get('n') > 2 and missing_name" + transform: "return {'branch': 'long'}" + - name: after + transform: "return {'done': True}" +""" + + +class TestPipelineLevelContinue: + def test_pipeline_on_error_continue_applies_to_condition_errors(self, tmp_path) -> None: + """``on_error: continue`` used to be ignored for condition failures.""" + with TestClient(_platform(tmp_path, PIPELINE_CONTINUE).build()) as client: + body = client.post( + "/api/v1/pipelines/continue_condition/run", json={"input": {}} + ).json() + + assert body["steps"]["branch"]["status"] == "failed" + assert body["steps"]["after"]["status"] == "success" + assert body["status"] == "partial" + + +def test_the_scaffolded_pipeline_template_declares_real_contracts() -> None: + """``--template pipeline`` wrote ``input:``/``output:`` (ignored keys) and a + ``ctx.steps..output`` condition that always raised at run time.""" + from agentomatic.cli.templates import _pipeline_yaml + from agentomatic.pipelines.context import PipelineContext + from agentomatic.pipelines.engine import PipelineEngine + from agentomatic.pipelines.loader import PipelineLoader + from agentomatic.pipelines.models import StepResult, StepStatus + + config = PipelineLoader.from_yaml_string(_pipeline_yaml("scaffolded")) + assert config.input_schema == {"query": {"type": "string", "required": True}} + assert config.output_schema is not None + + ctx = PipelineContext(input_data={"query": "q"}) + ctx.steps["classify"] = StepResult( + name="classify", status=StepStatus.SUCCESS, output={"response": "billing"} + ) + engine = PipelineEngine.__new__(PipelineEngine) + for step in config.steps: + if getattr(step, "condition", None): + assert engine._evaluate_condition(step.condition, ctx) is True # noqa: SLF001 diff --git a/tests/test_studio_bundle.py b/tests/test_studio_bundle.py new file mode 100644 index 00000000..0825b3f2 --- /dev/null +++ b/tests/test_studio_bundle.py @@ -0,0 +1,64 @@ +"""The prebuilt Studio bundle must be loadable and free of known defects. + +The bundle under ``src/agentomatic/studio/static`` is built from the +``agentomatic-studio`` repository. These checks run on the shipped files: + +* every asset ``index.html`` and the chunks reference exists (assets are + served ``immutable``, so a changed file is re-hashed and every reference + must follow); +* the Chat tab sends the typed message as ``query`` — a string message was + dropped from the request body, so every agent answered an empty question; +* message ids are normalised to strings — SQL / memory stores return integer + ids and ``id.includes(...)`` crashed the chat view; +* operation contracts resolve templated routes, so the Task Board can load + the input form of ``/api/v1/pipelines/{name}/run``. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[1] / "src" / "agentomatic" / "studio" / "static" +ASSETS = STATIC / "assets" + + +def _entry() -> str: + match = re.search( + r'src="/studio/ui/assets/(index-[\w-]+\.js)"', (STATIC / "index.html").read_text() + ) + assert match, "index.html has no entry script" + return (ASSETS / match.group(1)).read_text(encoding="utf-8") + + +def test_every_referenced_asset_exists() -> None: + names = {p.name for p in ASSETS.iterdir()} + sources = [(STATIC / "index.html").read_text()] + [ + p.read_text(encoding="utf-8") for p in ASSETS.glob("*.js") + ] + referenced = { + ref for text in sources for ref in re.findall(r"(?:assets/|\./)([\w-]+\.(?:js|css))", text) + } + missing = sorted(ref for ref in referenced if ref not in names) + assert not missing, missing + + +def test_chat_sends_a_typed_message_as_query() -> None: + entry = _entry() + # The defect: ``query`` was only sent when the input *object* had one. + buggy = re.search(r"\.\.\.(\w)&&\((\w)\|\|(\w)\.query\)\?\{query:\2\|\|\3\.query\}", entry) + assert buggy is None, "string chat input is dropped from the run request" + + +def test_message_ids_are_strings() -> None: + entry = _entry() + assert "normalizeMessage(e,t){return{id:e?.id||" not in entry + chat = next(ASSETS.glob("ChatView-*.js")).read_text(encoding="utf-8") + assert not re.search(r"\b\w\.id\.includes\(", chat) + + +def test_operation_contracts_match_templated_paths() -> None: + entry = _entry() + start = entry.index("async getOperationContract(") + body = entry[start : start + 1500] + assert "Object.keys(" in body and "RegExp(" in body, "no templated-path fallback" diff --git a/tests/test_task_target_failures.py b/tests/test_task_target_failures.py new file mode 100644 index 00000000..f7054595 --- /dev/null +++ b/tests/test_task_target_failures.py @@ -0,0 +1,105 @@ +# pyright: reportMissingParameterType=none +"""A task whose target reports failure must be marked ``failed``. + +Studio's Task Board showed ``succeeded`` for a pipeline whose status was +``failed`` and for an endpoint whose every upstream call failed: both return +normally (with the failure inside the result), and the task manager only +looked at whether the dispatcher raised. +""" + +from __future__ import annotations + +import time +from types import SimpleNamespace +from typing import Any + +import pytest +from fastapi.testclient import TestClient + +from agentomatic import AgentPlatform +from agentomatic.tasks import TargetFailedError +from agentomatic.tasks.dispatchers import make_endpoint_dispatcher + +FAILING = """ +name: failing_pipe +steps: + - name: boom + transform: "raise ValueError('upstream exploded')" + - name: after + transform: "return {'done': True}" +""" + +PARTIAL = """ +name: partial_pipe +on_error: continue +steps: + - name: boom + transform: "raise ValueError('upstream exploded')" + - name: after + transform: "return {'done': True}" +""" + + +@pytest.fixture +def client(tmp_path): + agents = tmp_path / "agents" + agents.mkdir() + pipelines = tmp_path / "pipelines" + pipelines.mkdir() + (pipelines / "failing_pipe.yaml").write_text(FAILING) + (pipelines / "partial_pipe.yaml").write_text(PARTIAL) + with TestClient(AgentPlatform(agents_dir=str(agents)).build()) as test_client: + yield test_client + + +def _run_task(client: TestClient, pipeline: str) -> dict[str, Any]: + response = client.post( + "/api/v1/tasks", + json={"target_type": "pipeline", "target": pipeline, "input": {}}, + ) + assert response.status_code == 202, response.text + task_id = response.json()["id"] + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + record = client.get(f"/api/v1/tasks/{task_id}").json() + if record["status"] in {"succeeded", "failed", "cancelled"}: + return record + time.sleep(0.05) + raise AssertionError("task did not finish") + + +class TestPipelineTasks: + def test_a_failed_pipeline_fails_its_task_and_keeps_the_details(self, client) -> None: + record = _run_task(client, "failing_pipe") + assert record["status"] == "failed" + assert "Pipeline 'failing_pipe' failed" in record["error"] + assert "boom" in record["error"] + assert record["result"]["steps"]["boom"]["status"] == "failed" + + def test_a_partial_pipeline_still_succeeds(self, client) -> None: + record = _run_task(client, "partial_pipe") + assert record["status"] == "succeeded" + assert record["result"]["status"] == "partial" + + +class TestEndpointTasks: + async def test_all_upstreams_failing_raises(self) -> None: + class _Schema: + @staticmethod + def model_validate(payload: Any) -> Any: + return payload + + async def handle(request: Any) -> dict[str, Any]: + return {"endpoint": "e", "ok": False, "results": [{"ok": False}], "aggregated": None} + + endpoint = SimpleNamespace(get_input_schema=lambda: _Schema, handle=handle) + registry = SimpleNamespace(get=lambda name: endpoint, list_names=lambda: ["e"]) + ctx = SimpleNamespace(report=_noop) + + with pytest.raises(TargetFailedError) as info: + await make_endpoint_dispatcher(registry)("e", {}, ctx) # type: ignore[arg-type] + assert info.value.result["ok"] is False + + +async def _noop(**_: Any) -> None: + return None diff --git a/tests/test_template_chat_threads_tasks.py b/tests/test_template_chat_threads_tasks.py index 71ec6326..665182e2 100644 --- a/tests/test_template_chat_threads_tasks.py +++ b/tests/test_template_chat_threads_tasks.py @@ -196,6 +196,55 @@ def test_basic_templates_send_a_real_system_message(project_app, template: str) assert _texts(payload)[-1] == "ping" +@pytest.mark.parametrize("template", ("basic", "full")) +def test_studio_debug_shows_state_and_history(project_app, template: str) -> None: + """The Debug view's State / Time-travel tabs were empty for class agents.""" + client, _ = project_app + agent = TEMPLATES[template] + thread_id = client.post(f"/api/v1/{agent}/threads", json={"title": "t"}).json()["id"] + _stream_turn(client, agent, thread_id, "debug me") + + state = client.get(f"/studio/agents/{agent}/threads/{thread_id}/state").json() + assert state["state"], state + assert state["checkpoint_id"] + history = client.get(f"/studio/agents/{agent}/threads/{thread_id}/history").json() + assert history, "no checkpoints recorded" + assert all(c["metadata"].get("node") for c in history) + assert history[0]["id"] == state["checkpoint_id"] # newest first + + +def test_agent_folder_pipelines_are_served(project_app) -> None: + """``agents//pipeline.yaml`` (the extraction template ships one) was + never discovered: the platform scanned the agents folder as a project root.""" + client, _ = project_app + listed = client.get("/api/v1/pipelines").json() + listed = listed["pipelines"] if isinstance(listed, dict) else listed + names = {p["name"] for p in listed} + assert TEMPLATES["extraction"] in names + + +def test_feedback_export_uses_the_default_store(project_app) -> None: + """With the default (ephemeral) store configured, export returned nothing: + the store dropped the query, response and correction.""" + client, _ = project_app + agent = TEMPLATES["basic"] + recorded = client.post( + f"/api/v1/{agent}/feedback", + json={ + "query": "What is the refund window?", + "response": "No idea.", + "correction": "30 days for annual plans.", + "rating": 1, + "user_id": "u", + }, + ) + assert recorded.status_code == 200, recorded.text + export = client.get(f"/api/v1/{agent}/feedback/export").json() + assert export["count"] >= 1 + rows = [line for line in export["data"].splitlines() if "refund window" in line] + assert rows and "30 days for annual plans." in rows[0] + + @pytest.mark.parametrize("template", list(TEMPLATES)) class TestTasks: def test_async_task_succeeds(self, project_app, template: str) -> None: From 9b88a7111ed98e6912a497c984d3410c9693bc60 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 20:35:34 +0000 Subject: [PATCH 10/16] chore: sync uv.lock with the 1.14.0 project version Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 31195ca5..f40cb16e 100644 --- a/uv.lock +++ b/uv.lock @@ -10,7 +10,7 @@ resolution-markers = [ [[package]] name = "agentomatic" -version = "1.13.0" +version = "1.14.0" source = { editable = "." } dependencies = [ { name = "click" }, From b5b60d121505c099f0ec90980ad3c1e54df44da0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 20:47:41 +0000 Subject: [PATCH 11/16] chore(studio): ship the Studio UI 0.4.1 build from source Replaces the hand-patched bundle with a build of agentomatic-studio 0.4.1 (`VITE_BASE_URL=/studio/ui/ npm run build`). That release carries the same fixes in source: * a typed chat message is sent as `query`; * integer message ids are normalised to strings; * pipeline input forms resolve through templated routes; * the header tab bar no longer runs under the agent picker. The bundle test now checks the source implementation of the templated-route lookup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- ...ew-Aw10hiXI.js => BuilderView-C296ULRo.js} | 2 +- ...tView-SPDbgpwb.js => ChatView-C7_FNxo9.js} | 2 +- ...fIgs5wX.js => ConnectionsView-Dvq88oBW.js} | 2 +- ...4D_JM4.js => ControlPlaneView-CC__Od52.js} | 2 +- ...View-v__T__mW.js => DebugView-Bwa7sy_c.js} | 2 +- ...-uQLIFHRE.js => EndpointsView-fCUdmgxr.js} | 2 +- ...View-bgnAIRJp.js => GraphView-CMqOwCTc.js} | 4 +- ...-q0ceZCW0.js => IngestorsView-Cd56f61k.js} | 2 +- ...CQ1.js => OutputSchemaSummary-C65WaRqI.js} | 2 +- ...-8o6MHHuZ.js => PipelinesView-DacXbEMw.js} | 2 +- ...ew-T_czY3dU.js => PluginsView-COAn7Q5V.js} | 2 +- ...orm-bIikrW9E.js => SchemaForm-DyHc2s7z.js} | 2 +- ...View-HJeIPOTt.js => TasksView-DAoR0f0z.js} | 2 +- .../studio/static/assets/index-A2k5j4o2.js | 197 ------------------ .../studio/static/assets/index-Czmh8XoR.css | 1 + .../studio/static/assets/index-DHb1ckAg.css | 1 - .../studio/static/assets/index-FSSL6O5F.js | 197 ++++++++++++++++++ src/agentomatic/studio/static/index.html | 4 +- tests/test_studio_bundle.py | 7 +- 19 files changed, 218 insertions(+), 217 deletions(-) rename src/agentomatic/studio/static/assets/{BuilderView-Aw10hiXI.js => BuilderView-C296ULRo.js} (99%) rename src/agentomatic/studio/static/assets/{ChatView-SPDbgpwb.js => ChatView-C7_FNxo9.js} (99%) rename src/agentomatic/studio/static/assets/{ConnectionsView-wfIgs5wX.js => ConnectionsView-Dvq88oBW.js} (97%) rename src/agentomatic/studio/static/assets/{ControlPlaneView-ba4D_JM4.js => ControlPlaneView-CC__Od52.js} (99%) rename src/agentomatic/studio/static/assets/{DebugView-v__T__mW.js => DebugView-Bwa7sy_c.js} (99%) rename src/agentomatic/studio/static/assets/{EndpointsView-uQLIFHRE.js => EndpointsView-fCUdmgxr.js} (97%) rename src/agentomatic/studio/static/assets/{GraphView-bgnAIRJp.js => GraphView-CMqOwCTc.js} (99%) rename src/agentomatic/studio/static/assets/{IngestorsView-q0ceZCW0.js => IngestorsView-Cd56f61k.js} (95%) rename src/agentomatic/studio/static/assets/{OutputSchemaSummary-DzWXQCQ1.js => OutputSchemaSummary-C65WaRqI.js} (97%) rename src/agentomatic/studio/static/assets/{PipelinesView-8o6MHHuZ.js => PipelinesView-DacXbEMw.js} (96%) rename src/agentomatic/studio/static/assets/{PluginsView-T_czY3dU.js => PluginsView-COAn7Q5V.js} (96%) rename src/agentomatic/studio/static/assets/{SchemaForm-bIikrW9E.js => SchemaForm-DyHc2s7z.js} (99%) rename src/agentomatic/studio/static/assets/{TasksView-HJeIPOTt.js => TasksView-DAoR0f0z.js} (98%) delete mode 100644 src/agentomatic/studio/static/assets/index-A2k5j4o2.js create mode 100644 src/agentomatic/studio/static/assets/index-Czmh8XoR.css delete mode 100644 src/agentomatic/studio/static/assets/index-DHb1ckAg.css create mode 100644 src/agentomatic/studio/static/assets/index-FSSL6O5F.js diff --git a/src/agentomatic/studio/static/assets/BuilderView-Aw10hiXI.js b/src/agentomatic/studio/static/assets/BuilderView-C296ULRo.js similarity index 99% rename from src/agentomatic/studio/static/assets/BuilderView-Aw10hiXI.js rename to src/agentomatic/studio/static/assets/BuilderView-C296ULRo.js index 05bf28f8..b8ddf955 100644 --- a/src/agentomatic/studio/static/assets/BuilderView-Aw10hiXI.js +++ b/src/agentomatic/studio/static/assets/BuilderView-C296ULRo.js @@ -1,4 +1,4 @@ -import{j as s,V as se,p as tt,a as ui,u as pi,A as di,F as Un,g as fi}from"./index-A2k5j4o2.js";import{r as y,R as mi}from"./react-vendor-BHJ3EV8m.js";import{F as gi,R as hi,L as xi,N as bi,B as yi,I as vi,G as Ni,P as ji,a as Si,b as yr,C as vr,c as Nr,T as Ai,d as jr,X as wt,e as vt,f as bn,g as yn,A as Sr}from"./ui-vendor-DIaV1y77.js";import{S as Ci}from"./SchemaForm-bIikrW9E.js";import"./syntax-vendor-ru7AzRyY.js";function $i({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"}))}const wi=y.forwardRef($i);function _i({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const ki=y.forwardRef(_i);function Ti({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17.25 6.75 22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3-4.5 16.5"}))}const Ei=y.forwardRef(Ti);function Ii({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"}))}const Oi=y.forwardRef(Ii),qe={agent:{label:"Agent",description:"Invoke a registered agent",icon:"Bot",badge:"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",accent:"border-blue-500"},plugin:{label:"Plugin",description:"Call an ML plugin predict",icon:"Puzzle",badge:"bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300",accent:"border-purple-500"},endpoint:{label:"Endpoint",description:"Call a custom endpoint",icon:"Globe",badge:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",accent:"border-emerald-500"},ingestion:{label:"Ingestion",description:"Run an ingestor",icon:"Inbox",badge:"bg-teal-100 text-teal-700 dark:bg-teal-900 dark:text-teal-300",accent:"border-teal-500"},transform:{label:"Transform",description:"Python code block",icon:"Braces",badge:"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",accent:"border-amber-500"},parallel:{label:"Parallel",description:"Fan out agent steps",icon:"Network",badge:"bg-pink-100 text-pink-700 dark:bg-pink-900 dark:text-pink-300",accent:"border-pink-500"},map:{label:"Map",description:"Agent over a list of items",icon:"ListTree",badge:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300",accent:"border-indigo-500"},loop:{label:"Loop",description:"Iterate an agent step",icon:"Repeat",badge:"bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300",accent:"border-orange-500"},sub_pipeline:{label:"Sub-pipeline",description:"Nest another pipeline",icon:"FolderTree",badge:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300",accent:"border-cyan-500"}},Bn=[{kind:"agent",label:"Agent step",description:"Invoke a registered agent"},{kind:"endpoint",label:"Endpoint step",description:"Call a custom endpoint"},{kind:"plugin",label:"Plugin step",description:"Call an ML plugin predict"},{kind:"ingestion",label:"Ingestion step",description:"Run an ingestor"},{kind:"transform",label:"Transform step",description:"Python code block"},{kind:"parallel",label:"Parallel container",description:"Fan out agent steps"},{kind:"map",label:"Map step",description:"Agent over a list of items"},{kind:"loop",label:"Loop container",description:"Iterate an agent step"},{kind:"sub_pipeline",label:"Sub-pipeline step",description:"Nest another pipeline"}];function Xt(e,t){switch(e){case"agent":return{name:t,agent:""};case"plugin":return{name:t,plugin:""};case"endpoint":return{name:t,endpoint:""};case"ingestion":return{name:t,ingestion:""};case"transform":return{name:t,transform:""};case"parallel":return{name:t,parallel:{steps:[]}};case"map":return{name:t,map:{agent:"",items:"$.input.items"}};case"loop":return{name:t,loop:{step:{}}};case"sub_pipeline":return{name:t,sub_pipeline:""}}}function Ri(e,t){return e==="parallel"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Xt("agent",`${t}_child_1`),children:[]}]:e==="loop"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Xt("agent",`${t}_child_1`),children:[]}]:[]}var L=Symbol("NOT_RESOLVED"),vn=Symbol("MERGE_KEY");function X(e,t){return{tagName:e,nodeKind:"scalar",implicit:t.implicit??!1,matchByTagPrefix:t.matchByTagPrefix??!1,implicitFirstChars:t.implicitFirstChars??null,resolve:t.resolve,identify:t.identify??null,represent:t.represent??(n=>String(n)),representTagName:t.representTagName??null}}function Nn(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"sequence",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addItem:t.addItem,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify??null,represent:t.represent??(r=>r),representTagName:t.representTagName??null}}function _t(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"mapping",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addPair:t.addPair,has:t.has,keys:t.keys,get:t.get,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify??null,represent:t.represent??(r=>r),representTagName:t.representTagName??null}}var Li=X("tag:yaml.org,2002:str",{resolve:e=>e,identify:e=>typeof e=="string"}),Fi=["","~","null","Null","NULL"],Pi=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Fi.indexOf(e)!==-1?null:L,identify:e=>e===null,represent:()=>"null"}),Di=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["n"],resolve:(e,t)=>e==="null"||t&&e===""?null:L,identify:e=>e===null,represent:()=>"null"}),Ui=["","~","null","Null","NULL"],Bi=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Ui.indexOf(e)!==-1?null:L,identify:e=>e===null,represent:()=>"null"}),Yi=["true","True","TRUE"],qi=["false","False","FALSE"],Ki=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","T","f","F"],resolve:e=>Yi.indexOf(e)!==-1?!0:qi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Hi=["true"],Vi=["false"],Wi=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","f"],resolve:e=>Hi.indexOf(e)!==-1?!0:Vi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Gi=["true","True","TRUE","y","Y","yes","Yes","YES","on","On","ON"],zi=["false","False","FALSE","n","N","no","No","NO","off","Off","OFF"],Ji=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["y","Y","n","N","t","T","f","F","o","O"],resolve:e=>Gi.indexOf(e)!==-1?!0:zi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Qi=new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$"),Xi=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function Mi(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function Zi(e,t){if(t){if(!Xi.test(e))return L}else if(!Qi.test(e))return L;const n=Mi(e);return Number.isFinite(n)?n:L}var Ar=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:Zi,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),ea=new RegExp("^-?(?:0|[1-9][0-9]*)$"),ta=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function na(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function ra(e,t){if(t){if(!ta.test(e))return L}else if(!ea.test(e))return L;const n=na(e);return Number.isFinite(n)?n:L}var ia=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:ra,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),aa=new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$");function sa(e){let t=e.replace(/_/g,""),n=1;if((t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b"))return n*parseInt(t.slice(2),2);if(t.startsWith("0x"))return n*parseInt(t.slice(2),16);if(t.includes(":")){let r=0;for(const i of t.split(":"))r=r*60+Number(i);return n*r}return t!=="0"&&t[0]==="0"?n*parseInt(t,8):n*parseInt(t,10)}function oa(e){if(!aa.test(e))return L;const t=sa(e);return Number.isFinite(t)?t:L}var Mt=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:oa,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),la=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),ca=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ua(e){if(!la.test(e))return L;let t=e.toLowerCase();const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;const r=n*parseFloat(t);return Number.isFinite(r)||ca.test(e)?r:L}function pa(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var Cr=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:ua,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:pa}),da=new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$"),fa=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ma(e,t){if(t){if(!fa.test(e))return L;let r=e.toLowerCase();const i=r[0]==="-"?-1:1;if("+-".includes(r[0])&&(r=r.slice(1)),r===".inf")return i===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(r===".nan")return NaN;const a=i*parseFloat(r);return Number.isFinite(a)?a:L}if(!da.test(e))return L;const n=Number(e);return Number.isFinite(n)?n:L}function ga(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var ha=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:ma,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:ga}),xa=new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),ba=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ya(e){if(!xa.test(e))return L;let t=e.toLowerCase().replace(/_/g,"");const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;let r=0;if(t.includes(":")){for(const i of t.split(":"))r=r*60+Number(i);r*=n}else r=n*parseFloat(t);return Number.isFinite(r)||ba.test(e)?r:L}function va(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var Zt=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:ya,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:va}),Na=X("tag:yaml.org,2002:merge",{implicit:!0,implicitFirstChars:["<"],resolve:(e,t)=>e==="<<"||t&&e===""?vn:L}),ja=/^[A-Za-z0-9+/]*={0,2}$/;function Sa(e){const t=e.replace(/\s/g,"");if(t.length%4!==0||!ja.test(t))return L;const n=atob(t),r=new Uint8Array(n.length);for(let i=0;iObject.prototype.toString.call(e)==="[object Uint8Array]",represent:Aa}),$a=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),wa=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function Yn(e,t,n,r=0,i=0,a=0,l=0){const o=new Date(Date.UTC(e,t,n,r,i,a,l));return o.setUTCFullYear(e,t,n),o}function _a(e){let t=$a.exec(e);if(t===null&&(t=wa.exec(e)),t===null)return L;const n=+t[1],r=+t[2]-1,i=+t[3];if(!t[4]){const c=Yn(n,r,i);return c.getUTCFullYear()!==n||c.getUTCMonth()!==r||c.getUTCDate()!==i?L:c}const a=+t[4],l=+t[5],o=+t[6];let u=0;if(a>23||l>59||o>59)return L;if(t[7]){let c=t[7].slice(0,3);for(;c.length<3;)c+="0";u=+c}const p=Yn(n,r,i,a,l,o,u);if(p.getUTCFullYear()!==n||p.getUTCMonth()!==r||p.getUTCDate()!==i)return L;if(t[9]){const c=+t[10],f=+(t[11]||0);if(c>23||f>59)return L;const m=(c*60+f)*6e4;p.setTime(p.getTime()-(t[9]==="-"?-m:m))}return p}var ka=X("tag:yaml.org,2002:timestamp",{implicit:!0,implicitFirstChars:[..."0123456789"],resolve:_a,identify:e=>e instanceof Date,represent:e=>e.toISOString()}),Ta=Nn("tag:yaml.org,2002:seq",{create:()=>[],addItem:(e,t)=>{e.push(t)},identify:Array.isArray});function kt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function en(e,t){const n={};for(const r of t)e[r]!==void 0&&(n[r]=e[r]);return n}var Ea=Nn("tag:yaml.org,2002:omap",{create:()=>({list:[],seen:new Set}),addItem:(e,t)=>{let n;if(t instanceof Map){if(t.size!==1)return"cannot resolve an ordered map item";n=t.keys().next().value}else if(kt(t)){const r=Object.keys(t);if(r.length!==1)return"cannot resolve an ordered map item";n=r[0]}else return"cannot resolve an ordered map item";return e.seen.has(n)?"duplicate key in ordered map":(e.seen.add(n),e.list.push(t),"")},finalize:e=>e.list}),Ia=Nn("tag:yaml.org,2002:pairs",{create:()=>[],addItem:(e,t)=>{if(t instanceof Map)return t.size!==1?"cannot resolve a pairs item":(e.push(t.entries().next().value),"");if(Object.prototype.toString.call(t)!=="[object Object]")return"cannot resolve a pairs item";const n=t,r=Object.keys(n);return r.length!==1?"cannot resolve a pairs item":(e.push([r[0],n[r[0]]]),"")}}),Oa=_t("tag:yaml.org,2002:map",{create:()=>({}),identify:kt,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{if(t!==null&&typeof t=="object")return"object-based map does not support complex keys";const r=String(t);return r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,""},has:(e,t)=>t!==null&&typeof t=="object"?!1:Object.prototype.hasOwnProperty.call(e,String(t)),keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}}),Ra=_t("tag:yaml.org,2002:set",{create:()=>new Set,identify:e=>e instanceof Set,represent:e=>{const t=new Map;for(const n of e)t.set(n,null);return t},addPair:(e,t,n)=>n!==null?"cannot resolve a set item":(e.add(t),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:()=>null});function La(){return{scalar:Object.create(null),sequence:Object.create(null),mapping:Object.create(null)}}function Fa(){return{scalar:[],sequence:[],mapping:[]}}function Pa(e){const t=[];for(const n of e){let r=t.length;for(let i=0;ic.implicitFirstChars===null),o=new Set;for(const c of r)if(c.implicitFirstChars!==null)for(const f of c.implicitFirstChars)o.add(f);const u=new Map;for(const c of o)u.set(c,r.filter(f=>f.implicitFirstChars===null||f.implicitFirstChars.indexOf(c)!==-1));const p=i.scalar["tag:yaml.org,2002:str"];if(!p)throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)");this.tags=n,this.implicitScalarTags=r,this.implicitScalarByFirstChar=u,this.implicitScalarAnyFirstChar=l,this.defaultScalarTag=p,this.defaultSequenceTag=i.sequence["tag:yaml.org,2002:seq"],this.defaultMappingTag=i.mapping["tag:yaml.org,2002:map"],this.exact=i,this.prefix=a}withTags(...t){let n=[];for(const r of t)n=n.concat(r);return new $r([...this.tags,...n])}},jn=new Tt([Li,Ta,Oa]);new Tt([...jn.tags,Di,Wi,ia,ha]);var Da=new Tt([...jn.tags,Pi,Ki,Ar,Cr]),Ua=new Tt([...jn.tags,Bi,Ji,Mt,Zt,ka,Na,Ca,Ea,Ia,Ra]);_t("tag:yaml.org,2002:map",{create:()=>new Map,addPair:(e,t,n)=>(e.set(t,n),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:(e,t)=>e.get(t),identify:e=>e instanceof Map||kt(e),represent:e=>{if(e instanceof Map)return e;const t=new Map,n=e;for(const r of Object.keys(n))t.set(r,n[r]);return t}});function qn(e){if(Array.isArray(e)){const t=Array.prototype.slice.call(e);for(let n=0;n({}),identify:kt,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{const r=qn(t);return r===null?"nested arrays are not supported inside keys":(r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,"")},has:(e,t)=>{const n=qn(t);return n!==null&&Object.prototype.hasOwnProperty.call(e,n)},keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}});var Ba={maxLength:79,indent:1,linesBefore:3,linesAfter:2};function Yt(e,t,n,r,i){let a="",l="";const o=Math.floor(i/2)-1;return r-t>o&&(a=" ... ",t=r-o+a.length),n-r>o&&(l=" ...",n=r+o-l.length),{str:a+e.slice(t,n).replace(/\t/g,"→")+l,pos:r-t+a.length}}function qt(e,t){return" ".repeat(Math.max(t-e.length,0))+e}function Ya(e,t){if(!e.buffer)return null;const n={...Ba,...t},r=/\r?\n|\r|\0/g,i=[0],a=[];let l,o=-1;for(;l=r.exec(e.buffer);)a.push(l.index),i.push(l.index+l[0].length),e.position<=l.index&&o<0&&(o=i.length-2);o<0&&(o=i.length-1);let u="";const p=Math.min(e.line+n.linesAfter,a.length).toString().length,c=n.maxLength-(n.indent+p+3);for(let m=1;m<=n.linesBefore&&!(o-m<0);m++){const b=Yt(e.buffer,i[o-m],a[o-m],e.position-(i[o]-i[o-m]),c);u=`${" ".repeat(n.indent)}${qt((e.line-m+1).toString(),p)} | ${b.str} +import{j as s,V as se,p as tt,a as ui,u as pi,A as di,F as Un,g as fi}from"./index-FSSL6O5F.js";import{r as y,R as mi}from"./react-vendor-BHJ3EV8m.js";import{F as gi,R as hi,L as xi,N as bi,B as yi,I as vi,G as Ni,P as ji,a as Si,b as yr,C as vr,c as Nr,T as Ai,d as jr,X as wt,e as vt,f as bn,g as yn,A as Sr}from"./ui-vendor-DIaV1y77.js";import{S as Ci}from"./SchemaForm-DyHc2s7z.js";import"./syntax-vendor-ru7AzRyY.js";function $i({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"}))}const wi=y.forwardRef($i);function _i({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const ki=y.forwardRef(_i);function Ti({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17.25 6.75 22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3-4.5 16.5"}))}const Ei=y.forwardRef(Ti);function Ii({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"}))}const Oi=y.forwardRef(Ii),qe={agent:{label:"Agent",description:"Invoke a registered agent",icon:"Bot",badge:"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",accent:"border-blue-500"},plugin:{label:"Plugin",description:"Call an ML plugin predict",icon:"Puzzle",badge:"bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300",accent:"border-purple-500"},endpoint:{label:"Endpoint",description:"Call a custom endpoint",icon:"Globe",badge:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",accent:"border-emerald-500"},ingestion:{label:"Ingestion",description:"Run an ingestor",icon:"Inbox",badge:"bg-teal-100 text-teal-700 dark:bg-teal-900 dark:text-teal-300",accent:"border-teal-500"},transform:{label:"Transform",description:"Python code block",icon:"Braces",badge:"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",accent:"border-amber-500"},parallel:{label:"Parallel",description:"Fan out agent steps",icon:"Network",badge:"bg-pink-100 text-pink-700 dark:bg-pink-900 dark:text-pink-300",accent:"border-pink-500"},map:{label:"Map",description:"Agent over a list of items",icon:"ListTree",badge:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300",accent:"border-indigo-500"},loop:{label:"Loop",description:"Iterate an agent step",icon:"Repeat",badge:"bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300",accent:"border-orange-500"},sub_pipeline:{label:"Sub-pipeline",description:"Nest another pipeline",icon:"FolderTree",badge:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300",accent:"border-cyan-500"}},Bn=[{kind:"agent",label:"Agent step",description:"Invoke a registered agent"},{kind:"endpoint",label:"Endpoint step",description:"Call a custom endpoint"},{kind:"plugin",label:"Plugin step",description:"Call an ML plugin predict"},{kind:"ingestion",label:"Ingestion step",description:"Run an ingestor"},{kind:"transform",label:"Transform step",description:"Python code block"},{kind:"parallel",label:"Parallel container",description:"Fan out agent steps"},{kind:"map",label:"Map step",description:"Agent over a list of items"},{kind:"loop",label:"Loop container",description:"Iterate an agent step"},{kind:"sub_pipeline",label:"Sub-pipeline step",description:"Nest another pipeline"}];function Xt(e,t){switch(e){case"agent":return{name:t,agent:""};case"plugin":return{name:t,plugin:""};case"endpoint":return{name:t,endpoint:""};case"ingestion":return{name:t,ingestion:""};case"transform":return{name:t,transform:""};case"parallel":return{name:t,parallel:{steps:[]}};case"map":return{name:t,map:{agent:"",items:"$.input.items"}};case"loop":return{name:t,loop:{step:{}}};case"sub_pipeline":return{name:t,sub_pipeline:""}}}function Ri(e,t){return e==="parallel"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Xt("agent",`${t}_child_1`),children:[]}]:e==="loop"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Xt("agent",`${t}_child_1`),children:[]}]:[]}var L=Symbol("NOT_RESOLVED"),vn=Symbol("MERGE_KEY");function X(e,t){return{tagName:e,nodeKind:"scalar",implicit:t.implicit??!1,matchByTagPrefix:t.matchByTagPrefix??!1,implicitFirstChars:t.implicitFirstChars??null,resolve:t.resolve,identify:t.identify??null,represent:t.represent??(n=>String(n)),representTagName:t.representTagName??null}}function Nn(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"sequence",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addItem:t.addItem,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify??null,represent:t.represent??(r=>r),representTagName:t.representTagName??null}}function _t(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"mapping",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addPair:t.addPair,has:t.has,keys:t.keys,get:t.get,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify??null,represent:t.represent??(r=>r),representTagName:t.representTagName??null}}var Li=X("tag:yaml.org,2002:str",{resolve:e=>e,identify:e=>typeof e=="string"}),Fi=["","~","null","Null","NULL"],Pi=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Fi.indexOf(e)!==-1?null:L,identify:e=>e===null,represent:()=>"null"}),Di=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["n"],resolve:(e,t)=>e==="null"||t&&e===""?null:L,identify:e=>e===null,represent:()=>"null"}),Ui=["","~","null","Null","NULL"],Bi=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Ui.indexOf(e)!==-1?null:L,identify:e=>e===null,represent:()=>"null"}),Yi=["true","True","TRUE"],qi=["false","False","FALSE"],Ki=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","T","f","F"],resolve:e=>Yi.indexOf(e)!==-1?!0:qi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Hi=["true"],Vi=["false"],Wi=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","f"],resolve:e=>Hi.indexOf(e)!==-1?!0:Vi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Gi=["true","True","TRUE","y","Y","yes","Yes","YES","on","On","ON"],zi=["false","False","FALSE","n","N","no","No","NO","off","Off","OFF"],Ji=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["y","Y","n","N","t","T","f","F","o","O"],resolve:e=>Gi.indexOf(e)!==-1?!0:zi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Qi=new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$"),Xi=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function Mi(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function Zi(e,t){if(t){if(!Xi.test(e))return L}else if(!Qi.test(e))return L;const n=Mi(e);return Number.isFinite(n)?n:L}var Ar=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:Zi,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),ea=new RegExp("^-?(?:0|[1-9][0-9]*)$"),ta=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function na(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function ra(e,t){if(t){if(!ta.test(e))return L}else if(!ea.test(e))return L;const n=na(e);return Number.isFinite(n)?n:L}var ia=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:ra,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),aa=new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$");function sa(e){let t=e.replace(/_/g,""),n=1;if((t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b"))return n*parseInt(t.slice(2),2);if(t.startsWith("0x"))return n*parseInt(t.slice(2),16);if(t.includes(":")){let r=0;for(const i of t.split(":"))r=r*60+Number(i);return n*r}return t!=="0"&&t[0]==="0"?n*parseInt(t,8):n*parseInt(t,10)}function oa(e){if(!aa.test(e))return L;const t=sa(e);return Number.isFinite(t)?t:L}var Mt=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:oa,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),la=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),ca=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ua(e){if(!la.test(e))return L;let t=e.toLowerCase();const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;const r=n*parseFloat(t);return Number.isFinite(r)||ca.test(e)?r:L}function pa(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var Cr=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:ua,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:pa}),da=new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$"),fa=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ma(e,t){if(t){if(!fa.test(e))return L;let r=e.toLowerCase();const i=r[0]==="-"?-1:1;if("+-".includes(r[0])&&(r=r.slice(1)),r===".inf")return i===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(r===".nan")return NaN;const a=i*parseFloat(r);return Number.isFinite(a)?a:L}if(!da.test(e))return L;const n=Number(e);return Number.isFinite(n)?n:L}function ga(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var ha=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:ma,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:ga}),xa=new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),ba=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ya(e){if(!xa.test(e))return L;let t=e.toLowerCase().replace(/_/g,"");const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;let r=0;if(t.includes(":")){for(const i of t.split(":"))r=r*60+Number(i);r*=n}else r=n*parseFloat(t);return Number.isFinite(r)||ba.test(e)?r:L}function va(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var Zt=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:ya,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:va}),Na=X("tag:yaml.org,2002:merge",{implicit:!0,implicitFirstChars:["<"],resolve:(e,t)=>e==="<<"||t&&e===""?vn:L}),ja=/^[A-Za-z0-9+/]*={0,2}$/;function Sa(e){const t=e.replace(/\s/g,"");if(t.length%4!==0||!ja.test(t))return L;const n=atob(t),r=new Uint8Array(n.length);for(let i=0;iObject.prototype.toString.call(e)==="[object Uint8Array]",represent:Aa}),$a=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),wa=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function Yn(e,t,n,r=0,i=0,a=0,l=0){const o=new Date(Date.UTC(e,t,n,r,i,a,l));return o.setUTCFullYear(e,t,n),o}function _a(e){let t=$a.exec(e);if(t===null&&(t=wa.exec(e)),t===null)return L;const n=+t[1],r=+t[2]-1,i=+t[3];if(!t[4]){const c=Yn(n,r,i);return c.getUTCFullYear()!==n||c.getUTCMonth()!==r||c.getUTCDate()!==i?L:c}const a=+t[4],l=+t[5],o=+t[6];let u=0;if(a>23||l>59||o>59)return L;if(t[7]){let c=t[7].slice(0,3);for(;c.length<3;)c+="0";u=+c}const p=Yn(n,r,i,a,l,o,u);if(p.getUTCFullYear()!==n||p.getUTCMonth()!==r||p.getUTCDate()!==i)return L;if(t[9]){const c=+t[10],f=+(t[11]||0);if(c>23||f>59)return L;const m=(c*60+f)*6e4;p.setTime(p.getTime()-(t[9]==="-"?-m:m))}return p}var ka=X("tag:yaml.org,2002:timestamp",{implicit:!0,implicitFirstChars:[..."0123456789"],resolve:_a,identify:e=>e instanceof Date,represent:e=>e.toISOString()}),Ta=Nn("tag:yaml.org,2002:seq",{create:()=>[],addItem:(e,t)=>{e.push(t)},identify:Array.isArray});function kt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function en(e,t){const n={};for(const r of t)e[r]!==void 0&&(n[r]=e[r]);return n}var Ea=Nn("tag:yaml.org,2002:omap",{create:()=>({list:[],seen:new Set}),addItem:(e,t)=>{let n;if(t instanceof Map){if(t.size!==1)return"cannot resolve an ordered map item";n=t.keys().next().value}else if(kt(t)){const r=Object.keys(t);if(r.length!==1)return"cannot resolve an ordered map item";n=r[0]}else return"cannot resolve an ordered map item";return e.seen.has(n)?"duplicate key in ordered map":(e.seen.add(n),e.list.push(t),"")},finalize:e=>e.list}),Ia=Nn("tag:yaml.org,2002:pairs",{create:()=>[],addItem:(e,t)=>{if(t instanceof Map)return t.size!==1?"cannot resolve a pairs item":(e.push(t.entries().next().value),"");if(Object.prototype.toString.call(t)!=="[object Object]")return"cannot resolve a pairs item";const n=t,r=Object.keys(n);return r.length!==1?"cannot resolve a pairs item":(e.push([r[0],n[r[0]]]),"")}}),Oa=_t("tag:yaml.org,2002:map",{create:()=>({}),identify:kt,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{if(t!==null&&typeof t=="object")return"object-based map does not support complex keys";const r=String(t);return r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,""},has:(e,t)=>t!==null&&typeof t=="object"?!1:Object.prototype.hasOwnProperty.call(e,String(t)),keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}}),Ra=_t("tag:yaml.org,2002:set",{create:()=>new Set,identify:e=>e instanceof Set,represent:e=>{const t=new Map;for(const n of e)t.set(n,null);return t},addPair:(e,t,n)=>n!==null?"cannot resolve a set item":(e.add(t),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:()=>null});function La(){return{scalar:Object.create(null),sequence:Object.create(null),mapping:Object.create(null)}}function Fa(){return{scalar:[],sequence:[],mapping:[]}}function Pa(e){const t=[];for(const n of e){let r=t.length;for(let i=0;ic.implicitFirstChars===null),o=new Set;for(const c of r)if(c.implicitFirstChars!==null)for(const f of c.implicitFirstChars)o.add(f);const u=new Map;for(const c of o)u.set(c,r.filter(f=>f.implicitFirstChars===null||f.implicitFirstChars.indexOf(c)!==-1));const p=i.scalar["tag:yaml.org,2002:str"];if(!p)throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)");this.tags=n,this.implicitScalarTags=r,this.implicitScalarByFirstChar=u,this.implicitScalarAnyFirstChar=l,this.defaultScalarTag=p,this.defaultSequenceTag=i.sequence["tag:yaml.org,2002:seq"],this.defaultMappingTag=i.mapping["tag:yaml.org,2002:map"],this.exact=i,this.prefix=a}withTags(...t){let n=[];for(const r of t)n=n.concat(r);return new $r([...this.tags,...n])}},jn=new Tt([Li,Ta,Oa]);new Tt([...jn.tags,Di,Wi,ia,ha]);var Da=new Tt([...jn.tags,Pi,Ki,Ar,Cr]),Ua=new Tt([...jn.tags,Bi,Ji,Mt,Zt,ka,Na,Ca,Ea,Ia,Ra]);_t("tag:yaml.org,2002:map",{create:()=>new Map,addPair:(e,t,n)=>(e.set(t,n),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:(e,t)=>e.get(t),identify:e=>e instanceof Map||kt(e),represent:e=>{if(e instanceof Map)return e;const t=new Map,n=e;for(const r of Object.keys(n))t.set(r,n[r]);return t}});function qn(e){if(Array.isArray(e)){const t=Array.prototype.slice.call(e);for(let n=0;n({}),identify:kt,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{const r=qn(t);return r===null?"nested arrays are not supported inside keys":(r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,"")},has:(e,t)=>{const n=qn(t);return n!==null&&Object.prototype.hasOwnProperty.call(e,n)},keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}});var Ba={maxLength:79,indent:1,linesBefore:3,linesAfter:2};function Yt(e,t,n,r,i){let a="",l="";const o=Math.floor(i/2)-1;return r-t>o&&(a=" ... ",t=r-o+a.length),n-r>o&&(l=" ...",n=r+o-l.length),{str:a+e.slice(t,n).replace(/\t/g,"→")+l,pos:r-t+a.length}}function qt(e,t){return" ".repeat(Math.max(t-e.length,0))+e}function Ya(e,t){if(!e.buffer)return null;const n={...Ba,...t},r=/\r?\n|\r|\0/g,i=[0],a=[];let l,o=-1;for(;l=r.exec(e.buffer);)a.push(l.index),i.push(l.index+l[0].length),e.position<=l.index&&o<0&&(o=i.length-2);o<0&&(o=i.length-1);let u="";const p=Math.min(e.line+n.linesAfter,a.length).toString().length,c=n.maxLength-(n.indent+p+3);for(let m=1;m<=n.linesBefore&&!(o-m<0);m++){const b=Yt(e.buffer,i[o-m],a[o-m],e.position-(i[o]-i[o-m]),c);u=`${" ".repeat(n.indent)}${qt((e.line-m+1).toString(),p)} | ${b.str} ${u}`}const f=Yt(e.buffer,i[o],a[o],e.position,c);u+=`${" ".repeat(n.indent)}${qt((e.line+1).toString(),p)} | ${f.str} `,u+=`${"-".repeat(n.indent+p+3+f.pos)}^ `;for(let m=1;m<=n.linesAfter&&!(o+m>=a.length);m++){const b=Yt(e.buffer,i[o+m],a[o+m],e.position-(i[o]-i[o+m]),c);u+=`${" ".repeat(n.indent)}${qt((e.line+m+1).toString(),p)} | ${b.str} diff --git a/src/agentomatic/studio/static/assets/ChatView-SPDbgpwb.js b/src/agentomatic/studio/static/assets/ChatView-C7_FNxo9.js similarity index 99% rename from src/agentomatic/studio/static/assets/ChatView-SPDbgpwb.js rename to src/agentomatic/studio/static/assets/ChatView-C7_FNxo9.js index f8673010..5361c217 100644 --- a/src/agentomatic/studio/static/assets/ChatView-SPDbgpwb.js +++ b/src/agentomatic/studio/static/assets/ChatView-C7_FNxo9.js @@ -1,4 +1,4 @@ -import{u as qe,i as dr,d as mr,b as Ge,c as gr,j as d,V as Ve,f as xr,e as yr}from"./index-A2k5j4o2.js";import{r as M,g as Re,R as Ne}from"./react-vendor-BHJ3EV8m.js";import{S as br}from"./SchemaForm-bIikrW9E.js";import{O as _n}from"./OutputSchemaSummary-DzWXQCQ1.js";import{d as En,s as wr,b as kr}from"./syntax-vendor-ru7AzRyY.js";import{F as Sr}from"./ClipboardDocumentIcon-Cnz7XqGa.js";function vr({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M11.35 3.836c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75 2.25 2.25 0 0 0-.1-.664m-5.8 0A2.251 2.251 0 0 1 13.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m8.9-4.414c.376.023.75.05 1.124.08 1.131.094 1.976 1.057 1.976 2.192V16.5A2.25 2.25 0 0 1 18 18.75h-2.25m-7.5-10.5H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V18.75m-7.5-10.5h6.375c.621 0 1.125.504 1.125 1.125v9.375m-8.25-3 1.5 1.5 3-3.75"}))}const Cr=M.forwardRef(vr);function Er({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.98 8.223A10.477 10.477 0 0 0 1.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.451 10.451 0 0 1 12 4.5c4.756 0 8.773 3.162 10.065 7.498a10.522 10.522 0 0 1-4.293 5.774M6.228 6.228 3 3m3.228 3.228 3.65 3.65m7.894 7.894L21 21m-3.228-3.228-3.65-3.65m0 0a3 3 0 1 0-4.243-4.243m4.242 4.242L9.88 9.88"}))}const jr=M.forwardRef(Er);function Nr({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"}),M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const Ar=M.forwardRef(Nr);function Fr({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 12 3.269 3.125A59.769 59.769 0 0 1 21.485 12 59.768 59.768 0 0 1 3.27 20.875L5.999 12Zm0 0h7.5"}))}const Tr=M.forwardRef(Fr),$n=["http","https","mailto","tel"];function Ir(e){const n=(e||"").trim(),t=n.charAt(0);if(t==="#"||t==="/")return n;const r=n.indexOf(":");if(r===-1)return n;let i=-1;for(;++i<$n.length;){const l=$n[i];if(r===l.length&&n.slice(0,l.length).toLowerCase()===l)return n}return i=n.indexOf("?"),i!==-1&&r>i||(i=n.indexOf("#"),i!==-1&&r>i)?n:"javascript:void(0)"}var Je,Mn;function Lr(){return Mn||(Mn=1,Je=function(n){return n!=null&&n.constructor!=null&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}),Je}var Pr=Lr();const Et=Re(Pr);function De(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Hn(e.position):"start"in e||"end"in e?Hn(e):"line"in e||"column"in e?gn(e):""}function gn(e){return Un(e&&e.line)+":"+Un(e&&e.column)}function Hn(e){return gn(e&&e.start)+"-"+gn(e&&e.end)}function Un(e){return e&&typeof e=="number"?e:1}class he extends Error{constructor(n,t,r){const i=[null,null];let l={start:{line:null,column:null},end:{line:null,column:null}};if(super(),typeof t=="string"&&(r=t,t=void 0),typeof r=="string"){const a=r.indexOf(":");a===-1?i[1]=r:(i[0]=r.slice(0,a),i[1]=r.slice(a+1))}t&&("type"in t||"position"in t?t.position&&(l=t.position):"start"in t||"end"in t?l=t:("line"in t||"column"in t)&&(l.start=t)),this.name=De(t)||"1:1",this.message=typeof n=="object"?n.message:n,this.stack="",typeof n=="object"&&n.stack&&(this.stack=n.stack),this.reason=this.message,this.fatal,this.line=l.start.line,this.column=l.start.column,this.position=l,this.source=i[0],this.ruleId=i[1],this.file,this.actual,this.expected,this.url,this.note}}he.prototype.file="";he.prototype.name="";he.prototype.reason="";he.prototype.message="";he.prototype.stack="";he.prototype.fatal=null;he.prototype.column=null;he.prototype.line=null;he.prototype.source=null;he.prototype.ruleId=null;he.prototype.position=null;const ge={basename:Or,dirname:Dr,extname:zr,join:Rr,sep:"/"};function Or(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Be(e);let t=0,r=-1,i=e.length,l;if(n===void 0||n.length===0||n.length>e.length){for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else r<0&&(l=!0,r=i+1);return r<0?"":e.slice(t,r)}if(n===e)return"";let a=-1,o=n.length-1;for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else a<0&&(l=!0,a=i+1),o>-1&&(e.charCodeAt(i)===n.charCodeAt(o--)?o<0&&(r=i):(o=-1,r=a));return t===r?r=a:r<0&&(r=e.length),e.slice(t,r)}function Dr(e){if(Be(e),e.length===0)return".";let n=-1,t=e.length,r;for(;--t;)if(e.charCodeAt(t)===47){if(r){n=t;break}}else r||(r=!0);return n<0?e.charCodeAt(0)===47?"/":".":n===1&&e.charCodeAt(0)===47?"//":e.slice(0,n)}function zr(e){Be(e);let n=e.length,t=-1,r=0,i=-1,l=0,a;for(;n--;){const o=e.charCodeAt(n);if(o===47){if(a){r=n+1;break}continue}t<0&&(a=!0,t=n+1),o===46?i<0?i=n:l!==1&&(l=1):i>-1&&(l=-1)}return i<0||t<0||l===0||l===1&&i===t-1&&i===r+1?"":e.slice(i,t)}function Rr(...e){let n=-1,t;for(;++n0&&e.charCodeAt(e.length-1)===47&&(t+="/"),n?"/"+t:t}function _r(e,n){let t="",r=0,i=-1,l=0,a=-1,o,c;for(;++a<=e.length;){if(a2){if(c=t.lastIndexOf("/"),c!==t.length-1){c<0?(t="",r=0):(t=t.slice(0,c),r=t.length-1-t.lastIndexOf("/")),i=a,l=0;continue}}else if(t.length>0){t="",r=0,i=a,l=0;continue}}n&&(t=t.length>0?t+"/..":"..",r=2)}else t.length>0?t+="/"+e.slice(i+1,a):t=e.slice(i+1,a),r=a-i-1;i=a,l=0}else o===46&&l>-1?l++:l=-1}return t}function Be(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const $r={cwd:Mr};function Mr(){return"/"}function xn(e){return e!==null&&typeof e=="object"&&e.href&&e.origin}function Hr(e){if(typeof e=="string")e=new URL(e);else if(!xn(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return Ur(e)}function Ur(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const n=e.pathname;let t=-1;for(;++t"u"||e.call(s,g)},a=function(s,u){t&&u.name==="__proto__"?t(s,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):s[u.name]=u.newValue},o=function(s,u){if(u==="__proto__")if(e.call(s,u)){if(r)return r(s,u).value}else return;return s[u]};return tn=function c(){var s,u,h,g,f,j,b=arguments[0],x=1,k=arguments.length,S=!1;for(typeof b=="boolean"&&(S=b,b=arguments[1]||{},x=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});xa.length;let c;o&&a.push(i);try{c=e.apply(this,a)}catch(s){const u=s;if(o&&t)throw u;return i(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(l,i):c instanceof Error?i(c):l(c))}function i(a,...o){t||(t=!0,n(a,...o))}function l(a){i(null,a)}}const Yr=At().freeze(),Nt={}.hasOwnProperty;function At(){const e=Qr(),n=[];let t={},r,i=-1;return l.data=a,l.Parser=void 0,l.Compiler=void 0,l.freeze=o,l.attachers=n,l.use=c,l.parse=s,l.stringify=u,l.run=h,l.runSync=g,l.process=f,l.processSync=j,l;function l(){const b=At();let x=-1;for(;++x{if(y||!L||!B)$(y);else{const H=l.stringify(L,B);H==null||(Jr(H)?B.value=H:B.result=H),$(y,B)}});function $(y,L){y||!L?C(y):S?S(L):x(null,L)}}}function j(b){let x;l.freeze(),rn("processSync",l.Parser),ln("processSync",l.Compiler);const k=Oe(b);return l.process(k,S),Kn("processSync","process",x),k;function S(C){x=!0,Vn(C)}}}function Xn(e,n){return typeof e=="function"&&e.prototype&&(Kr(e.prototype)||n in e.prototype)}function Kr(e){let n;for(n in e)if(Nt.call(e,n))return!0;return!1}function rn(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Parser`")}function ln(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Compiler`")}function an(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Yn(e){if(!yn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Kn(e,n,t){if(!t)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Oe(e){return Gr(e)?e:new jt(e)}function Gr(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Jr(e){return typeof e=="string"||Et(e)}const Zr={};function ei(e,n){const t=Zr,r=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return Ft(e,r,i)}function Ft(e,n,t){if(ni(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Gn(e.children,n,t)}return Array.isArray(e)?Gn(e,n,t):""}function Gn(e,n,t){const r=[];let i=-1;for(;++ii?0:i+n:n=n>i?i:n,t=t>0?t:0,r.length<1e4)a=Array.from(r),a.unshift(n,t),e.splice(...a);else for(t&&e.splice(n,t);l0?(ye(e,e.length,0,n),e):n}const Jn={}.hasOwnProperty;function ti(e){const n={};let t=-1;for(;++ta))return;const L=n.events.length;let B=L,H,K;for(;B--;)if(n.events[B][0]==="exit"&&n.events[B][1].type==="chunkFlow"){if(H){K=n.events[B][1].end;break}H=!0}for(k(r),y=L;yC;){const $=t[F];n.containerState=$[1],$[0].exit.call(n,e)}t.length=C}function S(){i.write([null]),l=void 0,i=void 0,n.containerState._closeFlow=void 0}}function mi(e,n,t){return X(e,e.attempt(this.parser.constructs.document,n,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function et(e){if(e===null||re(e)||ci(e))return 1;if(ui(e))return 2}function jn(e,n,t){const r=[];let i=-1;for(;++i1&&e[t][1].end.offset-e[t][1].start.offset>1?2:1;const h=Object.assign({},e[r][1].end),g=Object.assign({},e[t][1].start);nt(h,-c),nt(g,c),a={type:c>1?"strongSequence":"emphasisSequence",start:h,end:Object.assign({},e[r][1].end)},o={type:c>1?"strongSequence":"emphasisSequence",start:Object.assign({},e[t][1].start),end:g},l={type:c>1?"strongText":"emphasisText",start:Object.assign({},e[r][1].end),end:Object.assign({},e[t][1].start)},i={type:c>1?"strong":"emphasis",start:Object.assign({},a.start),end:Object.assign({},o.end)},e[r][1].end=Object.assign({},a.start),e[t][1].start=Object.assign({},o.end),s=[],e[r][1].end.offset-e[r][1].start.offset&&(s=pe(s,[["enter",e[r][1],n],["exit",e[r][1],n]])),s=pe(s,[["enter",i,n],["enter",a,n],["exit",a,n],["enter",l,n]]),s=pe(s,jn(n.parser.constructs.insideSpan.null,e.slice(r+1,t),n)),s=pe(s,[["exit",l,n],["enter",o,n],["exit",o,n],["exit",i,n]]),e[t][1].end.offset-e[t][1].start.offset?(u=2,s=pe(s,[["enter",e[t][1],n],["exit",e[t][1],n]])):u=0,ye(e,r-1,t-r+3,s),t=r+s.length-u-2;break}}for(t=-1;++t0&&U(y)?X(e,S,"linePrefix",l+1)(y):S(y)}function S(y){return y===null||D(y)?e.check(tt,b,F)(y):(e.enter("codeFlowValue"),C(y))}function C(y){return y===null||D(y)?(e.exit("codeFlowValue"),S(y)):(e.consume(y),C)}function F(y){return e.exit("codeFenced"),n(y)}function $(y,L,B){let H=0;return K;function K(P){return y.enter("lineEnding"),y.consume(P),y.exit("lineEnding"),T}function T(P){return y.enter("codeFencedFence"),U(P)?X(y,A,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):A(P)}function A(P){return P===o?(y.enter("codeFencedFenceSequence"),N(P)):B(P)}function N(P){return P===o?(H++,y.consume(P),N):H>=a?(y.exit("codeFencedFenceSequence"),U(P)?X(y,I,"whitespace")(P):I(P)):B(P)}function I(P){return P===null||D(P)?(y.exit("codeFencedFence"),L(P)):B(P)}}}function Ni(e,n,t){const r=this;return i;function i(a){return a===null?t(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}const on={name:"codeIndented",tokenize:Fi},Ai={tokenize:Ti,partial:!0};function Fi(e,n,t){const r=this;return i;function i(s){return e.enter("codeIndented"),X(e,l,"linePrefix",5)(s)}function l(s){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?a(s):t(s)}function a(s){return s===null?c(s):D(s)?e.attempt(Ai,a,c)(s):(e.enter("codeFlowValue"),o(s))}function o(s){return s===null||D(s)?(e.exit("codeFlowValue"),a(s)):(e.consume(s),o)}function c(s){return e.exit("codeIndented"),n(s)}}function Ti(e,n,t){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?t(a):D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):X(e,l,"linePrefix",5)(a)}function l(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?n(a):D(a)?i(a):t(a)}}const Ii={name:"codeText",tokenize:Oi,resolve:Li,previous:Pi};function Li(e){let n=e.length-4,t=3,r,i;if((e[t][1].type==="lineEnding"||e[t][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(r=t;++r=4?n(a):e.interrupt(r.parser.constructs.flow,t,n)(a)}}function Ot(e,n,t,r,i,l,a,o,c){const s=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(k){return k===60?(e.enter(r),e.enter(i),e.enter(l),e.consume(k),e.exit(l),g):k===null||k===32||k===41||bn(k)?t(k):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),b(k))}function g(k){return k===62?(e.enter(l),e.consume(k),e.exit(l),e.exit(i),e.exit(r),n):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(k))}function f(k){return k===62?(e.exit("chunkString"),e.exit(o),g(k)):k===null||k===60||D(k)?t(k):(e.consume(k),k===92?j:f)}function j(k){return k===60||k===62||k===92?(e.consume(k),f):f(k)}function b(k){return!u&&(k===null||k===41||re(k))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),n(k)):u999||f===null||f===91||f===93&&!c||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?t(f):f===93?(e.exit(l),e.enter(i),e.consume(f),e.exit(i),e.exit(r),n):D(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||D(f)||o++>999?(e.exit("chunkString"),u(f)):(e.consume(f),c||(c=!U(f)),f===92?g:h)}function g(f){return f===91||f===92||f===93?(e.consume(f),o++,h):h(f)}}function zt(e,n,t,r,i,l){let a;return o;function o(g){return g===34||g===39||g===40?(e.enter(r),e.enter(i),e.consume(g),e.exit(i),a=g===40?41:g,c):t(g)}function c(g){return g===a?(e.enter(i),e.consume(g),e.exit(i),e.exit(r),n):(e.enter(l),s(g))}function s(g){return g===a?(e.exit(l),c(a)):g===null?t(g):D(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),X(e,s,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(g))}function u(g){return g===a||g===null||D(g)?(e.exit("chunkString"),s(g)):(e.consume(g),g===92?h:u)}function h(g){return g===a||g===92?(e.consume(g),u):u(g)}}function ze(e,n){let t;return r;function r(i){return D(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t=!0,r):U(i)?X(e,r,t?"linePrefix":"lineSuffix")(i):n(i)}}function Ae(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Mi={name:"definition",tokenize:Ui},Hi={tokenize:qi,partial:!0};function Ui(e,n,t){const r=this;let i;return l;function l(f){return e.enter("definition"),a(f)}function a(f){return Dt.call(r,e,o,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return i=Ae(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),c):t(f)}function c(f){return re(f)?ze(e,s)(f):s(f)}function s(f){return Ot(e,u,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return e.attempt(Hi,h,h)(f)}function h(f){return U(f)?X(e,g,"whitespace")(f):g(f)}function g(f){return f===null||D(f)?(e.exit("definition"),r.parser.defined.push(i),n(f)):t(f)}}function qi(e,n,t){return r;function r(o){return re(o)?ze(e,i)(o):t(o)}function i(o){return zt(e,l,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function l(o){return U(o)?X(e,a,"whitespace")(o):a(o)}function a(o){return o===null||D(o)?n(o):t(o)}}const Vi={name:"hardBreakEscape",tokenize:Wi};function Wi(e,n,t){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),i}function i(l){return D(l)?(e.exit("hardBreakEscape"),n(l)):t(l)}}const Qi={name:"headingAtx",tokenize:Yi,resolve:Xi};function Xi(e,n){let t=e.length-2,r=3,i,l;return e[r][1].type==="whitespace"&&(r+=2),t-2>r&&e[t][1].type==="whitespace"&&(t-=2),e[t][1].type==="atxHeadingSequence"&&(r===t-1||t-4>r&&e[t-2][1].type==="whitespace")&&(t-=r+1===t?2:4),t>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[t][1].end},l={type:"chunkText",start:e[r][1].start,end:e[t][1].end,contentType:"text"},ye(e,r,t-r+1,[["enter",i,n],["enter",l,n],["exit",l,n],["exit",i,n]])),e}function Yi(e,n,t){let r=0;return i;function i(u){return e.enter("atxHeading"),l(u)}function l(u){return e.enter("atxHeadingSequence"),a(u)}function a(u){return u===35&&r++<6?(e.consume(u),a):u===null||re(u)?(e.exit("atxHeadingSequence"),o(u)):t(u)}function o(u){return u===35?(e.enter("atxHeadingSequence"),c(u)):u===null||D(u)?(e.exit("atxHeading"),n(u)):U(u)?X(e,o,"whitespace")(u):(e.enter("atxHeadingText"),s(u))}function c(u){return u===35?(e.consume(u),c):(e.exit("atxHeadingSequence"),o(u))}function s(u){return u===null||u===35||re(u)?(e.exit("atxHeadingText"),o(u)):(e.consume(u),s)}}const Ki=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],it=["pre","script","style","textarea"],Gi={name:"htmlFlow",tokenize:nl,resolveTo:el,concrete:!0},Ji={tokenize:rl,partial:!0},Zi={tokenize:tl,partial:!0};function el(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function nl(e,n,t){const r=this;let i,l,a,o,c;return s;function s(p){return u(p)}function u(p){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(p),h}function h(p){return p===33?(e.consume(p),g):p===47?(e.consume(p),l=!0,b):p===63?(e.consume(p),i=3,r.interrupt?n:m):xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function g(p){return p===45?(e.consume(p),i=2,f):p===91?(e.consume(p),i=5,o=0,j):xe(p)?(e.consume(p),i=4,r.interrupt?n:m):t(p)}function f(p){return p===45?(e.consume(p),r.interrupt?n:m):t(p)}function j(p){const _="CDATA[";return p===_.charCodeAt(o++)?(e.consume(p),o===_.length?r.interrupt?n:A:j):t(p)}function b(p){return xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function x(p){if(p===null||p===47||p===62||re(p)){const _=p===47,se=a.toLowerCase();return!_&&!l&&it.includes(se)?(i=1,r.interrupt?n(p):A(p)):Ki.includes(a.toLowerCase())?(i=6,_?(e.consume(p),k):r.interrupt?n(p):A(p)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?t(p):l?S(p):C(p))}return p===45||oe(p)?(e.consume(p),a+=String.fromCharCode(p),x):t(p)}function k(p){return p===62?(e.consume(p),r.interrupt?n:A):t(p)}function S(p){return U(p)?(e.consume(p),S):K(p)}function C(p){return p===47?(e.consume(p),K):p===58||p===95||xe(p)?(e.consume(p),F):U(p)?(e.consume(p),C):K(p)}function F(p){return p===45||p===46||p===58||p===95||oe(p)?(e.consume(p),F):$(p)}function $(p){return p===61?(e.consume(p),y):U(p)?(e.consume(p),$):C(p)}function y(p){return p===null||p===60||p===61||p===62||p===96?t(p):p===34||p===39?(e.consume(p),c=p,L):U(p)?(e.consume(p),y):B(p)}function L(p){return p===c?(e.consume(p),c=null,H):p===null||D(p)?t(p):(e.consume(p),L)}function B(p){return p===null||p===34||p===39||p===47||p===60||p===61||p===62||p===96||re(p)?$(p):(e.consume(p),B)}function H(p){return p===47||p===62||U(p)?C(p):t(p)}function K(p){return p===62?(e.consume(p),T):t(p)}function T(p){return p===null||D(p)?A(p):U(p)?(e.consume(p),T):t(p)}function A(p){return p===45&&i===2?(e.consume(p),J):p===60&&i===1?(e.consume(p),Z):p===62&&i===4?(e.consume(p),ie):p===63&&i===3?(e.consume(p),m):p===93&&i===5?(e.consume(p),de):D(p)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Ji,le,N)(p)):p===null||D(p)?(e.exit("htmlFlowData"),N(p)):(e.consume(p),A)}function N(p){return e.check(Zi,I,le)(p)}function I(p){return e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),P}function P(p){return p===null||D(p)?N(p):(e.enter("htmlFlowData"),A(p))}function J(p){return p===45?(e.consume(p),m):A(p)}function Z(p){return p===47?(e.consume(p),a="",ne):A(p)}function ne(p){if(p===62){const _=a.toLowerCase();return it.includes(_)?(e.consume(p),ie):A(p)}return xe(p)&&a.length<8?(e.consume(p),a+=String.fromCharCode(p),ne):A(p)}function de(p){return p===93?(e.consume(p),m):A(p)}function m(p){return p===62?(e.consume(p),ie):p===45&&i===2?(e.consume(p),m):A(p)}function ie(p){return p===null||D(p)?(e.exit("htmlFlowData"),le(p)):(e.consume(p),ie)}function le(p){return e.exit("htmlFlow"),n(p)}}function tl(e,n,t){const r=this;return i;function i(a){return D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l):t(a)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}function rl(e,n,t){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Qe,n,t)}}const il={name:"htmlText",tokenize:ll};function ll(e,n,t){const r=this;let i,l,a;return o;function o(m){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(m),c}function c(m){return m===33?(e.consume(m),s):m===47?(e.consume(m),$):m===63?(e.consume(m),C):xe(m)?(e.consume(m),B):t(m)}function s(m){return m===45?(e.consume(m),u):m===91?(e.consume(m),l=0,j):xe(m)?(e.consume(m),S):t(m)}function u(m){return m===45?(e.consume(m),f):t(m)}function h(m){return m===null?t(m):m===45?(e.consume(m),g):D(m)?(a=h,Z(m)):(e.consume(m),h)}function g(m){return m===45?(e.consume(m),f):h(m)}function f(m){return m===62?J(m):m===45?g(m):h(m)}function j(m){const ie="CDATA[";return m===ie.charCodeAt(l++)?(e.consume(m),l===ie.length?b:j):t(m)}function b(m){return m===null?t(m):m===93?(e.consume(m),x):D(m)?(a=b,Z(m)):(e.consume(m),b)}function x(m){return m===93?(e.consume(m),k):b(m)}function k(m){return m===62?J(m):m===93?(e.consume(m),k):b(m)}function S(m){return m===null||m===62?J(m):D(m)?(a=S,Z(m)):(e.consume(m),S)}function C(m){return m===null?t(m):m===63?(e.consume(m),F):D(m)?(a=C,Z(m)):(e.consume(m),C)}function F(m){return m===62?J(m):C(m)}function $(m){return xe(m)?(e.consume(m),y):t(m)}function y(m){return m===45||oe(m)?(e.consume(m),y):L(m)}function L(m){return D(m)?(a=L,Z(m)):U(m)?(e.consume(m),L):J(m)}function B(m){return m===45||oe(m)?(e.consume(m),B):m===47||m===62||re(m)?H(m):t(m)}function H(m){return m===47?(e.consume(m),J):m===58||m===95||xe(m)?(e.consume(m),K):D(m)?(a=H,Z(m)):U(m)?(e.consume(m),H):J(m)}function K(m){return m===45||m===46||m===58||m===95||oe(m)?(e.consume(m),K):T(m)}function T(m){return m===61?(e.consume(m),A):D(m)?(a=T,Z(m)):U(m)?(e.consume(m),T):H(m)}function A(m){return m===null||m===60||m===61||m===62||m===96?t(m):m===34||m===39?(e.consume(m),i=m,N):D(m)?(a=A,Z(m)):U(m)?(e.consume(m),A):(e.consume(m),I)}function N(m){return m===i?(e.consume(m),i=void 0,P):m===null?t(m):D(m)?(a=N,Z(m)):(e.consume(m),N)}function I(m){return m===null||m===34||m===39||m===60||m===61||m===96?t(m):m===47||m===62||re(m)?H(m):(e.consume(m),I)}function P(m){return m===47||m===62||re(m)?H(m):t(m)}function J(m){return m===62?(e.consume(m),e.exit("htmlTextData"),e.exit("htmlText"),n):t(m)}function Z(m){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),ne}function ne(m){return U(m)?X(e,de,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(m):de(m)}function de(m){return e.enter("htmlTextData"),a(m)}}const Nn={name:"labelEnd",tokenize:pl,resolveTo:cl,resolveAll:ul},al={tokenize:hl},ol={tokenize:fl},sl={tokenize:dl};function ul(e){let n=-1;for(;++n=3&&(s===null||D(s))?(e.exit("thematicBreak"),n(s)):t(s)}function c(s){return s===i?(e.consume(s),r++,c):(e.exit("thematicBreakSequence"),U(s)?X(e,o,"whitespace")(s):o(s))}}const te={name:"list",tokenize:vl,continuation:{tokenize:Cl},exit:jl},kl={tokenize:Nl,partial:!0},Sl={tokenize:El,partial:!0};function vl(e,n,t){const r=this,i=r.events[r.events.length-1];let l=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(f){const j=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(j==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:wn(f)){if(r.containerState.type||(r.containerState.type=j,e.enter(j,{_container:!0})),j==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Ue,t,s)(f):s(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(f)}return t(f)}function c(f){return wn(f)&&++a<10?(e.consume(f),c):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),s(f)):t(f)}function s(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(Qe,r.interrupt?t:u,e.attempt(kl,g,h))}function u(f){return r.containerState.initialBlankLine=!0,l++,g(f)}function h(f){return U(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),g):t(f)}function g(f){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(f)}}function Cl(e,n,t){const r=this;return r.containerState._closeFlow=void 0,e.check(Qe,i,l);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,X(e,n,"listItemIndent",r.containerState.size+1)(o)}function l(o){return r.containerState.furtherBlankLines||!U(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Sl,n,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(te,n,t),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function El(e,n,t){const r=this;return X(e,i,"listItemIndent",r.containerState.size+1);function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?n(l):t(l)}}function jl(e){e.exit(this.containerState.type)}function Nl(e,n,t){const r=this;return X(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(l){const a=r.events[r.events.length-1];return!U(l)&&a&&a[1].type==="listItemPrefixWhitespace"?n(l):t(l)}}const lt={name:"setextUnderline",tokenize:Fl,resolveTo:Al};function Al(e,n){let t=e.length,r,i,l;for(;t--;)if(e[t][0]==="enter"){if(e[t][1].type==="content"){r=t;break}e[t][1].type==="paragraph"&&(i=t)}else e[t][1].type==="content"&&e.splice(t,1),!l&&e[t][1].type==="definition"&&(l=t);const a={type:"setextHeading",start:Object.assign({},e[i][1].start),end:Object.assign({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",l?(e.splice(i,0,["enter",a,n]),e.splice(l+1,0,["exit",e[r][1],n]),e[r][1].end=Object.assign({},e[l][1].end)):e[r][1]=a,e.push(["exit",a,n]),e}function Fl(e,n,t){const r=this;let i;return l;function l(s){let u=r.events.length,h;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){h=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(e.enter("setextHeadingLine"),i=s,a(s)):t(s)}function a(s){return e.enter("setextHeadingLineSequence"),o(s)}function o(s){return s===i?(e.consume(s),o):(e.exit("setextHeadingLineSequence"),U(s)?X(e,c,"lineSuffix")(s):c(s))}function c(s){return s===null||D(s)?(e.exit("setextHeadingLine"),n(s)):t(s)}}const Tl={tokenize:Il};function Il(e){const n=this,t=e.attempt(Qe,r,e.attempt(this.parser.constructs.flowInitial,i,X(e,e.attempt(this.parser.constructs.flow,i,e.attempt(zi,i)),"linePrefix")));return t;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),n.currentConstruct=void 0,t}function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),n.currentConstruct=void 0,t}}const Ll={resolveAll:Bt()},Pl=Rt("string"),Ol=Rt("text");function Rt(e){return{tokenize:n,resolveAll:Bt(e==="text"?Dl:void 0)};function n(t){const r=this,i=this.parser.constructs[e],l=t.attempt(i,a,o);return a;function a(u){return s(u)?l(u):o(u)}function o(u){if(u===null){t.consume(u);return}return t.enter("data"),t.consume(u),c}function c(u){return s(u)?(t.exit("data"),l(u)):(t.consume(u),c)}function s(u){if(u===null)return!0;const h=i[u];let g=-1;if(h)for(;++g-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}l>0&&a.push(e[i].slice(0,l))}return a}function Bl(e,n){let t=-1;const r=[];let i;for(;++ti||(i=n.indexOf("#"),i!==-1&&r>i)?n:"javascript:void(0)"}var Je,Mn;function Lr(){return Mn||(Mn=1,Je=function(n){return n!=null&&n.constructor!=null&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}),Je}var Pr=Lr();const Et=Re(Pr);function De(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Hn(e.position):"start"in e||"end"in e?Hn(e):"line"in e||"column"in e?gn(e):""}function gn(e){return Un(e&&e.line)+":"+Un(e&&e.column)}function Hn(e){return gn(e&&e.start)+"-"+gn(e&&e.end)}function Un(e){return e&&typeof e=="number"?e:1}class he extends Error{constructor(n,t,r){const i=[null,null];let l={start:{line:null,column:null},end:{line:null,column:null}};if(super(),typeof t=="string"&&(r=t,t=void 0),typeof r=="string"){const a=r.indexOf(":");a===-1?i[1]=r:(i[0]=r.slice(0,a),i[1]=r.slice(a+1))}t&&("type"in t||"position"in t?t.position&&(l=t.position):"start"in t||"end"in t?l=t:("line"in t||"column"in t)&&(l.start=t)),this.name=De(t)||"1:1",this.message=typeof n=="object"?n.message:n,this.stack="",typeof n=="object"&&n.stack&&(this.stack=n.stack),this.reason=this.message,this.fatal,this.line=l.start.line,this.column=l.start.column,this.position=l,this.source=i[0],this.ruleId=i[1],this.file,this.actual,this.expected,this.url,this.note}}he.prototype.file="";he.prototype.name="";he.prototype.reason="";he.prototype.message="";he.prototype.stack="";he.prototype.fatal=null;he.prototype.column=null;he.prototype.line=null;he.prototype.source=null;he.prototype.ruleId=null;he.prototype.position=null;const ge={basename:Or,dirname:Dr,extname:zr,join:Rr,sep:"/"};function Or(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Be(e);let t=0,r=-1,i=e.length,l;if(n===void 0||n.length===0||n.length>e.length){for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else r<0&&(l=!0,r=i+1);return r<0?"":e.slice(t,r)}if(n===e)return"";let a=-1,o=n.length-1;for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else a<0&&(l=!0,a=i+1),o>-1&&(e.charCodeAt(i)===n.charCodeAt(o--)?o<0&&(r=i):(o=-1,r=a));return t===r?r=a:r<0&&(r=e.length),e.slice(t,r)}function Dr(e){if(Be(e),e.length===0)return".";let n=-1,t=e.length,r;for(;--t;)if(e.charCodeAt(t)===47){if(r){n=t;break}}else r||(r=!0);return n<0?e.charCodeAt(0)===47?"/":".":n===1&&e.charCodeAt(0)===47?"//":e.slice(0,n)}function zr(e){Be(e);let n=e.length,t=-1,r=0,i=-1,l=0,a;for(;n--;){const o=e.charCodeAt(n);if(o===47){if(a){r=n+1;break}continue}t<0&&(a=!0,t=n+1),o===46?i<0?i=n:l!==1&&(l=1):i>-1&&(l=-1)}return i<0||t<0||l===0||l===1&&i===t-1&&i===r+1?"":e.slice(i,t)}function Rr(...e){let n=-1,t;for(;++n0&&e.charCodeAt(e.length-1)===47&&(t+="/"),n?"/"+t:t}function _r(e,n){let t="",r=0,i=-1,l=0,a=-1,o,c;for(;++a<=e.length;){if(a2){if(c=t.lastIndexOf("/"),c!==t.length-1){c<0?(t="",r=0):(t=t.slice(0,c),r=t.length-1-t.lastIndexOf("/")),i=a,l=0;continue}}else if(t.length>0){t="",r=0,i=a,l=0;continue}}n&&(t=t.length>0?t+"/..":"..",r=2)}else t.length>0?t+="/"+e.slice(i+1,a):t=e.slice(i+1,a),r=a-i-1;i=a,l=0}else o===46&&l>-1?l++:l=-1}return t}function Be(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const $r={cwd:Mr};function Mr(){return"/"}function xn(e){return e!==null&&typeof e=="object"&&e.href&&e.origin}function Hr(e){if(typeof e=="string")e=new URL(e);else if(!xn(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return Ur(e)}function Ur(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const n=e.pathname;let t=-1;for(;++t"u"||e.call(s,g)},a=function(s,u){t&&u.name==="__proto__"?t(s,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):s[u.name]=u.newValue},o=function(s,u){if(u==="__proto__")if(e.call(s,u)){if(r)return r(s,u).value}else return;return s[u]};return tn=function c(){var s,u,h,g,f,j,b=arguments[0],x=1,k=arguments.length,S=!1;for(typeof b=="boolean"&&(S=b,b=arguments[1]||{},x=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});xa.length;let c;o&&a.push(i);try{c=e.apply(this,a)}catch(s){const u=s;if(o&&t)throw u;return i(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(l,i):c instanceof Error?i(c):l(c))}function i(a,...o){t||(t=!0,n(a,...o))}function l(a){i(null,a)}}const Yr=At().freeze(),Nt={}.hasOwnProperty;function At(){const e=Qr(),n=[];let t={},r,i=-1;return l.data=a,l.Parser=void 0,l.Compiler=void 0,l.freeze=o,l.attachers=n,l.use=c,l.parse=s,l.stringify=u,l.run=h,l.runSync=g,l.process=f,l.processSync=j,l;function l(){const b=At();let x=-1;for(;++x{if(y||!L||!B)$(y);else{const H=l.stringify(L,B);H==null||(Jr(H)?B.value=H:B.result=H),$(y,B)}});function $(y,L){y||!L?C(y):S?S(L):x(null,L)}}}function j(b){let x;l.freeze(),rn("processSync",l.Parser),ln("processSync",l.Compiler);const k=Oe(b);return l.process(k,S),Kn("processSync","process",x),k;function S(C){x=!0,Vn(C)}}}function Xn(e,n){return typeof e=="function"&&e.prototype&&(Kr(e.prototype)||n in e.prototype)}function Kr(e){let n;for(n in e)if(Nt.call(e,n))return!0;return!1}function rn(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Parser`")}function ln(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Compiler`")}function an(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Yn(e){if(!yn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Kn(e,n,t){if(!t)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Oe(e){return Gr(e)?e:new jt(e)}function Gr(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Jr(e){return typeof e=="string"||Et(e)}const Zr={};function ei(e,n){const t=Zr,r=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return Ft(e,r,i)}function Ft(e,n,t){if(ni(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Gn(e.children,n,t)}return Array.isArray(e)?Gn(e,n,t):""}function Gn(e,n,t){const r=[];let i=-1;for(;++ii?0:i+n:n=n>i?i:n,t=t>0?t:0,r.length<1e4)a=Array.from(r),a.unshift(n,t),e.splice(...a);else for(t&&e.splice(n,t);l0?(ye(e,e.length,0,n),e):n}const Jn={}.hasOwnProperty;function ti(e){const n={};let t=-1;for(;++ta))return;const L=n.events.length;let B=L,H,K;for(;B--;)if(n.events[B][0]==="exit"&&n.events[B][1].type==="chunkFlow"){if(H){K=n.events[B][1].end;break}H=!0}for(k(r),y=L;yC;){const $=t[F];n.containerState=$[1],$[0].exit.call(n,e)}t.length=C}function S(){i.write([null]),l=void 0,i=void 0,n.containerState._closeFlow=void 0}}function mi(e,n,t){return X(e,e.attempt(this.parser.constructs.document,n,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function et(e){if(e===null||re(e)||ci(e))return 1;if(ui(e))return 2}function jn(e,n,t){const r=[];let i=-1;for(;++i1&&e[t][1].end.offset-e[t][1].start.offset>1?2:1;const h=Object.assign({},e[r][1].end),g=Object.assign({},e[t][1].start);nt(h,-c),nt(g,c),a={type:c>1?"strongSequence":"emphasisSequence",start:h,end:Object.assign({},e[r][1].end)},o={type:c>1?"strongSequence":"emphasisSequence",start:Object.assign({},e[t][1].start),end:g},l={type:c>1?"strongText":"emphasisText",start:Object.assign({},e[r][1].end),end:Object.assign({},e[t][1].start)},i={type:c>1?"strong":"emphasis",start:Object.assign({},a.start),end:Object.assign({},o.end)},e[r][1].end=Object.assign({},a.start),e[t][1].start=Object.assign({},o.end),s=[],e[r][1].end.offset-e[r][1].start.offset&&(s=pe(s,[["enter",e[r][1],n],["exit",e[r][1],n]])),s=pe(s,[["enter",i,n],["enter",a,n],["exit",a,n],["enter",l,n]]),s=pe(s,jn(n.parser.constructs.insideSpan.null,e.slice(r+1,t),n)),s=pe(s,[["exit",l,n],["enter",o,n],["exit",o,n],["exit",i,n]]),e[t][1].end.offset-e[t][1].start.offset?(u=2,s=pe(s,[["enter",e[t][1],n],["exit",e[t][1],n]])):u=0,ye(e,r-1,t-r+3,s),t=r+s.length-u-2;break}}for(t=-1;++t0&&U(y)?X(e,S,"linePrefix",l+1)(y):S(y)}function S(y){return y===null||D(y)?e.check(tt,b,F)(y):(e.enter("codeFlowValue"),C(y))}function C(y){return y===null||D(y)?(e.exit("codeFlowValue"),S(y)):(e.consume(y),C)}function F(y){return e.exit("codeFenced"),n(y)}function $(y,L,B){let H=0;return K;function K(P){return y.enter("lineEnding"),y.consume(P),y.exit("lineEnding"),T}function T(P){return y.enter("codeFencedFence"),U(P)?X(y,A,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):A(P)}function A(P){return P===o?(y.enter("codeFencedFenceSequence"),N(P)):B(P)}function N(P){return P===o?(H++,y.consume(P),N):H>=a?(y.exit("codeFencedFenceSequence"),U(P)?X(y,I,"whitespace")(P):I(P)):B(P)}function I(P){return P===null||D(P)?(y.exit("codeFencedFence"),L(P)):B(P)}}}function Ni(e,n,t){const r=this;return i;function i(a){return a===null?t(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}const on={name:"codeIndented",tokenize:Fi},Ai={tokenize:Ti,partial:!0};function Fi(e,n,t){const r=this;return i;function i(s){return e.enter("codeIndented"),X(e,l,"linePrefix",5)(s)}function l(s){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?a(s):t(s)}function a(s){return s===null?c(s):D(s)?e.attempt(Ai,a,c)(s):(e.enter("codeFlowValue"),o(s))}function o(s){return s===null||D(s)?(e.exit("codeFlowValue"),a(s)):(e.consume(s),o)}function c(s){return e.exit("codeIndented"),n(s)}}function Ti(e,n,t){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?t(a):D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):X(e,l,"linePrefix",5)(a)}function l(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?n(a):D(a)?i(a):t(a)}}const Ii={name:"codeText",tokenize:Oi,resolve:Li,previous:Pi};function Li(e){let n=e.length-4,t=3,r,i;if((e[t][1].type==="lineEnding"||e[t][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(r=t;++r=4?n(a):e.interrupt(r.parser.constructs.flow,t,n)(a)}}function Ot(e,n,t,r,i,l,a,o,c){const s=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(k){return k===60?(e.enter(r),e.enter(i),e.enter(l),e.consume(k),e.exit(l),g):k===null||k===32||k===41||bn(k)?t(k):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),b(k))}function g(k){return k===62?(e.enter(l),e.consume(k),e.exit(l),e.exit(i),e.exit(r),n):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(k))}function f(k){return k===62?(e.exit("chunkString"),e.exit(o),g(k)):k===null||k===60||D(k)?t(k):(e.consume(k),k===92?j:f)}function j(k){return k===60||k===62||k===92?(e.consume(k),f):f(k)}function b(k){return!u&&(k===null||k===41||re(k))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),n(k)):u999||f===null||f===91||f===93&&!c||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?t(f):f===93?(e.exit(l),e.enter(i),e.consume(f),e.exit(i),e.exit(r),n):D(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||D(f)||o++>999?(e.exit("chunkString"),u(f)):(e.consume(f),c||(c=!U(f)),f===92?g:h)}function g(f){return f===91||f===92||f===93?(e.consume(f),o++,h):h(f)}}function zt(e,n,t,r,i,l){let a;return o;function o(g){return g===34||g===39||g===40?(e.enter(r),e.enter(i),e.consume(g),e.exit(i),a=g===40?41:g,c):t(g)}function c(g){return g===a?(e.enter(i),e.consume(g),e.exit(i),e.exit(r),n):(e.enter(l),s(g))}function s(g){return g===a?(e.exit(l),c(a)):g===null?t(g):D(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),X(e,s,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(g))}function u(g){return g===a||g===null||D(g)?(e.exit("chunkString"),s(g)):(e.consume(g),g===92?h:u)}function h(g){return g===a||g===92?(e.consume(g),u):u(g)}}function ze(e,n){let t;return r;function r(i){return D(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t=!0,r):U(i)?X(e,r,t?"linePrefix":"lineSuffix")(i):n(i)}}function Ae(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Mi={name:"definition",tokenize:Ui},Hi={tokenize:qi,partial:!0};function Ui(e,n,t){const r=this;let i;return l;function l(f){return e.enter("definition"),a(f)}function a(f){return Dt.call(r,e,o,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return i=Ae(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),c):t(f)}function c(f){return re(f)?ze(e,s)(f):s(f)}function s(f){return Ot(e,u,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return e.attempt(Hi,h,h)(f)}function h(f){return U(f)?X(e,g,"whitespace")(f):g(f)}function g(f){return f===null||D(f)?(e.exit("definition"),r.parser.defined.push(i),n(f)):t(f)}}function qi(e,n,t){return r;function r(o){return re(o)?ze(e,i)(o):t(o)}function i(o){return zt(e,l,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function l(o){return U(o)?X(e,a,"whitespace")(o):a(o)}function a(o){return o===null||D(o)?n(o):t(o)}}const Vi={name:"hardBreakEscape",tokenize:Wi};function Wi(e,n,t){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),i}function i(l){return D(l)?(e.exit("hardBreakEscape"),n(l)):t(l)}}const Qi={name:"headingAtx",tokenize:Yi,resolve:Xi};function Xi(e,n){let t=e.length-2,r=3,i,l;return e[r][1].type==="whitespace"&&(r+=2),t-2>r&&e[t][1].type==="whitespace"&&(t-=2),e[t][1].type==="atxHeadingSequence"&&(r===t-1||t-4>r&&e[t-2][1].type==="whitespace")&&(t-=r+1===t?2:4),t>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[t][1].end},l={type:"chunkText",start:e[r][1].start,end:e[t][1].end,contentType:"text"},ye(e,r,t-r+1,[["enter",i,n],["enter",l,n],["exit",l,n],["exit",i,n]])),e}function Yi(e,n,t){let r=0;return i;function i(u){return e.enter("atxHeading"),l(u)}function l(u){return e.enter("atxHeadingSequence"),a(u)}function a(u){return u===35&&r++<6?(e.consume(u),a):u===null||re(u)?(e.exit("atxHeadingSequence"),o(u)):t(u)}function o(u){return u===35?(e.enter("atxHeadingSequence"),c(u)):u===null||D(u)?(e.exit("atxHeading"),n(u)):U(u)?X(e,o,"whitespace")(u):(e.enter("atxHeadingText"),s(u))}function c(u){return u===35?(e.consume(u),c):(e.exit("atxHeadingSequence"),o(u))}function s(u){return u===null||u===35||re(u)?(e.exit("atxHeadingText"),o(u)):(e.consume(u),s)}}const Ki=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],it=["pre","script","style","textarea"],Gi={name:"htmlFlow",tokenize:nl,resolveTo:el,concrete:!0},Ji={tokenize:rl,partial:!0},Zi={tokenize:tl,partial:!0};function el(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function nl(e,n,t){const r=this;let i,l,a,o,c;return s;function s(p){return u(p)}function u(p){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(p),h}function h(p){return p===33?(e.consume(p),g):p===47?(e.consume(p),l=!0,b):p===63?(e.consume(p),i=3,r.interrupt?n:m):xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function g(p){return p===45?(e.consume(p),i=2,f):p===91?(e.consume(p),i=5,o=0,j):xe(p)?(e.consume(p),i=4,r.interrupt?n:m):t(p)}function f(p){return p===45?(e.consume(p),r.interrupt?n:m):t(p)}function j(p){const _="CDATA[";return p===_.charCodeAt(o++)?(e.consume(p),o===_.length?r.interrupt?n:A:j):t(p)}function b(p){return xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function x(p){if(p===null||p===47||p===62||re(p)){const _=p===47,se=a.toLowerCase();return!_&&!l&&it.includes(se)?(i=1,r.interrupt?n(p):A(p)):Ki.includes(a.toLowerCase())?(i=6,_?(e.consume(p),k):r.interrupt?n(p):A(p)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?t(p):l?S(p):C(p))}return p===45||oe(p)?(e.consume(p),a+=String.fromCharCode(p),x):t(p)}function k(p){return p===62?(e.consume(p),r.interrupt?n:A):t(p)}function S(p){return U(p)?(e.consume(p),S):K(p)}function C(p){return p===47?(e.consume(p),K):p===58||p===95||xe(p)?(e.consume(p),F):U(p)?(e.consume(p),C):K(p)}function F(p){return p===45||p===46||p===58||p===95||oe(p)?(e.consume(p),F):$(p)}function $(p){return p===61?(e.consume(p),y):U(p)?(e.consume(p),$):C(p)}function y(p){return p===null||p===60||p===61||p===62||p===96?t(p):p===34||p===39?(e.consume(p),c=p,L):U(p)?(e.consume(p),y):B(p)}function L(p){return p===c?(e.consume(p),c=null,H):p===null||D(p)?t(p):(e.consume(p),L)}function B(p){return p===null||p===34||p===39||p===47||p===60||p===61||p===62||p===96||re(p)?$(p):(e.consume(p),B)}function H(p){return p===47||p===62||U(p)?C(p):t(p)}function K(p){return p===62?(e.consume(p),T):t(p)}function T(p){return p===null||D(p)?A(p):U(p)?(e.consume(p),T):t(p)}function A(p){return p===45&&i===2?(e.consume(p),J):p===60&&i===1?(e.consume(p),Z):p===62&&i===4?(e.consume(p),ie):p===63&&i===3?(e.consume(p),m):p===93&&i===5?(e.consume(p),de):D(p)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Ji,le,N)(p)):p===null||D(p)?(e.exit("htmlFlowData"),N(p)):(e.consume(p),A)}function N(p){return e.check(Zi,I,le)(p)}function I(p){return e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),P}function P(p){return p===null||D(p)?N(p):(e.enter("htmlFlowData"),A(p))}function J(p){return p===45?(e.consume(p),m):A(p)}function Z(p){return p===47?(e.consume(p),a="",ne):A(p)}function ne(p){if(p===62){const _=a.toLowerCase();return it.includes(_)?(e.consume(p),ie):A(p)}return xe(p)&&a.length<8?(e.consume(p),a+=String.fromCharCode(p),ne):A(p)}function de(p){return p===93?(e.consume(p),m):A(p)}function m(p){return p===62?(e.consume(p),ie):p===45&&i===2?(e.consume(p),m):A(p)}function ie(p){return p===null||D(p)?(e.exit("htmlFlowData"),le(p)):(e.consume(p),ie)}function le(p){return e.exit("htmlFlow"),n(p)}}function tl(e,n,t){const r=this;return i;function i(a){return D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l):t(a)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}function rl(e,n,t){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Qe,n,t)}}const il={name:"htmlText",tokenize:ll};function ll(e,n,t){const r=this;let i,l,a;return o;function o(m){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(m),c}function c(m){return m===33?(e.consume(m),s):m===47?(e.consume(m),$):m===63?(e.consume(m),C):xe(m)?(e.consume(m),B):t(m)}function s(m){return m===45?(e.consume(m),u):m===91?(e.consume(m),l=0,j):xe(m)?(e.consume(m),S):t(m)}function u(m){return m===45?(e.consume(m),f):t(m)}function h(m){return m===null?t(m):m===45?(e.consume(m),g):D(m)?(a=h,Z(m)):(e.consume(m),h)}function g(m){return m===45?(e.consume(m),f):h(m)}function f(m){return m===62?J(m):m===45?g(m):h(m)}function j(m){const ie="CDATA[";return m===ie.charCodeAt(l++)?(e.consume(m),l===ie.length?b:j):t(m)}function b(m){return m===null?t(m):m===93?(e.consume(m),x):D(m)?(a=b,Z(m)):(e.consume(m),b)}function x(m){return m===93?(e.consume(m),k):b(m)}function k(m){return m===62?J(m):m===93?(e.consume(m),k):b(m)}function S(m){return m===null||m===62?J(m):D(m)?(a=S,Z(m)):(e.consume(m),S)}function C(m){return m===null?t(m):m===63?(e.consume(m),F):D(m)?(a=C,Z(m)):(e.consume(m),C)}function F(m){return m===62?J(m):C(m)}function $(m){return xe(m)?(e.consume(m),y):t(m)}function y(m){return m===45||oe(m)?(e.consume(m),y):L(m)}function L(m){return D(m)?(a=L,Z(m)):U(m)?(e.consume(m),L):J(m)}function B(m){return m===45||oe(m)?(e.consume(m),B):m===47||m===62||re(m)?H(m):t(m)}function H(m){return m===47?(e.consume(m),J):m===58||m===95||xe(m)?(e.consume(m),K):D(m)?(a=H,Z(m)):U(m)?(e.consume(m),H):J(m)}function K(m){return m===45||m===46||m===58||m===95||oe(m)?(e.consume(m),K):T(m)}function T(m){return m===61?(e.consume(m),A):D(m)?(a=T,Z(m)):U(m)?(e.consume(m),T):H(m)}function A(m){return m===null||m===60||m===61||m===62||m===96?t(m):m===34||m===39?(e.consume(m),i=m,N):D(m)?(a=A,Z(m)):U(m)?(e.consume(m),A):(e.consume(m),I)}function N(m){return m===i?(e.consume(m),i=void 0,P):m===null?t(m):D(m)?(a=N,Z(m)):(e.consume(m),N)}function I(m){return m===null||m===34||m===39||m===60||m===61||m===96?t(m):m===47||m===62||re(m)?H(m):(e.consume(m),I)}function P(m){return m===47||m===62||re(m)?H(m):t(m)}function J(m){return m===62?(e.consume(m),e.exit("htmlTextData"),e.exit("htmlText"),n):t(m)}function Z(m){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),ne}function ne(m){return U(m)?X(e,de,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(m):de(m)}function de(m){return e.enter("htmlTextData"),a(m)}}const Nn={name:"labelEnd",tokenize:pl,resolveTo:cl,resolveAll:ul},al={tokenize:hl},ol={tokenize:fl},sl={tokenize:dl};function ul(e){let n=-1;for(;++n=3&&(s===null||D(s))?(e.exit("thematicBreak"),n(s)):t(s)}function c(s){return s===i?(e.consume(s),r++,c):(e.exit("thematicBreakSequence"),U(s)?X(e,o,"whitespace")(s):o(s))}}const te={name:"list",tokenize:vl,continuation:{tokenize:Cl},exit:jl},kl={tokenize:Nl,partial:!0},Sl={tokenize:El,partial:!0};function vl(e,n,t){const r=this,i=r.events[r.events.length-1];let l=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(f){const j=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(j==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:wn(f)){if(r.containerState.type||(r.containerState.type=j,e.enter(j,{_container:!0})),j==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Ue,t,s)(f):s(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(f)}return t(f)}function c(f){return wn(f)&&++a<10?(e.consume(f),c):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),s(f)):t(f)}function s(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(Qe,r.interrupt?t:u,e.attempt(kl,g,h))}function u(f){return r.containerState.initialBlankLine=!0,l++,g(f)}function h(f){return U(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),g):t(f)}function g(f){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(f)}}function Cl(e,n,t){const r=this;return r.containerState._closeFlow=void 0,e.check(Qe,i,l);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,X(e,n,"listItemIndent",r.containerState.size+1)(o)}function l(o){return r.containerState.furtherBlankLines||!U(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Sl,n,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(te,n,t),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function El(e,n,t){const r=this;return X(e,i,"listItemIndent",r.containerState.size+1);function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?n(l):t(l)}}function jl(e){e.exit(this.containerState.type)}function Nl(e,n,t){const r=this;return X(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(l){const a=r.events[r.events.length-1];return!U(l)&&a&&a[1].type==="listItemPrefixWhitespace"?n(l):t(l)}}const lt={name:"setextUnderline",tokenize:Fl,resolveTo:Al};function Al(e,n){let t=e.length,r,i,l;for(;t--;)if(e[t][0]==="enter"){if(e[t][1].type==="content"){r=t;break}e[t][1].type==="paragraph"&&(i=t)}else e[t][1].type==="content"&&e.splice(t,1),!l&&e[t][1].type==="definition"&&(l=t);const a={type:"setextHeading",start:Object.assign({},e[i][1].start),end:Object.assign({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",l?(e.splice(i,0,["enter",a,n]),e.splice(l+1,0,["exit",e[r][1],n]),e[r][1].end=Object.assign({},e[l][1].end)):e[r][1]=a,e.push(["exit",a,n]),e}function Fl(e,n,t){const r=this;let i;return l;function l(s){let u=r.events.length,h;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){h=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(e.enter("setextHeadingLine"),i=s,a(s)):t(s)}function a(s){return e.enter("setextHeadingLineSequence"),o(s)}function o(s){return s===i?(e.consume(s),o):(e.exit("setextHeadingLineSequence"),U(s)?X(e,c,"lineSuffix")(s):c(s))}function c(s){return s===null||D(s)?(e.exit("setextHeadingLine"),n(s)):t(s)}}const Tl={tokenize:Il};function Il(e){const n=this,t=e.attempt(Qe,r,e.attempt(this.parser.constructs.flowInitial,i,X(e,e.attempt(this.parser.constructs.flow,i,e.attempt(zi,i)),"linePrefix")));return t;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),n.currentConstruct=void 0,t}function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),n.currentConstruct=void 0,t}}const Ll={resolveAll:Bt()},Pl=Rt("string"),Ol=Rt("text");function Rt(e){return{tokenize:n,resolveAll:Bt(e==="text"?Dl:void 0)};function n(t){const r=this,i=this.parser.constructs[e],l=t.attempt(i,a,o);return a;function a(u){return s(u)?l(u):o(u)}function o(u){if(u===null){t.consume(u);return}return t.enter("data"),t.consume(u),c}function c(u){return s(u)?(t.exit("data"),l(u)):(t.consume(u),c)}function s(u){if(u===null)return!0;const h=i[u];let g=-1;if(h)for(;++g-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}l>0&&a.push(e[i].slice(0,l))}return a}function Bl(e,n){let t=-1;const r=[];let i;for(;++t13&&t<32||t>126&&t<160||t>55295&&t<57344||t>64975&&t<65008||(t&65535)===65535||(t&65535)===65534||t>1114111?"�":String.fromCharCode(t)}const Jl=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Zl(e){return e.replace(Jl,ea)}function ea(e,n,t){if(n)return n;if(t.charCodeAt(0)===35){const i=t.charCodeAt(1),l=i===120||i===88;return _t(t.slice(l?2:1),l?16:10)}return En(t)||e}const $t={}.hasOwnProperty,na=function(e,n,t){return typeof n!="string"&&(t=n,n=void 0),ta(t)(Gl(Yl(t).document().write(Kl()(e,n,!0))))};function ta(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Rn),autolinkProtocol:T,autolinkEmail:T,atxHeading:o(On),blockQuote:o(Ye),characterEscape:T,characterReference:T,codeFenced:o(Pn),codeFencedFenceInfo:c,codeFencedFenceMeta:c,codeIndented:o(Pn,c),codeText:o(lr,c),codeTextData:T,data:T,codeFlowValue:T,definition:o(ar),definitionDestinationString:c,definitionLabelString:c,definitionTitleString:c,emphasis:o(or),hardBreakEscape:o(Dn),hardBreakTrailing:o(Dn),htmlFlow:o(zn,c),htmlFlowData:T,htmlText:o(zn,c),htmlTextData:T,image:o(sr),label:c,link:o(Rn),listItem:o(ur),listItemValue:j,listOrdered:o(Bn,f),listUnordered:o(Bn),paragraph:o(cr),reference:se,referenceString:c,resourceDestinationString:c,resourceTitleString:c,setextHeading:o(On),strong:o(pr),thematicBreak:o(fr)},exit:{atxHeading:u(),atxHeadingSequence:L,autolink:u(),autolinkEmail:Se,autolinkProtocol:ke,blockQuote:u(),characterEscapeValue:A,characterReferenceMarkerHexadecimal:ue,characterReferenceMarkerNumeric:ue,characterReferenceValue:ce,codeFenced:u(S),codeFencedFence:k,codeFencedFenceInfo:b,codeFencedFenceMeta:x,codeFlowValue:A,codeIndented:u(C),codeText:u(Z),codeTextData:A,data:A,definition:u(),definitionDestinationString:y,definitionLabelString:F,definitionTitleString:$,emphasis:u(),hardBreakEscape:u(I),hardBreakTrailing:u(I),htmlFlow:u(P),htmlFlowData:A,htmlText:u(J),htmlTextData:A,image:u(de),label:ie,labelText:m,lineEnding:N,link:u(ne),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:Y,resourceDestinationString:le,resourceTitleString:p,resource:_,setextHeading:u(K),setextHeadingLineSequence:H,setextHeadingText:B,strong:u(),thematicBreak:u()}};Mt(n,(e||{}).mdastExtensions||[]);const t={};return r;function r(w){let E={type:"root",children:[]};const O={stack:[E],tokenStack:[],config:n,enter:s,exit:h,buffer:c,resume:g,setData:l,getData:a},V=[];let W=-1;for(;++W0){const me=O.tokenStack[O.tokenStack.length-1];(me[1]||ot).call(O,void 0,me[0])}for(E.position={start:Ce(w.length>0?w[0][1].start:{line:1,column:1,offset:0}),end:Ce(w.length>0?w[w.length-2][1].end:{line:1,column:1,offset:0})},W=-1;++W{const r=this.data("settings");return na(t,Object.assign({},r,e,{extensions:this.data("micromarkExtensions")||[],mdastExtensions:this.data("fromMarkdownExtensions")||[]}))}})}function la(e,n){const t={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,t),e.applyData(n,t)}function aa(e,n){const t={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,t),[e.applyData(n,t),{type:"text",value:` `}]}function oa(e,n){const t=n.value?n.value+` diff --git a/src/agentomatic/studio/static/assets/ConnectionsView-wfIgs5wX.js b/src/agentomatic/studio/static/assets/ConnectionsView-Dvq88oBW.js similarity index 97% rename from src/agentomatic/studio/static/assets/ConnectionsView-wfIgs5wX.js rename to src/agentomatic/studio/static/assets/ConnectionsView-Dvq88oBW.js index a316b0a2..33638a0e 100644 --- a/src/agentomatic/studio/static/assets/ConnectionsView-wfIgs5wX.js +++ b/src/agentomatic/studio/static/assets/ConnectionsView-Dvq88oBW.js @@ -1 +1 @@ -import{u as U,A as j,j as e}from"./index-A2k5j4o2.js";import{r as a}from"./react-vendor-BHJ3EV8m.js";import{O as K}from"./OutputSchemaSummary-DzWXQCQ1.js";import"./syntax-vendor-ru7AzRyY.js";const f=o=>{switch(o){case"healthy":case"ok":case"configured":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},A=()=>{const{config:o,darkMode:n}=U(),[d,N]=a.useState([]),[g,w]=a.useState(!0),[x,u]=a.useState(null),[b,h]=a.useState(null),[$,C]=a.useState({}),[k,S]=a.useState(null),[y,v]=a.useState(null),m=a.useCallback(async()=>{try{if(!o?.apiUrl)return;const s=new j(o.apiUrl,o.apiKey||void 0),[r,c]=await Promise.all([s.listControlConnections(),s.getOperationContract("/api/v1/control/connections/{scope}/{name}","get").catch(t=>(v(t?.message||"Could not load the connection probe contract"),null))]);N(r),S(c),c&&v(null),u(null)}catch(s){u(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch connections")}finally{w(!1)}},[o?.apiUrl,o?.apiKey]);a.useEffect(()=>{m()},[m]);const E=async(s,r)=>{if(!o?.apiUrl)return;const c=`${s}:${r}`;h(c);try{const p=await new j(o.apiUrl,o.apiKey||void 0).probeControlConnection(s,r);C(i=>({...i,[c]:p})),u(null)}catch(t){u(t?.message||`Failed to test connection '${r}'`)}finally{h(null)}},O=n?"bg-gray-800 border-gray-700":"bg-white border-gray-200",l=n?"text-gray-400":"text-gray-600",P=d.reduce((s,r)=>s+Object.keys(r.connections||{}).length,0);return e.jsxs("div",{className:`p-6 h-full overflow-y-auto ${n?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Connections"}),e.jsx("button",{onClick:m,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]}),e.jsxs("p",{className:`text-sm mb-6 ${l}`,children:["Platform persistence plus per-agent databases, vector stores & services — ",P," connection(s) across ",d.length," scope(s). Each test runs the selected live probe only."]}),g&&e.jsx("div",{className:l,children:"Loading connections…"}),x&&e.jsx("div",{className:`p-4 rounded-lg border mb-4 ${n?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:x}),!g&&!x&&d.length===0&&e.jsx("div",{className:l,children:"No connections registered."}),e.jsx("div",{className:"space-y-6",children:d.map(s=>e.jsxs("div",{className:`rounded-xl border ${O}`,children:[e.jsxs("div",{className:`px-5 py-3 border-b flex items-center gap-2 ${n?"border-gray-700":"border-gray-200"}`,children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${n?"bg-gray-700":"bg-gray-100"}`,children:"scope"}),e.jsx("span",{className:"font-semibold",children:s.scope})]}),e.jsxs("div",{className:"p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[Object.entries(s.connections||{}).map(([r,c])=>{const t=c||{},p=`${s.scope}:${r}`,i=$[p];return e.jsxs("div",{className:`p-4 rounded-lg border ${n?"border-gray-700 bg-gray-900/40":"border-gray-200 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-medium",children:r}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${f(t.status)}`}),t.status||"unknown"]})]}),e.jsxs("div",{className:`text-xs space-y-0.5 ${l}`,children:[t.kind&&e.jsxs("div",{children:["kind: ",t.kind]}),t.purpose&&e.jsxs("div",{children:["purpose: ",t.purpose]}),t.backend&&e.jsxs("div",{children:["backend: ",t.backend]}),t.provider&&e.jsxs("div",{children:["provider: ",t.provider]}),t.detail&&e.jsx("div",{className:n?"text-amber-300":"text-amber-700",children:String(t.detail)}),t.error&&e.jsxs("div",{className:"text-red-400",children:["error: ",String(t.error)]})]}),e.jsx("button",{type:"button",onClick:()=>{E(s.scope,r)},disabled:b!==null,className:"mt-3 rounded-md bg-violet-600 px-2.5 py-1.5 text-xs font-medium text-white hover:bg-violet-700 disabled:opacity-50",children:b===p?"Testing…":"Test connection"}),y?e.jsxs("p",{role:"status",className:`mt-2 text-[10px] ${n?"text-amber-300":"text-amber-700"}`,children:["Live output contract unavailable: ",y]}):e.jsx(K,{schema:k?.output_schema,darkMode:n,className:"mt-3"}),i&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("div",{className:`mb-1 flex items-center gap-1.5 text-[10px] font-medium ${l}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f(i.status)}`}),"Last live probe: ",i.status||"unknown"]}),e.jsx("pre",{className:`max-h-36 overflow-auto rounded p-2 text-[10px] ${n?"bg-gray-950 text-gray-300":"bg-white text-gray-700"}`,children:JSON.stringify(i,null,2)})]})]},r)}),Object.keys(s.connections||{}).length===0&&e.jsx("div",{className:`text-sm ${l}`,children:"No connections in this scope."})]})]},s.scope))})]})};export{A as ConnectionsView}; +import{u as U,A as j,j as e}from"./index-FSSL6O5F.js";import{r as a}from"./react-vendor-BHJ3EV8m.js";import{O as K}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const f=o=>{switch(o){case"healthy":case"ok":case"configured":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},A=()=>{const{config:o,darkMode:n}=U(),[d,N]=a.useState([]),[g,w]=a.useState(!0),[x,u]=a.useState(null),[b,h]=a.useState(null),[$,C]=a.useState({}),[k,S]=a.useState(null),[y,v]=a.useState(null),m=a.useCallback(async()=>{try{if(!o?.apiUrl)return;const s=new j(o.apiUrl,o.apiKey||void 0),[r,c]=await Promise.all([s.listControlConnections(),s.getOperationContract("/api/v1/control/connections/{scope}/{name}","get").catch(t=>(v(t?.message||"Could not load the connection probe contract"),null))]);N(r),S(c),c&&v(null),u(null)}catch(s){u(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch connections")}finally{w(!1)}},[o?.apiUrl,o?.apiKey]);a.useEffect(()=>{m()},[m]);const E=async(s,r)=>{if(!o?.apiUrl)return;const c=`${s}:${r}`;h(c);try{const p=await new j(o.apiUrl,o.apiKey||void 0).probeControlConnection(s,r);C(i=>({...i,[c]:p})),u(null)}catch(t){u(t?.message||`Failed to test connection '${r}'`)}finally{h(null)}},O=n?"bg-gray-800 border-gray-700":"bg-white border-gray-200",l=n?"text-gray-400":"text-gray-600",P=d.reduce((s,r)=>s+Object.keys(r.connections||{}).length,0);return e.jsxs("div",{className:`p-6 h-full overflow-y-auto ${n?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Connections"}),e.jsx("button",{onClick:m,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]}),e.jsxs("p",{className:`text-sm mb-6 ${l}`,children:["Platform persistence plus per-agent databases, vector stores & services — ",P," connection(s) across ",d.length," scope(s). Each test runs the selected live probe only."]}),g&&e.jsx("div",{className:l,children:"Loading connections…"}),x&&e.jsx("div",{className:`p-4 rounded-lg border mb-4 ${n?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:x}),!g&&!x&&d.length===0&&e.jsx("div",{className:l,children:"No connections registered."}),e.jsx("div",{className:"space-y-6",children:d.map(s=>e.jsxs("div",{className:`rounded-xl border ${O}`,children:[e.jsxs("div",{className:`px-5 py-3 border-b flex items-center gap-2 ${n?"border-gray-700":"border-gray-200"}`,children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${n?"bg-gray-700":"bg-gray-100"}`,children:"scope"}),e.jsx("span",{className:"font-semibold",children:s.scope})]}),e.jsxs("div",{className:"p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[Object.entries(s.connections||{}).map(([r,c])=>{const t=c||{},p=`${s.scope}:${r}`,i=$[p];return e.jsxs("div",{className:`p-4 rounded-lg border ${n?"border-gray-700 bg-gray-900/40":"border-gray-200 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-medium",children:r}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${f(t.status)}`}),t.status||"unknown"]})]}),e.jsxs("div",{className:`text-xs space-y-0.5 ${l}`,children:[t.kind&&e.jsxs("div",{children:["kind: ",t.kind]}),t.purpose&&e.jsxs("div",{children:["purpose: ",t.purpose]}),t.backend&&e.jsxs("div",{children:["backend: ",t.backend]}),t.provider&&e.jsxs("div",{children:["provider: ",t.provider]}),t.detail&&e.jsx("div",{className:n?"text-amber-300":"text-amber-700",children:String(t.detail)}),t.error&&e.jsxs("div",{className:"text-red-400",children:["error: ",String(t.error)]})]}),e.jsx("button",{type:"button",onClick:()=>{E(s.scope,r)},disabled:b!==null,className:"mt-3 rounded-md bg-violet-600 px-2.5 py-1.5 text-xs font-medium text-white hover:bg-violet-700 disabled:opacity-50",children:b===p?"Testing…":"Test connection"}),y?e.jsxs("p",{role:"status",className:`mt-2 text-[10px] ${n?"text-amber-300":"text-amber-700"}`,children:["Live output contract unavailable: ",y]}):e.jsx(K,{schema:k?.output_schema,darkMode:n,className:"mt-3"}),i&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("div",{className:`mb-1 flex items-center gap-1.5 text-[10px] font-medium ${l}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f(i.status)}`}),"Last live probe: ",i.status||"unknown"]}),e.jsx("pre",{className:`max-h-36 overflow-auto rounded p-2 text-[10px] ${n?"bg-gray-950 text-gray-300":"bg-white text-gray-700"}`,children:JSON.stringify(i,null,2)})]})]},r)}),Object.keys(s.connections||{}).length===0&&e.jsx("div",{className:`text-sm ${l}`,children:"No connections in this scope."})]})]},s.scope))})]})};export{A as ConnectionsView}; diff --git a/src/agentomatic/studio/static/assets/ControlPlaneView-ba4D_JM4.js b/src/agentomatic/studio/static/assets/ControlPlaneView-CC__Od52.js similarity index 99% rename from src/agentomatic/studio/static/assets/ControlPlaneView-ba4D_JM4.js rename to src/agentomatic/studio/static/assets/ControlPlaneView-CC__Od52.js index c9592043..73eb90a5 100644 --- a/src/agentomatic/studio/static/assets/ControlPlaneView-ba4D_JM4.js +++ b/src/agentomatic/studio/static/assets/ControlPlaneView-CC__Od52.js @@ -1,2 +1,2 @@ -import{u as P,A as q,j as e,V as h}from"./index-A2k5j4o2.js";import{r as l,R as F}from"./react-vendor-BHJ3EV8m.js";import"./syntax-vendor-ru7AzRyY.js";const f="agentomatic_control_token",K=r=>{switch(r){case"healthy":case"ok":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},D=()=>{const{config:r,darkMode:o}=P(),[t,w]=l.useState(null),[p,_]=l.useState(null),[y,$]=l.useState([]),[j,k]=l.useState({}),[C,A]=l.useState(!0),[g,N]=l.useState(null),[d,m]=l.useState(null),[x,S]=l.useState(()=>sessionStorage.getItem(f)||""),n=F.useMemo(()=>r?.apiUrl?new q(r.apiUrl,r.apiKey||void 0):null,[r?.apiUrl,r?.apiKey]),i=l.useCallback(async()=>{if(n)try{const[s,c,T,M]=await Promise.all([n.getControlInfo(),n.getControlMetricsSummary(),n.listControlAgents(),n.getControlConfig()]);w(s),_(c),$(T),k(M.features||{}),N(null)}catch(s){const c=s?.status===404?"Control plane is not enabled on this platform (start with enable_control_plane=True).":s?.message||"Failed to load control plane";N(c)}finally{A(!1)}},[n]);l.useEffect(()=>{i();const s=setInterval(i,5e3);return()=>clearInterval(s)},[i]);const E=s=>{S(s),s?sessionStorage.setItem(f,s):sessionStorage.removeItem(f)},R=async s=>{if(n){m(`agent:${s.name}`);try{await n.setAgentEnabled(s.name,!s.enabled,x||void 0),h.success(`${s.name} ${s.enabled?"disabled":"enabled"}`),i()}catch(c){h.error(c?.status===401?"Invalid control token":c?.message||"Action failed")}finally{m(null)}}},I=async()=>{if(!(!n||!t)){m("maintenance");try{await n.setMaintenance(!t.maintenance_mode,x||void 0),h.success(`Maintenance mode ${t.maintenance_mode?"disabled":"enabled"}`),i()}catch(s){h.error(s?.status===401?"Invalid control token":s?.message||"Action failed")}finally{m(null)}}},b=o?"bg-gray-800 border-gray-700":"bg-white border-gray-200",a=o?"text-gray-400":"text-gray-500",v=!!t?.control_token_required,u=v&&!x||d!==null;return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${o?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Control Plane"}),e.jsx("p",{className:`text-sm ${a}`,children:"Runtime operations & health"})]}),e.jsxs("div",{className:"flex w-full items-center gap-2 sm:w-auto",children:[e.jsx("input",{type:"password","aria-label":"X-Control-Token (optional)",value:x,onChange:s=>E(s.target.value),placeholder:"X-Control-Token (optional)",className:`min-w-0 flex-1 px-3 py-2 rounded-lg text-sm border sm:w-56 sm:flex-none ${o?"bg-gray-800 border-gray-700 text-white":"bg-white border-gray-300"}`}),e.jsx("button",{type:"button",onClick:i,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]})]}),C&&e.jsx("div",{className:a,children:"Loading control plane…"}),g&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${o?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:g}),!g&&t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 mb-6",children:[{label:"Agents",value:t.agent_count},{label:"Endpoints",value:t.endpoint_count},{label:"Plugins",value:t.plugin_count},{label:"Pipelines",value:t.pipeline_count},{label:"Conn. scopes",value:t.connection_scopes},{label:"Uptime (s)",value:Math.round(t.uptime_seconds)}].map(s=>e.jsxs("div",{className:`p-4 rounded-xl border ${b}`,children:[e.jsx("div",{className:"text-2xl font-bold",children:s.value}),e.jsx("div",{className:`text-xs ${a}`,children:s.label})]},s.label))}),e.jsxs("div",{className:`mb-6 flex flex-col gap-3 rounded-xl border p-4 sm:flex-row sm:items-center sm:justify-between ${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`w-3 h-3 rounded-full ${t.maintenance_mode?"bg-yellow-500 animate-pulse":"bg-green-500"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold",children:[t.platform," · v",t.version]}),e.jsxs("div",{className:`text-xs ${a}`,children:[t.maintenance_mode?"Maintenance mode is ON":"Serving traffic",p?` · ${p.disabled_agents} disabled · metrics ${p.prometheus_available?"on":"off"}`:"",v?" · control token required for mutations":""]})]})]}),e.jsx("button",{onClick:I,disabled:u,title:d?"Another control-plane change is in progress":u?"Enter X-Control-Token to change maintenance mode":void 0,className:`px-4 py-2 rounded-lg text-sm font-medium ${t.maintenance_mode?"bg-green-600 text-white hover:bg-green-700":"bg-yellow-600 text-white hover:bg-yellow-700"} disabled:cursor-not-allowed disabled:opacity-50`,children:d==="maintenance"?t.maintenance_mode?"Resuming traffic…":"Entering maintenance…":t.maintenance_mode?"Resume traffic":"Enter maintenance"})]}),e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Agents"}),e.jsx("div",{className:`overflow-x-auto rounded-xl border ${b}`,children:e.jsxs("table",{className:"min-w-[44rem] w-full text-sm",children:[e.jsx("thead",{className:o?"bg-gray-700/50":"bg-gray-100",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3",children:"Agent"}),e.jsx("th",{className:"px-4 py-3",children:"Framework"}),e.jsx("th",{className:"px-4 py-3",children:"Health"}),e.jsx("th",{className:"px-4 py-3",children:"Agent policy"}),e.jsx("th",{className:"px-4 py-3",children:"Connections"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Action"})]})}),e.jsxs("tbody",{children:[y.map(s=>e.jsxs("tr",{className:`border-t ${o?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium",children:s.name}),e.jsx("div",{className:`text-xs ${a}`,children:s.description||s.slug})]}),e.jsx("td",{className:"px-4 py-3",children:s.framework||"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${K(s.health?.status)}`}),s.health?.status||"unknown"]})}),e.jsx("td",{className:"px-4 py-3",children:s.requires_auth?e.jsxs("span",{className:"text-xs",title:`roles: ${s.allowed_roles.join(", ")||"—"} +import{u as P,A as q,j as e,V as h}from"./index-FSSL6O5F.js";import{r as l,R as F}from"./react-vendor-BHJ3EV8m.js";import"./syntax-vendor-ru7AzRyY.js";const f="agentomatic_control_token",K=r=>{switch(r){case"healthy":case"ok":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},D=()=>{const{config:r,darkMode:o}=P(),[t,w]=l.useState(null),[p,_]=l.useState(null),[y,$]=l.useState([]),[j,k]=l.useState({}),[C,A]=l.useState(!0),[g,N]=l.useState(null),[d,m]=l.useState(null),[x,S]=l.useState(()=>sessionStorage.getItem(f)||""),n=F.useMemo(()=>r?.apiUrl?new q(r.apiUrl,r.apiKey||void 0):null,[r?.apiUrl,r?.apiKey]),i=l.useCallback(async()=>{if(n)try{const[s,c,T,M]=await Promise.all([n.getControlInfo(),n.getControlMetricsSummary(),n.listControlAgents(),n.getControlConfig()]);w(s),_(c),$(T),k(M.features||{}),N(null)}catch(s){const c=s?.status===404?"Control plane is not enabled on this platform (start with enable_control_plane=True).":s?.message||"Failed to load control plane";N(c)}finally{A(!1)}},[n]);l.useEffect(()=>{i();const s=setInterval(i,5e3);return()=>clearInterval(s)},[i]);const E=s=>{S(s),s?sessionStorage.setItem(f,s):sessionStorage.removeItem(f)},R=async s=>{if(n){m(`agent:${s.name}`);try{await n.setAgentEnabled(s.name,!s.enabled,x||void 0),h.success(`${s.name} ${s.enabled?"disabled":"enabled"}`),i()}catch(c){h.error(c?.status===401?"Invalid control token":c?.message||"Action failed")}finally{m(null)}}},I=async()=>{if(!(!n||!t)){m("maintenance");try{await n.setMaintenance(!t.maintenance_mode,x||void 0),h.success(`Maintenance mode ${t.maintenance_mode?"disabled":"enabled"}`),i()}catch(s){h.error(s?.status===401?"Invalid control token":s?.message||"Action failed")}finally{m(null)}}},b=o?"bg-gray-800 border-gray-700":"bg-white border-gray-200",a=o?"text-gray-400":"text-gray-500",v=!!t?.control_token_required,u=v&&!x||d!==null;return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${o?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Control Plane"}),e.jsx("p",{className:`text-sm ${a}`,children:"Runtime operations & health"})]}),e.jsxs("div",{className:"flex w-full items-center gap-2 sm:w-auto",children:[e.jsx("input",{type:"password","aria-label":"X-Control-Token (optional)",value:x,onChange:s=>E(s.target.value),placeholder:"X-Control-Token (optional)",className:`min-w-0 flex-1 px-3 py-2 rounded-lg text-sm border sm:w-56 sm:flex-none ${o?"bg-gray-800 border-gray-700 text-white":"bg-white border-gray-300"}`}),e.jsx("button",{type:"button",onClick:i,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]})]}),C&&e.jsx("div",{className:a,children:"Loading control plane…"}),g&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${o?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:g}),!g&&t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 mb-6",children:[{label:"Agents",value:t.agent_count},{label:"Endpoints",value:t.endpoint_count},{label:"Plugins",value:t.plugin_count},{label:"Pipelines",value:t.pipeline_count},{label:"Conn. scopes",value:t.connection_scopes},{label:"Uptime (s)",value:Math.round(t.uptime_seconds)}].map(s=>e.jsxs("div",{className:`p-4 rounded-xl border ${b}`,children:[e.jsx("div",{className:"text-2xl font-bold",children:s.value}),e.jsx("div",{className:`text-xs ${a}`,children:s.label})]},s.label))}),e.jsxs("div",{className:`mb-6 flex flex-col gap-3 rounded-xl border p-4 sm:flex-row sm:items-center sm:justify-between ${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`w-3 h-3 rounded-full ${t.maintenance_mode?"bg-yellow-500 animate-pulse":"bg-green-500"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold",children:[t.platform," · v",t.version]}),e.jsxs("div",{className:`text-xs ${a}`,children:[t.maintenance_mode?"Maintenance mode is ON":"Serving traffic",p?` · ${p.disabled_agents} disabled · metrics ${p.prometheus_available?"on":"off"}`:"",v?" · control token required for mutations":""]})]})]}),e.jsx("button",{onClick:I,disabled:u,title:d?"Another control-plane change is in progress":u?"Enter X-Control-Token to change maintenance mode":void 0,className:`px-4 py-2 rounded-lg text-sm font-medium ${t.maintenance_mode?"bg-green-600 text-white hover:bg-green-700":"bg-yellow-600 text-white hover:bg-yellow-700"} disabled:cursor-not-allowed disabled:opacity-50`,children:d==="maintenance"?t.maintenance_mode?"Resuming traffic…":"Entering maintenance…":t.maintenance_mode?"Resume traffic":"Enter maintenance"})]}),e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Agents"}),e.jsx("div",{className:`overflow-x-auto rounded-xl border ${b}`,children:e.jsxs("table",{className:"min-w-[44rem] w-full text-sm",children:[e.jsx("thead",{className:o?"bg-gray-700/50":"bg-gray-100",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3",children:"Agent"}),e.jsx("th",{className:"px-4 py-3",children:"Framework"}),e.jsx("th",{className:"px-4 py-3",children:"Health"}),e.jsx("th",{className:"px-4 py-3",children:"Agent policy"}),e.jsx("th",{className:"px-4 py-3",children:"Connections"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Action"})]})}),e.jsxs("tbody",{children:[y.map(s=>e.jsxs("tr",{className:`border-t ${o?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium",children:s.name}),e.jsx("div",{className:`text-xs ${a}`,children:s.description||s.slug})]}),e.jsx("td",{className:"px-4 py-3",children:s.framework||"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${K(s.health?.status)}`}),s.health?.status||"unknown"]})}),e.jsx("td",{className:"px-4 py-3",children:s.requires_auth?e.jsxs("span",{className:"text-xs",title:`roles: ${s.allowed_roles.join(", ")||"—"} scopes: ${s.allowed_scopes.join(", ")||"—"}`,children:["🔒 ",s.allowed_roles.length+s.allowed_scopes.length," rule(s)"]}):e.jsx("span",{className:`text-xs ${a}`,title:j.auth?"No per-agent rules; platform API-key authentication is still required.":"No platform or per-agent authentication rules.",children:j.auth?"policy open · API key":"open"})}),e.jsx("td",{className:"px-4 py-3",children:s.connections.length?e.jsx("span",{className:"text-xs",children:s.connections.join(", ")}):e.jsx("span",{className:`text-xs ${a}`,children:"—"})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx("button",{onClick:()=>R(s),disabled:u,title:d?"Another control-plane change is in progress":u?"Enter X-Control-Token to change agent routing":void 0,className:`px-3 py-1.5 rounded-lg text-xs font-medium ${s.enabled?"bg-red-600 text-white hover:bg-red-700":"bg-green-600 text-white hover:bg-green-700"} disabled:cursor-not-allowed disabled:opacity-50`,children:d===`agent:${s.name}`?s.enabled?"Draining…":"Enabling…":s.enabled?"Drain":"Enable"})})]},s.name)),y.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:`px-4 py-6 text-center ${a}`,children:"No agents registered."})})]})]})})]})]})};export{D as ControlPlaneView}; diff --git a/src/agentomatic/studio/static/assets/DebugView-v__T__mW.js b/src/agentomatic/studio/static/assets/DebugView-Bwa7sy_c.js similarity index 99% rename from src/agentomatic/studio/static/assets/DebugView-v__T__mW.js rename to src/agentomatic/studio/static/assets/DebugView-Bwa7sy_c.js index 270c3a41..6bb76ac6 100644 --- a/src/agentomatic/studio/static/assets/DebugView-v__T__mW.js +++ b/src/agentomatic/studio/static/assets/DebugView-Bwa7sy_c.js @@ -1 +1 @@ -import{u as T,j as e,A as O,f as W,V as f}from"./index-A2k5j4o2.js";import{r as o,R as F}from"./react-vendor-BHJ3EV8m.js";import{F as I}from"./ClipboardDocumentIcon-Cnz7XqGa.js";import"./syntax-vendor-ru7AzRyY.js";function V({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.75 19.5 8.25 12l7.5-7.5"}))}const P=o.forwardRef(V);function H({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m8.25 4.5 7.5 7.5-7.5 7.5"}))}const z=o.forwardRef(H),ee=()=>{const{graphState:l,selectedThread:t,darkMode:s,executionContext:n,selectedAgent:x,config:m}=T(),[d,r]=o.useState("state"),[c,u]=o.useState(""),[p,v]=o.useState("ALL"),[N,_]=o.useState(0),[j,w]=o.useState(null),[$,h]=o.useState([]),[b,S]=o.useState(!1),[R,L]=o.useState(void 0);o.useEffect(()=>{let a=!0;return(async()=>{if(!x?.id||!t?.id||!m?.apiUrl){w(null),h([]),L(void 0),S(!1);return}S(!0);try{const y=await new O(m.apiUrl,m.apiKey).getState(x.id,t.id);a&&(w(y),L(void 0))}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load real state, using execution context",y),a&&L(y)}try{const y=await new O(m.apiUrl,m.apiKey).getHistory(x.id,t.id);a&&h(y)}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load history",y),a&&L(E=>E||y)}a&&S(!1)})(),()=>{a=!1}},[x?.id,t?.id,m?.apiUrl,m?.apiKey]);const D=n.isExecuting&&n.currentState&&Object.keys(n.currentState).length>0?{...j?.state||{},...n.currentState}:void 0,A=j?{messages:t?.messages||[],current_node:l?.currentNode||j.state?.current_node||"agent",execution_path:l?.executionPath||[],variables:D||j.state||n.currentState||{},metadata:{agent_name:j.agent_name||x?.name||"unknown",thread_id:j.thread_id||t?.id||"unknown",checkpoint_id:j.checkpoint_id||null,timestamp:j.timestamp||new Date().toISOString()}}:{messages:t?.messages||[],current_node:l?.currentNode||"agent",execution_path:l?.executionPath||[],variables:D||n.currentState||{},metadata:{agent_name:x?.name||"unknown",thread_id:t?.id||"unknown",timestamp:new Date().toISOString()}},C=n.logs.filter(a=>a.type==="input"||a.type==="output").reduce((a,i,g)=>{const y=a.find(E=>E.node===i.nodeId);return y?i.type==="output"&&(y.status="completed",y.output=i.data?.output||i.data,y.duration=i.duration||null):a.push({id:i.id||`step_${g}`,node:i.nodeId,status:i.type==="output"?"completed":i.type==="error"?"error":"running",input:i.type==="input"?i.data?.input||i.data:null,output:i.type==="output"?i.data?.output||i.data:null,timestamp:i.timestamp,duration:i.duration||null,tokens_used:0}),a},[]),B=n.logs.map(a=>({level:a.type==="error"?"ERROR":a.type==="debug"?"DEBUG":(a.type==="info","INFO"),message:a.message,timestamp:a.timestamp,node:a.nodeId,details:a.data||{}})),J={total_execution_time:n.startTime&&n.endTime?n.endTime.getTime()-n.startTime.getTime():n.startTime?Date.now()-n.startTime.getTime():0,node_performance:Object.entries(n.logs.reduce((a,i)=>(i.duration!==void 0&&(a[i.nodeId]||(a[i.nodeId]={total:0,count:0}),a[i.nodeId].total+=i.duration,a[i.nodeId].count+=1),a),{})).map(([a,i])=>({node:a,avg_duration:Number((i.total/i.count).toFixed(2)),calls:i.count,total_time:Number(i.total.toFixed(2))})),memory_usage:{current:"N/A",peak:"N/A",average:"N/A"},token_usage:n.logs.reduce((a,i)=>{const g=i.data?.output?.metadata?.tokens_used||i.data?.metadata?.tokens_used||0;return g&&(a.total+=g),a},{total:0,input:0,output:0,cost_estimate:"$0.00"})},U=B.filter(a=>{const i=a.message.toLowerCase().includes(c.toLowerCase())||a.node.toLowerCase().includes(c.toLowerCase()),g=p==="ALL"||a.level===p;return i&&g});return e.jsxs("div",{className:`h-full flex flex-col transition-all duration-300 ${s?"bg-gray-900":"bg-gray-50"}`,children:[R&&e.jsxs("div",{className:`px-4 py-3 text-sm border-b ${s?"bg-red-900/40 border-red-700 text-red-200":"bg-red-50 border-red-200 text-red-800"}`,role:"alert",children:[e.jsx("strong",{children:"Debug load error:"})," ",R]}),e.jsxs("div",{className:`relative overflow-hidden ${s?"bg-gradient-to-r from-gray-800 via-gray-700 to-gray-800":"bg-gradient-to-r from-blue-50 via-white to-purple-50"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),e.jsx("div",{className:"relative border-b border-gray-200 p-4 sm:p-6 dark:border-gray-700",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center space-x-3 sm:space-x-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${s?"bg-blue-600/20 text-blue-400":"bg-blue-100 text-blue-600"}`,children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}),e.jsxs("div",{children:[e.jsx("h2",{className:`text-xl font-bold sm:text-2xl ${s?"text-white":"text-gray-900"}`,children:"Debug Console"}),e.jsx("p",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:"Real-time graph execution monitoring and analysis"})]})]}),e.jsxs("div",{className:"hidden items-center space-x-3 sm:flex",children:[e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full animate-pulse ${b?"bg-amber-500":"bg-green-500"}`}),e.jsx("span",{className:`text-sm font-medium ${s?"text-gray-300":"text-gray-700"}`,children:b?"Loading state…":"Live"})]}),e.jsx("div",{className:`px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:e.jsxs("span",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:[C.filter(a=>a.status==="completed").length,"/",C.length," Steps"]})})]})]})})]}),e.jsx("div",{className:`border-b ${s?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsx("div",{className:"overflow-x-auto px-3 sm:px-6",children:e.jsx("nav",{className:"flex min-w-max space-x-5 sm:space-x-8",children:[{id:"state",label:"State",icon:"🔍",count:Object.keys(A.variables).length},{id:"history",label:"Time Travel",icon:"⏪",count:$.length},{id:"steps",label:"Steps",icon:"📋",count:C.length},{id:"logs",label:"Logs",icon:"📝",count:U.length},{id:"performance",label:"Performance",icon:"⚡",count:J.node_performance.length}].map(a=>e.jsx("button",{onClick:()=>r(a.id),className:`relative py-4 px-1 font-medium text-sm transition-all duration-200 ${d===a.id?s?"text-blue-400 border-b-2 border-blue-400":"text-blue-600 border-b-2 border-blue-500":s?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{children:a.icon}),e.jsx("span",{children:a.label}),e.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${d===a.id?s?"bg-blue-600 text-white":"bg-blue-100 text-blue-600":s?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-600"}`,children:a.count})]})},a.id))})})}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[d==="state"&&e.jsx(G,{state:A,darkMode:s,isExecuting:n.isExecuting,onStateUpdated:w}),d==="history"&&e.jsx(X,{history:$,darkMode:s,checkpointIndex:N,setCheckpointIndex:_}),d==="steps"&&e.jsx(K,{steps:C,darkMode:s}),d==="logs"&&e.jsx(q,{logs:U,darkMode:s,searchTerm:c,setSearchTerm:u,logLevel:p,setLogLevel:v}),d==="performance"&&e.jsx(Q,{performance:J,darkMode:s})]})]})},G=({state:l,darkMode:t,isExecuting:s,onStateUpdated:n})=>{const[x,m]=o.useState(new Set(["variables"])),[d,r]=o.useState(!1),[c,u]=o.useState(""),{selectedAgent:p,selectedThread:v,config:N}=T(),_=async()=>{try{await navigator.clipboard.writeText(JSON.stringify(l.variables,null,2)),f.success("State JSON copied to clipboard")}catch{f.error("Failed to copy to clipboard")}},j=()=>{u(JSON.stringify(l.variables,null,2)),r(!0)},w=async()=>{let h;try{h=JSON.parse(c)}catch{f.error("State must be valid JSON");return}if(!p||!v||!N?.apiUrl){f.error("Select an agent and thread before editing state");return}try{const S=await new O(N.apiUrl,N.apiKey).updateState(p.id,v.id,h);n(S),r(!1),f.success("State updated")}catch(b){f.error(b instanceof Error?b.message:"Failed to update state")}},$=h=>{const b=new Set(x);b.has(h)?b.delete(h):b.add(h),m(b)};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("h3",{className:`text-lg font-semibold mb-4 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("svg",{className:"w-5 h-5 mr-2 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Execution Overview",s&&e.jsxs("span",{className:"ml-3 flex items-center space-x-2",children:[e.jsxs("span",{className:"relative flex h-3 w-3",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-green-500"})]}),e.jsx("span",{className:`text-xs font-normal ${t?"text-green-400":"text-green-600"}`,children:"Live updating"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Current Node"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:l.current_node})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Steps Completed"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.execution_path?.length||0})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Messages"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.messages?.length||0})]})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Execution Path"}),e.jsx("div",{className:"flex items-center space-x-2 flex-wrap gap-2",children:l.execution_path?.map((h,b)=>e.jsxs(F.Fragment,{children:[e.jsxs("div",{className:`flex items-center px-4 py-2 rounded-lg border-2 ${t?"bg-blue-600 border-blue-500 text-white":"bg-blue-50 border-blue-200 text-blue-700"}`,children:[e.jsx("span",{className:`w-6 h-6 rounded-full flex items-center justify-center mr-2 text-xs font-bold ${t?"bg-blue-500":"bg-blue-200"}`,children:b+1}),h]}),br(!1),className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Cancel"})]}):e.jsx("button",{onClick:j,className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Edit State"})]}),e.jsx("button",{onClick:()=>$("variables"),children:e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("variables")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]}),x.has("variables")&&e.jsx("div",{className:`mx-6 mb-6 p-4 rounded-lg overflow-x-auto ${t?"bg-gray-900":"bg-gray-50"}`,children:d?e.jsx("textarea",{"aria-label":"Edit state JSON",className:`w-full h-64 p-2 font-mono text-sm rounded ${t?"bg-gray-800 text-green-400":"bg-white text-green-600"}`,value:c,onChange:h=>u(h.target.value)}):e.jsx("pre",{className:`text-sm font-mono ${t?"text-green-400":"text-green-600"}`,children:JSON.stringify(l.variables,null,2)})})]}),e.jsxs("div",{className:`rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("button",{onClick:()=>$("metadata"),className:`w-full p-6 text-left flex items-center justify-between ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Metadata"}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("metadata")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),x.has("metadata")&&e.jsx("div",{className:"px-6 pb-6",children:e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(l.metadata,null,2)})})})]})]})})},K=({steps:l,darkMode:t})=>{const[s,n]=o.useState(new Set),x=r=>{const c=new Set(s);c.has(r)?c.delete(r):c.add(r),n(c)},m=r=>{switch(r){case"completed":return"text-green-600 bg-green-100 border-green-200";case"running":return"text-blue-600 bg-blue-100 border-blue-200";case"error":return"text-red-600 bg-red-100 border-red-200";default:return"text-gray-600 bg-gray-100 border-gray-200"}},d=r=>{switch(r){case"completed":return"text-green-400 bg-green-900/30 border-green-700";case"running":return"text-blue-400 bg-blue-900/30 border-blue-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsx("div",{className:"max-w-4xl mx-auto space-y-4",children:l.map((r,c)=>{const u=s.has(r.id),p=t?d(r.status):m(r.status);return e.jsxs("div",{className:`rounded-xl border transition-all duration-200 ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"} hover:shadow-lg`,children:[e.jsx("button",{onClick:()=>x(r.id),className:`w-full p-6 text-left ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`flex items-center justify-center w-10 h-10 rounded-full font-bold ${t?"bg-blue-600 text-white":"bg-blue-100 text-blue-600"}`,children:c+1}),e.jsxs("div",{children:[e.jsx("h4",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:r.node}),e.jsxs("p",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:["Step ID: ",r.id]})]})]}),e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`px-3 py-1 rounded-full text-sm font-medium border ${p}`,children:r.status}),r.duration&&e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:[r.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${u?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}),u&&e.jsxs("div",{className:`px-6 pb-6 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6",children:[r.input&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Input Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.input,null,2)})})]}),r.output&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Output Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.output,null,2)})})]})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Timestamp"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.timestamp?W(r.timestamp,"HH:mm:ss.SSS"):"Pending"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Duration"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.duration?`${r.duration}ms`:"N/A"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Tokens Used"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.tokens_used||0})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Status"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.status})]})]})]})]},r.id)})})})},q=({logs:l,darkMode:t,searchTerm:s,setSearchTerm:n,logLevel:x,setLogLevel:m})=>{const d=r=>{switch(r){case"ERROR":return t?"text-red-400 bg-red-900/30":"text-red-700 bg-red-50";case"WARN":return t?"text-yellow-400 bg-yellow-900/30":"text-yellow-700 bg-yellow-50";case"INFO":return t?"text-blue-400 bg-blue-900/30":"text-blue-700 bg-blue-50";case"DEBUG":return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100";default:return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100"}};return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:`p-4 border-b ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx("svg",{className:`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),e.jsx("input",{type:"text",placeholder:"Search logs...",value:s,onChange:r=>n(r.target.value),className:`w-full pl-10 pr-4 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`})]}),e.jsxs("select",{value:x,onChange:r=>m(r.target.value),className:`px-3 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`,children:[e.jsx("option",{value:"ALL",children:"All Levels"}),e.jsx("option",{value:"ERROR",children:"Error"}),e.jsx("option",{value:"WARN",children:"Warning"}),e.jsx("option",{value:"INFO",children:"Info"}),e.jsx("option",{value:"DEBUG",children:"Debug"})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 custom-scrollbar",children:e.jsx("div",{className:"space-y-3",children:l.map((r,c)=>e.jsx("div",{className:`rounded-lg border p-4 transition-all duration-200 hover:shadow-md ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx("div",{className:`px-2 py-1 rounded text-xs font-bold ${d(r.level)}`,children:r.level}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.message}),e.jsxs("div",{className:"flex items-center space-x-4 mt-2",children:[e.jsx("span",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:W(r.timestamp,"HH:mm:ss.SSS")}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:r.node})]}),r.details&&e.jsx("div",{className:`mt-3 p-3 rounded ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.details,null,2)})})]})]})},c))})})]})},Q=({performance:l,darkMode:t})=>e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Execution"}),e.jsxs("div",{className:`text-2xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:[l.total_execution_time,"ms"]})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Memory Usage"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.memory_usage.current})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Tokens"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.token_usage.total})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Cost Estimate"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-yellow-400":"text-yellow-600"}`,children:l.token_usage.cost_estimate})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Node Performance"}),e.jsx("div",{className:"space-y-4",children:l.node_performance.map(s=>e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:`font-medium ${t?"text-white":"text-gray-900"}`,children:s.node}),e.jsxs("span",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[s.calls," calls"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Avg Duration"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.avg_duration,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Total Time"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.total_time,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Efficiency"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[Math.round(s.total_time/l.total_execution_time*100),"%"]})]})]})]},s.node))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Memory Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.memory_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Token Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.token_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]})]})]})}),X=({history:l,darkMode:t,checkpointIndex:s,setCheckpointIndex:n})=>{const{startGlobalExecution:x}=T(),m=u=>{x("graph",{checkpoint_id:u})},d=()=>{s>0&&n(s-1)},r=()=>{s0?Math.min(s,l.length-1):0;return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Time Travel Debugging"}),e.jsx("p",{className:`text-sm mb-2 ${t?"text-gray-400":"text-gray-600"}`,children:"Review past states and fork execution from any checkpoint."})]}),l.length>1&&e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("button",{onClick:d,disabled:c===0,className:`p-1 rounded transition-colors ${c===0?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Previous checkpoint",children:e.jsx(P,{className:"w-5 h-5"})}),e.jsxs("span",{className:`text-sm font-medium min-w-[4rem] text-center ${t?"text-gray-300":"text-gray-700"}`,children:[c+1," / ",l.length]}),e.jsx("button",{onClick:r,disabled:c>=l.length-1,className:`p-1 rounded transition-colors ${c>=l.length-1?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Next checkpoint",children:e.jsx(z,{className:"w-5 h-5"})})]})]}),l.length===0?e.jsx("div",{className:`p-8 text-center rounded-xl border ${t?"bg-gray-800 border-gray-700 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:"No history available for this thread."}):e.jsx("div",{className:"space-y-4",children:l.map((u,p)=>e.jsxs("div",{className:`p-4 rounded-xl border flex items-center justify-between ${p===c?t?"bg-blue-900/20 border-blue-700 ring-1 ring-blue-600":"bg-blue-50 border-blue-300 ring-1 ring-blue-400":t?"bg-gray-800 border-gray-700 hover:bg-gray-750":"bg-white border-gray-200 hover:bg-gray-50"} transition-colors cursor-pointer`,onClick:()=>n(p),children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${p===c?"bg-blue-600 text-white":t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:p+1}),e.jsxs("div",{children:[e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:["Checkpoint ",u.id.slice(0,8),"..."]}),e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:new Date(u.timestamp).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[Object.keys(u.state||{}).length," variables"]}),e.jsxs("button",{onClick:v=>{v.stopPropagation(),m(u.id)},className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg shadow-sm transition-colors flex items-center",children:[e.jsxs("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})]}),"Replay from here"]})]})]},u.id))})]})})};export{ee as DebugView}; +import{u as T,j as e,A as O,f as W,V as f}from"./index-FSSL6O5F.js";import{r as o,R as F}from"./react-vendor-BHJ3EV8m.js";import{F as I}from"./ClipboardDocumentIcon-Cnz7XqGa.js";import"./syntax-vendor-ru7AzRyY.js";function V({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.75 19.5 8.25 12l7.5-7.5"}))}const P=o.forwardRef(V);function H({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m8.25 4.5 7.5 7.5-7.5 7.5"}))}const z=o.forwardRef(H),ee=()=>{const{graphState:l,selectedThread:t,darkMode:s,executionContext:n,selectedAgent:x,config:m}=T(),[d,r]=o.useState("state"),[c,u]=o.useState(""),[p,v]=o.useState("ALL"),[N,_]=o.useState(0),[j,w]=o.useState(null),[$,h]=o.useState([]),[b,S]=o.useState(!1),[R,L]=o.useState(void 0);o.useEffect(()=>{let a=!0;return(async()=>{if(!x?.id||!t?.id||!m?.apiUrl){w(null),h([]),L(void 0),S(!1);return}S(!0);try{const y=await new O(m.apiUrl,m.apiKey).getState(x.id,t.id);a&&(w(y),L(void 0))}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load real state, using execution context",y),a&&L(y)}try{const y=await new O(m.apiUrl,m.apiKey).getHistory(x.id,t.id);a&&h(y)}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load history",y),a&&L(E=>E||y)}a&&S(!1)})(),()=>{a=!1}},[x?.id,t?.id,m?.apiUrl,m?.apiKey]);const D=n.isExecuting&&n.currentState&&Object.keys(n.currentState).length>0?{...j?.state||{},...n.currentState}:void 0,A=j?{messages:t?.messages||[],current_node:l?.currentNode||j.state?.current_node||"agent",execution_path:l?.executionPath||[],variables:D||j.state||n.currentState||{},metadata:{agent_name:j.agent_name||x?.name||"unknown",thread_id:j.thread_id||t?.id||"unknown",checkpoint_id:j.checkpoint_id||null,timestamp:j.timestamp||new Date().toISOString()}}:{messages:t?.messages||[],current_node:l?.currentNode||"agent",execution_path:l?.executionPath||[],variables:D||n.currentState||{},metadata:{agent_name:x?.name||"unknown",thread_id:t?.id||"unknown",timestamp:new Date().toISOString()}},C=n.logs.filter(a=>a.type==="input"||a.type==="output").reduce((a,i,g)=>{const y=a.find(E=>E.node===i.nodeId);return y?i.type==="output"&&(y.status="completed",y.output=i.data?.output||i.data,y.duration=i.duration||null):a.push({id:i.id||`step_${g}`,node:i.nodeId,status:i.type==="output"?"completed":i.type==="error"?"error":"running",input:i.type==="input"?i.data?.input||i.data:null,output:i.type==="output"?i.data?.output||i.data:null,timestamp:i.timestamp,duration:i.duration||null,tokens_used:0}),a},[]),B=n.logs.map(a=>({level:a.type==="error"?"ERROR":a.type==="debug"?"DEBUG":(a.type==="info","INFO"),message:a.message,timestamp:a.timestamp,node:a.nodeId,details:a.data||{}})),J={total_execution_time:n.startTime&&n.endTime?n.endTime.getTime()-n.startTime.getTime():n.startTime?Date.now()-n.startTime.getTime():0,node_performance:Object.entries(n.logs.reduce((a,i)=>(i.duration!==void 0&&(a[i.nodeId]||(a[i.nodeId]={total:0,count:0}),a[i.nodeId].total+=i.duration,a[i.nodeId].count+=1),a),{})).map(([a,i])=>({node:a,avg_duration:Number((i.total/i.count).toFixed(2)),calls:i.count,total_time:Number(i.total.toFixed(2))})),memory_usage:{current:"N/A",peak:"N/A",average:"N/A"},token_usage:n.logs.reduce((a,i)=>{const g=i.data?.output?.metadata?.tokens_used||i.data?.metadata?.tokens_used||0;return g&&(a.total+=g),a},{total:0,input:0,output:0,cost_estimate:"$0.00"})},U=B.filter(a=>{const i=a.message.toLowerCase().includes(c.toLowerCase())||a.node.toLowerCase().includes(c.toLowerCase()),g=p==="ALL"||a.level===p;return i&&g});return e.jsxs("div",{className:`h-full flex flex-col transition-all duration-300 ${s?"bg-gray-900":"bg-gray-50"}`,children:[R&&e.jsxs("div",{className:`px-4 py-3 text-sm border-b ${s?"bg-red-900/40 border-red-700 text-red-200":"bg-red-50 border-red-200 text-red-800"}`,role:"alert",children:[e.jsx("strong",{children:"Debug load error:"})," ",R]}),e.jsxs("div",{className:`relative overflow-hidden ${s?"bg-gradient-to-r from-gray-800 via-gray-700 to-gray-800":"bg-gradient-to-r from-blue-50 via-white to-purple-50"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),e.jsx("div",{className:"relative border-b border-gray-200 p-4 sm:p-6 dark:border-gray-700",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center space-x-3 sm:space-x-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${s?"bg-blue-600/20 text-blue-400":"bg-blue-100 text-blue-600"}`,children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}),e.jsxs("div",{children:[e.jsx("h2",{className:`text-xl font-bold sm:text-2xl ${s?"text-white":"text-gray-900"}`,children:"Debug Console"}),e.jsx("p",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:"Real-time graph execution monitoring and analysis"})]})]}),e.jsxs("div",{className:"hidden items-center space-x-3 sm:flex",children:[e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full animate-pulse ${b?"bg-amber-500":"bg-green-500"}`}),e.jsx("span",{className:`text-sm font-medium ${s?"text-gray-300":"text-gray-700"}`,children:b?"Loading state…":"Live"})]}),e.jsx("div",{className:`px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:e.jsxs("span",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:[C.filter(a=>a.status==="completed").length,"/",C.length," Steps"]})})]})]})})]}),e.jsx("div",{className:`border-b ${s?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsx("div",{className:"overflow-x-auto px-3 sm:px-6",children:e.jsx("nav",{className:"flex min-w-max space-x-5 sm:space-x-8",children:[{id:"state",label:"State",icon:"🔍",count:Object.keys(A.variables).length},{id:"history",label:"Time Travel",icon:"⏪",count:$.length},{id:"steps",label:"Steps",icon:"📋",count:C.length},{id:"logs",label:"Logs",icon:"📝",count:U.length},{id:"performance",label:"Performance",icon:"⚡",count:J.node_performance.length}].map(a=>e.jsx("button",{onClick:()=>r(a.id),className:`relative py-4 px-1 font-medium text-sm transition-all duration-200 ${d===a.id?s?"text-blue-400 border-b-2 border-blue-400":"text-blue-600 border-b-2 border-blue-500":s?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{children:a.icon}),e.jsx("span",{children:a.label}),e.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${d===a.id?s?"bg-blue-600 text-white":"bg-blue-100 text-blue-600":s?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-600"}`,children:a.count})]})},a.id))})})}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[d==="state"&&e.jsx(G,{state:A,darkMode:s,isExecuting:n.isExecuting,onStateUpdated:w}),d==="history"&&e.jsx(X,{history:$,darkMode:s,checkpointIndex:N,setCheckpointIndex:_}),d==="steps"&&e.jsx(K,{steps:C,darkMode:s}),d==="logs"&&e.jsx(q,{logs:U,darkMode:s,searchTerm:c,setSearchTerm:u,logLevel:p,setLogLevel:v}),d==="performance"&&e.jsx(Q,{performance:J,darkMode:s})]})]})},G=({state:l,darkMode:t,isExecuting:s,onStateUpdated:n})=>{const[x,m]=o.useState(new Set(["variables"])),[d,r]=o.useState(!1),[c,u]=o.useState(""),{selectedAgent:p,selectedThread:v,config:N}=T(),_=async()=>{try{await navigator.clipboard.writeText(JSON.stringify(l.variables,null,2)),f.success("State JSON copied to clipboard")}catch{f.error("Failed to copy to clipboard")}},j=()=>{u(JSON.stringify(l.variables,null,2)),r(!0)},w=async()=>{let h;try{h=JSON.parse(c)}catch{f.error("State must be valid JSON");return}if(!p||!v||!N?.apiUrl){f.error("Select an agent and thread before editing state");return}try{const S=await new O(N.apiUrl,N.apiKey).updateState(p.id,v.id,h);n(S),r(!1),f.success("State updated")}catch(b){f.error(b instanceof Error?b.message:"Failed to update state")}},$=h=>{const b=new Set(x);b.has(h)?b.delete(h):b.add(h),m(b)};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("h3",{className:`text-lg font-semibold mb-4 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("svg",{className:"w-5 h-5 mr-2 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Execution Overview",s&&e.jsxs("span",{className:"ml-3 flex items-center space-x-2",children:[e.jsxs("span",{className:"relative flex h-3 w-3",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-green-500"})]}),e.jsx("span",{className:`text-xs font-normal ${t?"text-green-400":"text-green-600"}`,children:"Live updating"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Current Node"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:l.current_node})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Steps Completed"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.execution_path?.length||0})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Messages"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.messages?.length||0})]})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Execution Path"}),e.jsx("div",{className:"flex items-center space-x-2 flex-wrap gap-2",children:l.execution_path?.map((h,b)=>e.jsxs(F.Fragment,{children:[e.jsxs("div",{className:`flex items-center px-4 py-2 rounded-lg border-2 ${t?"bg-blue-600 border-blue-500 text-white":"bg-blue-50 border-blue-200 text-blue-700"}`,children:[e.jsx("span",{className:`w-6 h-6 rounded-full flex items-center justify-center mr-2 text-xs font-bold ${t?"bg-blue-500":"bg-blue-200"}`,children:b+1}),h]}),br(!1),className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Cancel"})]}):e.jsx("button",{onClick:j,className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Edit State"})]}),e.jsx("button",{onClick:()=>$("variables"),children:e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("variables")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]}),x.has("variables")&&e.jsx("div",{className:`mx-6 mb-6 p-4 rounded-lg overflow-x-auto ${t?"bg-gray-900":"bg-gray-50"}`,children:d?e.jsx("textarea",{"aria-label":"Edit state JSON",className:`w-full h-64 p-2 font-mono text-sm rounded ${t?"bg-gray-800 text-green-400":"bg-white text-green-600"}`,value:c,onChange:h=>u(h.target.value)}):e.jsx("pre",{className:`text-sm font-mono ${t?"text-green-400":"text-green-600"}`,children:JSON.stringify(l.variables,null,2)})})]}),e.jsxs("div",{className:`rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("button",{onClick:()=>$("metadata"),className:`w-full p-6 text-left flex items-center justify-between ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Metadata"}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("metadata")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),x.has("metadata")&&e.jsx("div",{className:"px-6 pb-6",children:e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(l.metadata,null,2)})})})]})]})})},K=({steps:l,darkMode:t})=>{const[s,n]=o.useState(new Set),x=r=>{const c=new Set(s);c.has(r)?c.delete(r):c.add(r),n(c)},m=r=>{switch(r){case"completed":return"text-green-600 bg-green-100 border-green-200";case"running":return"text-blue-600 bg-blue-100 border-blue-200";case"error":return"text-red-600 bg-red-100 border-red-200";default:return"text-gray-600 bg-gray-100 border-gray-200"}},d=r=>{switch(r){case"completed":return"text-green-400 bg-green-900/30 border-green-700";case"running":return"text-blue-400 bg-blue-900/30 border-blue-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsx("div",{className:"max-w-4xl mx-auto space-y-4",children:l.map((r,c)=>{const u=s.has(r.id),p=t?d(r.status):m(r.status);return e.jsxs("div",{className:`rounded-xl border transition-all duration-200 ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"} hover:shadow-lg`,children:[e.jsx("button",{onClick:()=>x(r.id),className:`w-full p-6 text-left ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`flex items-center justify-center w-10 h-10 rounded-full font-bold ${t?"bg-blue-600 text-white":"bg-blue-100 text-blue-600"}`,children:c+1}),e.jsxs("div",{children:[e.jsx("h4",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:r.node}),e.jsxs("p",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:["Step ID: ",r.id]})]})]}),e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`px-3 py-1 rounded-full text-sm font-medium border ${p}`,children:r.status}),r.duration&&e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:[r.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${u?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}),u&&e.jsxs("div",{className:`px-6 pb-6 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6",children:[r.input&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Input Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.input,null,2)})})]}),r.output&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Output Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.output,null,2)})})]})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Timestamp"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.timestamp?W(r.timestamp,"HH:mm:ss.SSS"):"Pending"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Duration"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.duration?`${r.duration}ms`:"N/A"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Tokens Used"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.tokens_used||0})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Status"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.status})]})]})]})]},r.id)})})})},q=({logs:l,darkMode:t,searchTerm:s,setSearchTerm:n,logLevel:x,setLogLevel:m})=>{const d=r=>{switch(r){case"ERROR":return t?"text-red-400 bg-red-900/30":"text-red-700 bg-red-50";case"WARN":return t?"text-yellow-400 bg-yellow-900/30":"text-yellow-700 bg-yellow-50";case"INFO":return t?"text-blue-400 bg-blue-900/30":"text-blue-700 bg-blue-50";case"DEBUG":return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100";default:return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100"}};return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:`p-4 border-b ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx("svg",{className:`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),e.jsx("input",{type:"text",placeholder:"Search logs...",value:s,onChange:r=>n(r.target.value),className:`w-full pl-10 pr-4 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`})]}),e.jsxs("select",{value:x,onChange:r=>m(r.target.value),className:`px-3 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`,children:[e.jsx("option",{value:"ALL",children:"All Levels"}),e.jsx("option",{value:"ERROR",children:"Error"}),e.jsx("option",{value:"WARN",children:"Warning"}),e.jsx("option",{value:"INFO",children:"Info"}),e.jsx("option",{value:"DEBUG",children:"Debug"})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 custom-scrollbar",children:e.jsx("div",{className:"space-y-3",children:l.map((r,c)=>e.jsx("div",{className:`rounded-lg border p-4 transition-all duration-200 hover:shadow-md ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx("div",{className:`px-2 py-1 rounded text-xs font-bold ${d(r.level)}`,children:r.level}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.message}),e.jsxs("div",{className:"flex items-center space-x-4 mt-2",children:[e.jsx("span",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:W(r.timestamp,"HH:mm:ss.SSS")}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:r.node})]}),r.details&&e.jsx("div",{className:`mt-3 p-3 rounded ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.details,null,2)})})]})]})},c))})})]})},Q=({performance:l,darkMode:t})=>e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Execution"}),e.jsxs("div",{className:`text-2xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:[l.total_execution_time,"ms"]})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Memory Usage"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.memory_usage.current})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Tokens"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.token_usage.total})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Cost Estimate"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-yellow-400":"text-yellow-600"}`,children:l.token_usage.cost_estimate})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Node Performance"}),e.jsx("div",{className:"space-y-4",children:l.node_performance.map(s=>e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:`font-medium ${t?"text-white":"text-gray-900"}`,children:s.node}),e.jsxs("span",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[s.calls," calls"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Avg Duration"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.avg_duration,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Total Time"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.total_time,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Efficiency"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[Math.round(s.total_time/l.total_execution_time*100),"%"]})]})]})]},s.node))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Memory Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.memory_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Token Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.token_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]})]})]})}),X=({history:l,darkMode:t,checkpointIndex:s,setCheckpointIndex:n})=>{const{startGlobalExecution:x}=T(),m=u=>{x("graph",{checkpoint_id:u})},d=()=>{s>0&&n(s-1)},r=()=>{s0?Math.min(s,l.length-1):0;return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Time Travel Debugging"}),e.jsx("p",{className:`text-sm mb-2 ${t?"text-gray-400":"text-gray-600"}`,children:"Review past states and fork execution from any checkpoint."})]}),l.length>1&&e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("button",{onClick:d,disabled:c===0,className:`p-1 rounded transition-colors ${c===0?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Previous checkpoint",children:e.jsx(P,{className:"w-5 h-5"})}),e.jsxs("span",{className:`text-sm font-medium min-w-[4rem] text-center ${t?"text-gray-300":"text-gray-700"}`,children:[c+1," / ",l.length]}),e.jsx("button",{onClick:r,disabled:c>=l.length-1,className:`p-1 rounded transition-colors ${c>=l.length-1?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Next checkpoint",children:e.jsx(z,{className:"w-5 h-5"})})]})]}),l.length===0?e.jsx("div",{className:`p-8 text-center rounded-xl border ${t?"bg-gray-800 border-gray-700 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:"No history available for this thread."}):e.jsx("div",{className:"space-y-4",children:l.map((u,p)=>e.jsxs("div",{className:`p-4 rounded-xl border flex items-center justify-between ${p===c?t?"bg-blue-900/20 border-blue-700 ring-1 ring-blue-600":"bg-blue-50 border-blue-300 ring-1 ring-blue-400":t?"bg-gray-800 border-gray-700 hover:bg-gray-750":"bg-white border-gray-200 hover:bg-gray-50"} transition-colors cursor-pointer`,onClick:()=>n(p),children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${p===c?"bg-blue-600 text-white":t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:p+1}),e.jsxs("div",{children:[e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:["Checkpoint ",u.id.slice(0,8),"..."]}),e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:new Date(u.timestamp).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[Object.keys(u.state||{}).length," variables"]}),e.jsxs("button",{onClick:v=>{v.stopPropagation(),m(u.id)},className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg shadow-sm transition-colors flex items-center",children:[e.jsxs("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})]}),"Replay from here"]})]})]},u.id))})]})})};export{ee as DebugView}; diff --git a/src/agentomatic/studio/static/assets/EndpointsView-uQLIFHRE.js b/src/agentomatic/studio/static/assets/EndpointsView-fCUdmgxr.js similarity index 97% rename from src/agentomatic/studio/static/assets/EndpointsView-uQLIFHRE.js rename to src/agentomatic/studio/static/assets/EndpointsView-fCUdmgxr.js index 894dc472..b2ed5a64 100644 --- a/src/agentomatic/studio/static/assets/EndpointsView-uQLIFHRE.js +++ b/src/agentomatic/studio/static/assets/EndpointsView-fCUdmgxr.js @@ -1 +1 @@ -import{u as V,A as U,d as M,j as e}from"./index-A2k5j4o2.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as B}from"./SchemaForm-bIikrW9E.js";import{O as H}from"./OutputSchemaSummary-DzWXQCQ1.js";import"./syntax-vendor-ru7AzRyY.js";const y=(l,a)=>`${l}:${a.toUpperCase()}`,g=l=>l.methods.map(a=>a.toUpperCase()).filter((a,u,f)=>!!a&&f.indexOf(a)===u),T=l=>g(l).includes("POST")?"POST":g(l)[0]||"POST",Q=()=>{const{config:l,darkMode:a}=V(),[u,f]=d.useState([]),[p,P]=d.useState({}),[j,R]=d.useState({}),[F,E]=d.useState({}),[_,C]=d.useState({}),[v,k]=d.useState(null),[O,A]=d.useState({}),[b,N]=d.useState(!0),[w,h]=d.useState(null),$=d.useCallback(async()=>{if(!l?.apiUrl){N(!1);return}N(!0);try{const s=new U(l.apiUrl,l.apiKey||void 0),o=await s.listEndpoints(),n=await Promise.all(o.flatMap(t=>g(t).map(async c=>{const S=`/api/v1/endpoints/${encodeURIComponent(t.name)}${t.path}`,x=y(t.name,c);try{return{key:x,contract:await s.getOperationContract(S,c),error:null}}catch(K){return{key:x,contract:null,error:K?.message||`Could not load ${c} contract`}}}))),i=Object.fromEntries(n.flatMap(t=>t.contract?[[t.key,t.contract]]:[])),r=Object.fromEntries(n.flatMap(t=>t.error?[[t.key,t.error]]:[]));f(o),P(i),R(r),C(t=>Object.fromEntries(o.map(c=>[c.name,g(c).includes(t[c.name])?t[c.name]:T(c)]))),E(t=>Object.fromEntries(o.flatMap(c=>g(c).map(S=>{const x=y(c.name,S);return[x,t[x]??M(i[x]?.input_schema||void 0)]})))),h(null)}catch(s){h(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch endpoints")}finally{N(!1)}},[l?.apiUrl,l?.apiKey]);d.useEffect(()=>{$()},[$]);const I=async(s,o,n)=>{if(!l?.apiUrl)return;const i=y(s.name,o);k(i),h(null);try{const t=await new U(l.apiUrl,l.apiKey||void 0).callEndpoint(s.name,s.path,n,o,p[i]);A(c=>({...c,[i]:t}))}catch(r){h(r?.message||`Failed to call endpoint '${s.name}'`)}finally{k(null)}},L=a?"bg-gray-800 border-gray-700":"bg-white border-gray-200",m=a?"text-gray-400":"text-gray-600";return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${a?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Custom Endpoints"}),e.jsx("p",{className:`mt-1 text-sm ${m}`,children:"Live callable APIs. Forms and expected output are generated from each endpoint's registered OpenAPI contract."})]}),e.jsx("button",{type:"button",onClick:()=>{$()},disabled:b||v!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:b?"Refreshing…":"Refresh"})]}),b&&e.jsx("div",{className:m,children:"Loading endpoints…"}),w&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${a?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:w}),!b&&!w&&u.length===0&&e.jsx("div",{className:m,children:"No custom endpoints registered."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:u.map(s=>e.jsx("div",{className:`p-6 rounded-xl border ${L} shadow-sm`,children:(()=>{const o=_[s.name]||T(s),n=y(s.name,o),i=g(s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:s.name}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${s.ready?"bg-green-500":"bg-gray-400"}`}),s.ready?"Ready":"Idle"]})]}),e.jsx("p",{className:`text-sm mb-4 ${m}`,children:s.description||"No description provided"}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[i.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-gray-700 text-gray-200":"bg-gray-100 text-gray-700"}`,children:r},r)),e.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-violet-900 text-violet-200":"bg-violet-100 text-violet-800"}`,children:["/api/v1/endpoints/",s.name,s.path]})]}),e.jsxs("dl",{className:"text-sm space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Aggregation"}),e.jsx("dd",{className:"font-medium",children:s.aggregation||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Upstreams"}),e.jsx("dd",{className:"font-medium",children:s.upstreams.length})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Version"}),e.jsxs("dd",{className:"font-medium",children:["v",s.version]})]})]}),s.upstreams.length>0&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700",children:[e.jsx("div",{className:`text-xs mb-2 ${m}`,children:"Upstreams"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.upstreams.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs ${a?"bg-gray-700":"bg-gray-100"}`,children:r},r))})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[i.length>1&&e.jsxs("label",{className:"block text-sm font-medium",children:["Method",e.jsx("select",{"aria-label":`HTTP method for ${s.name}`,value:o,onChange:r=>C(t=>({...t,[s.name]:r.target.value})),className:`mt-1 block w-full rounded-lg border px-3 py-2 text-sm ${a?"border-gray-600 bg-gray-900 text-white":"border-gray-300 bg-white text-gray-900"}`,children:i.map(r=>e.jsx("option",{value:r,children:r},r))})]}),j[n]&&e.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${a?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live ",o," contract unavailable: ",j[n],". Testing stays disabled until the deployed schema can be read."]}),e.jsx(B,{schema:p[n]?.input_schema,value:F[n]??M(p[n]?.input_schema||void 0),onChange:r=>E(t=>({...t,[n]:r})),onSubmit:r=>{I(s,o,r)},submitLabel:v===n?`Calling ${o}…`:`Test ${o}`,disabled:v!==null||!s.ready||!!j[n],darkMode:a}),e.jsx(H,{schema:p[n]?.output_schema,darkMode:a})]}),O[n]!==void 0&&e.jsx("pre",{className:`mt-4 overflow-x-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${a?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(O[n],null,2)})]})})()},s.name))})]})};export{Q as EndpointsView}; +import{u as V,A as U,d as M,j as e}from"./index-FSSL6O5F.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as B}from"./SchemaForm-DyHc2s7z.js";import{O as H}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const y=(l,a)=>`${l}:${a.toUpperCase()}`,g=l=>l.methods.map(a=>a.toUpperCase()).filter((a,u,f)=>!!a&&f.indexOf(a)===u),T=l=>g(l).includes("POST")?"POST":g(l)[0]||"POST",Q=()=>{const{config:l,darkMode:a}=V(),[u,f]=d.useState([]),[p,P]=d.useState({}),[j,R]=d.useState({}),[F,E]=d.useState({}),[_,C]=d.useState({}),[v,k]=d.useState(null),[O,A]=d.useState({}),[b,N]=d.useState(!0),[w,h]=d.useState(null),$=d.useCallback(async()=>{if(!l?.apiUrl){N(!1);return}N(!0);try{const s=new U(l.apiUrl,l.apiKey||void 0),o=await s.listEndpoints(),n=await Promise.all(o.flatMap(t=>g(t).map(async c=>{const S=`/api/v1/endpoints/${encodeURIComponent(t.name)}${t.path}`,x=y(t.name,c);try{return{key:x,contract:await s.getOperationContract(S,c),error:null}}catch(K){return{key:x,contract:null,error:K?.message||`Could not load ${c} contract`}}}))),i=Object.fromEntries(n.flatMap(t=>t.contract?[[t.key,t.contract]]:[])),r=Object.fromEntries(n.flatMap(t=>t.error?[[t.key,t.error]]:[]));f(o),P(i),R(r),C(t=>Object.fromEntries(o.map(c=>[c.name,g(c).includes(t[c.name])?t[c.name]:T(c)]))),E(t=>Object.fromEntries(o.flatMap(c=>g(c).map(S=>{const x=y(c.name,S);return[x,t[x]??M(i[x]?.input_schema||void 0)]})))),h(null)}catch(s){h(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch endpoints")}finally{N(!1)}},[l?.apiUrl,l?.apiKey]);d.useEffect(()=>{$()},[$]);const I=async(s,o,n)=>{if(!l?.apiUrl)return;const i=y(s.name,o);k(i),h(null);try{const t=await new U(l.apiUrl,l.apiKey||void 0).callEndpoint(s.name,s.path,n,o,p[i]);A(c=>({...c,[i]:t}))}catch(r){h(r?.message||`Failed to call endpoint '${s.name}'`)}finally{k(null)}},L=a?"bg-gray-800 border-gray-700":"bg-white border-gray-200",m=a?"text-gray-400":"text-gray-600";return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${a?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Custom Endpoints"}),e.jsx("p",{className:`mt-1 text-sm ${m}`,children:"Live callable APIs. Forms and expected output are generated from each endpoint's registered OpenAPI contract."})]}),e.jsx("button",{type:"button",onClick:()=>{$()},disabled:b||v!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:b?"Refreshing…":"Refresh"})]}),b&&e.jsx("div",{className:m,children:"Loading endpoints…"}),w&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${a?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:w}),!b&&!w&&u.length===0&&e.jsx("div",{className:m,children:"No custom endpoints registered."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:u.map(s=>e.jsx("div",{className:`p-6 rounded-xl border ${L} shadow-sm`,children:(()=>{const o=_[s.name]||T(s),n=y(s.name,o),i=g(s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:s.name}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${s.ready?"bg-green-500":"bg-gray-400"}`}),s.ready?"Ready":"Idle"]})]}),e.jsx("p",{className:`text-sm mb-4 ${m}`,children:s.description||"No description provided"}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[i.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-gray-700 text-gray-200":"bg-gray-100 text-gray-700"}`,children:r},r)),e.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-violet-900 text-violet-200":"bg-violet-100 text-violet-800"}`,children:["/api/v1/endpoints/",s.name,s.path]})]}),e.jsxs("dl",{className:"text-sm space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Aggregation"}),e.jsx("dd",{className:"font-medium",children:s.aggregation||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Upstreams"}),e.jsx("dd",{className:"font-medium",children:s.upstreams.length})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Version"}),e.jsxs("dd",{className:"font-medium",children:["v",s.version]})]})]}),s.upstreams.length>0&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700",children:[e.jsx("div",{className:`text-xs mb-2 ${m}`,children:"Upstreams"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.upstreams.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs ${a?"bg-gray-700":"bg-gray-100"}`,children:r},r))})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[i.length>1&&e.jsxs("label",{className:"block text-sm font-medium",children:["Method",e.jsx("select",{"aria-label":`HTTP method for ${s.name}`,value:o,onChange:r=>C(t=>({...t,[s.name]:r.target.value})),className:`mt-1 block w-full rounded-lg border px-3 py-2 text-sm ${a?"border-gray-600 bg-gray-900 text-white":"border-gray-300 bg-white text-gray-900"}`,children:i.map(r=>e.jsx("option",{value:r,children:r},r))})]}),j[n]&&e.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${a?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live ",o," contract unavailable: ",j[n],". Testing stays disabled until the deployed schema can be read."]}),e.jsx(B,{schema:p[n]?.input_schema,value:F[n]??M(p[n]?.input_schema||void 0),onChange:r=>E(t=>({...t,[n]:r})),onSubmit:r=>{I(s,o,r)},submitLabel:v===n?`Calling ${o}…`:`Test ${o}`,disabled:v!==null||!s.ready||!!j[n],darkMode:a}),e.jsx(H,{schema:p[n]?.output_schema,darkMode:a})]}),O[n]!==void 0&&e.jsx("pre",{className:`mt-4 overflow-x-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${a?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(O[n],null,2)})]})})()},s.name))})]})};export{Q as EndpointsView}; diff --git a/src/agentomatic/studio/static/assets/GraphView-bgnAIRJp.js b/src/agentomatic/studio/static/assets/GraphView-CMqOwCTc.js similarity index 99% rename from src/agentomatic/studio/static/assets/GraphView-bgnAIRJp.js rename to src/agentomatic/studio/static/assets/GraphView-CMqOwCTc.js index ed733b0d..a84fb94b 100644 --- a/src/agentomatic/studio/static/assets/GraphView-bgnAIRJp.js +++ b/src/agentomatic/studio/static/assets/GraphView-CMqOwCTc.js @@ -1,9 +1,9 @@ -import{u as V,j as e,d as Ne,a as we,V as ce}from"./index-A2k5j4o2.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";import{S as $e}from"./SchemaForm-bIikrW9E.js";import{O as Se}from"./OutputSchemaSummary-DzWXQCQ1.js";import"./syntax-vendor-ru7AzRyY.js";const Ce=({nodeId:i,logs:t,darkMode:n,position:o,onClose:f})=>{const b=t.filter(w=>w.nodeId===i);if(b.length===0)return null;const N=b[b.length-1];return e.jsx("div",{className:"fixed z-50 pointer-events-none",style:{left:o.x+20,top:o.y-10,maxWidth:"400px"},children:e.jsxs("div",{className:`rounded-lg shadow-xl border p-4 pointer-events-auto ${n?"bg-gray-800 border-gray-600 text-white":"bg-white border-gray-200 text-gray-900"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-semibold text-sm",children:"Node Execution Details"}),e.jsx("button",{onClick:f,className:`text-xs px-2 py-1 rounded ${n?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,children:"✕"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Latest Execution"}),e.jsx("div",{className:"text-sm",children:N.message}),e.jsx("div",{className:`text-xs mt-1 ${n?"text-gray-500":"text-gray-400"}`,children:N.timestamp.toLocaleString()})]}),N.data?.intermediate_results&&e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium mb-2 ${n?"text-gray-400":"text-gray-500"}`,children:"Results Preview"}),e.jsx("div",{className:`text-xs p-2 rounded font-mono ${n?"bg-gray-900 text-gray-300":"bg-gray-50 text-gray-700"}`,children:Object.keys(N.data.intermediate_results).length>0?e.jsx("div",{children:Object.entries(N.data.intermediate_results).map(([w,m])=>e.jsxs("div",{className:"mb-1",children:[e.jsxs("span",{className:"font-semibold",children:[w,":"]})," ",typeof m=="object"&&m!==null&&"response"in m?`"${m.response?.substring(0,50)}..."`:JSON.stringify(m).substring(0,50)+"..."]},w))}):"No results available"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-gray-200 dark:border-gray-600",children:[e.jsxs("span",{className:`text-xs ${n?"text-gray-400":"text-gray-500"}`,children:[b.length," total execution",b.length!==1?"s":""]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:"Click node to view all logs"})]})]})]})})},Le=({node:i,isSelected:t,isActive:n,isHighlighted:o,hasBreakpoint:f,onClick:b,onBreakpointToggle:N,canManageBreakpoints:w,logs:m,onShowLogTooltip:d,onHideLogTooltip:_})=>{const{darkMode:l}=V(),y=m.filter(C=>C.nodeId===i.id),r=y.length>0,x=C=>{if(r){const a=C.currentTarget.getBoundingClientRect();d(i.id,{x:a.right,y:a.top})}},h=()=>{r&&_()},u=((C,a)=>{const L={start:{bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",text:l?"#bfdbfe":"#1e40af",indicator:"#3b82f6",icon:"🚀"},end:{bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",text:l?"#fecaca":"#991b1b",indicator:"#ef4444",icon:"🏁"},agent:{bg:l?"#581c87":"#f3e8ff",border:"#8b5cf6",text:l?"#ddd6fe":"#6b21a8",indicator:"#8b5cf6",icon:"🤖"},tool:{bg:l?"#14532d":"#dcfce7",border:"#10b981",text:l?"#bbf7d0":"#065f46",indicator:"#10b981",icon:"🔧"},human:{bg:l?"#92400e":"#fef3c7",border:"#f59e0b",text:l?"#fde68a":"#92400e",indicator:"#f59e0b",icon:"👤"},condition:{bg:l?"#7c2d12":"#fed7aa",border:"#ea580c",text:l?"#fed7aa":"#9a3412",indicator:"#ea580c",icon:"🔀"},retrieval:{bg:l?"#164e63":"#cffafe",border:"#0891b2",text:l?"#a5f3fc":"#164e63",indicator:"#0891b2",icon:"🔍"},processing:{bg:l?"#4c1d95":"#ede9fe",border:"#7c3aed",text:l?"#c4b5fd":"#4c1d95",indicator:"#7c3aed",icon:"⚙️"},generation:{bg:l?"#be185d":"#fce7f3",border:"#ec4899",text:l?"#fbcfe8":"#be185d",indicator:"#ec4899",icon:"✨"},validation:{bg:l?"#365314":"#ecfccb",border:"#65a30d",text:l?"#d9f99d":"#365314",indicator:"#65a30d",icon:"✅"},default:{bg:l?"#374151":"#f9fafb",border:l?"#6b7280":"#d1d5db",text:l?"#e5e7eb":"#374151",indicator:l?"#9ca3af":"#6b7280",icon:"📦"}},j=L[C]||L.default;return a==="running"?{...j,bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",indicator:"#3b82f6"}:a==="completed"?{...j,bg:l?"#14532d":"#dcfce7",border:"#10b981",indicator:"#10b981"}:a==="error"?{...j,bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",indicator:"#ef4444"}:a==="paused"?{...j,bg:l?"#92400e":"#fef3c7",border:"#f59e0b",indicator:"#f59e0b"}:j})(i.type,i.data.status),S=160,p=100;return e.jsxs("g",{transform:`translate(${i.position.x}, ${i.position.y})`,className:"cursor-pointer graph-node-group",onMouseEnter:x,onMouseLeave:h,children:[e.jsxs("defs",{children:[e.jsx("filter",{id:`shadow-${i.id}`,x:"-20%",y:"-20%",width:"140%",height:"140%",children:e.jsx("feDropShadow",{dx:"0",dy:"3",stdDeviation:"4",floodColor:l?"rgba(0,0,0,0.5)":"rgba(0,0,0,0.15)",floodOpacity:"1"})}),e.jsxs("linearGradient",{id:`gradient-${i.id}`,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:u.bg,stopOpacity:"1"}),e.jsx("stop",{offset:"100%",stopColor:u.bg,stopOpacity:"0.8"})]})]}),w&&e.jsxs("g",{className:"cursor-pointer",onClick:C=>{C.stopPropagation(),N(i.id)},children:[e.jsx("title",{children:f?"Remove breakpoint":"Add breakpoint"}),e.jsx("circle",{cx:-8,cy:8,r:7,fill:f?"#ef4444":l?"#374151":"#ffffff",stroke:f?"#fecaca":"#9ca3af",strokeWidth:2}),!f&&e.jsx("path",{d:"M-11 8h6M-8 5v6",stroke:"#6b7280",strokeWidth:1.5,strokeLinecap:"round"})]}),r&&e.jsx("circle",{cx:S-8,cy:8,r:8,fill:l?"#3b82f6":"#2563eb",stroke:l?"#1f2937":"#ffffff",strokeWidth:2,className:"cursor-pointer animate-pulse"}),r&&e.jsx("text",{x:S-8,y:8,textAnchor:"middle",dominantBaseline:"central",fontSize:"10",fill:"white",className:"pointer-events-none font-bold",children:"ℹ️"}),n&&e.jsx("rect",{width:S+12,height:p+12,x:-6,y:-6,rx:20,fill:u.indicator,opacity:"0.2",className:"animate-pulse"}),o&&e.jsx("rect",{width:S+16,height:p+16,x:-8,y:-8,rx:22,fill:"none",stroke:"#f59e0b",strokeWidth:3,strokeDasharray:"12,6",className:"animate-pulse",opacity:"0.8"}),e.jsx("rect",{width:S,height:p,rx:16,fill:`url(#gradient-${i.id})`,stroke:u.border,strokeWidth:t?3:o?2.5:2,filter:`url(#shadow-${i.id})`,onClick:()=>b(i.id),className:o?"animate-pulse":""}),e.jsx("foreignObject",{x:16,y:16,width:S-32,height:p-32,style:{pointerEvents:"none"},children:e.jsxs("div",{className:"h-full flex flex-col justify-between",style:{pointerEvents:"none"},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:"text-lg",children:u.icon}),e.jsx("span",{className:"font-semibold text-sm truncate",style:{color:u.text},children:i.data.label})]}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${i.data.status==="running"?"animate-pulse":""}`,style:{backgroundColor:u.indicator,boxShadow:i.data.status==="running"?`0 0 8px ${u.indicator}`:"none"}}),r&&e.jsx("div",{className:`text-xs px-1 py-0.5 rounded-full font-bold ${l?"bg-blue-600 text-white":"bg-blue-100 text-blue-700"}`,title:`${y.length} execution log${y.length!==1?"s":""}`,children:y.length})]})]}),e.jsx("div",{className:"text-xs px-2 py-1 rounded-full self-start font-medium",style:{backgroundColor:u.indicator+"20",color:u.text},children:i.type}),i.data.description&&e.jsx("div",{className:"text-xs mt-1 line-clamp-2 opacity-80 leading-relaxed",style:{color:u.text},children:i.data.description}),e.jsx("div",{className:"text-xs mt-1 opacity-60 font-medium",style:{color:u.text},children:r?`Click to view ${y.length} logs • Hover for details`:"Click to view • Right-click for breakpoint"})]})})]})},Ee=({edge:i,nodes:t,isActive:n,isInExecutionPath:o})=>{const{darkMode:f}=V(),b=t.find(S=>S.id===i.source),N=t.find(S=>S.id===i.target);if(!b||!N)return null;const w=160,m=100,d=b.position.x+w,_=b.position.y+m/2,l=N.position.x,y=N.position.y+m/2,r=(d+l)/2,x=`M ${d} ${_} C ${r} ${_}, ${r} ${y}, ${l} ${y}`,$=n?"#3b82f6":o?"#10b981":f?"#6b7280":"#9ca3af",u=n?3:o?2.5:2;return e.jsxs("g",{children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrowhead-${i.id}`,markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:$})})}),e.jsx("path",{d:x,fill:"none",stroke:f?"rgba(0,0,0,0.3)":"rgba(0,0,0,0.1)",strokeWidth:u+1,transform:"translate(1, 2)"}),e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u,className:`transition-all duration-300 ${n?"animate-pulse":""} ${o?"execution-path-animated":""}`,style:{filter:n?`drop-shadow(0 0 6px ${$})`:"none"},markerEnd:`url(#arrowhead-${i.id})`}),n&&e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u+4,opacity:"0.3",className:"animate-pulse"})]})},_e=({currentState:i,onStateChange:t,onStartExecution:n,darkMode:o})=>{const{selectedAgent:f,agentSchemas:b,schemasLoading:N,fetchAgentSchemas:w}=V(),m=f?.id,d=m?b[m]:void 0,[_,l]=g.useState({});g.useEffect(()=>{m&&w(m)},[m,w]),g.useEffect(()=>{const x=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object"),h=x?Ne(d?.input_schema):we(d?.input_schema),$=d?.input_schema?.properties,u=$&&typeof $=="object"?Object.fromEntries(Object.entries(i||{}).filter(([C])=>Object.prototype.hasOwnProperty.call($,C))):{};if(x){const C=i?.__root__??h;l(C),t({__root__:C});return}const p={...{...h&&typeof h=="object"&&!Array.isArray(h)?h:{},...u}};delete p.intermediate_results,delete p.execution_history,delete p.error_log,delete p.current_node,l(p),t(p)},[d?.input_schema,m]);const y=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x)},r=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x),n(x)};return e.jsxs("div",{className:`p-4 border-b space-y-3 ${o?"border-gray-600":"border-gray-200"}`,children:[N&&!d&&e.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:"Loading agent schema…"}),e.jsx($e,{schema:d?.input_schema,value:_,onChange:y,onSubmit:r,submitLabel:"Submit & Run",darkMode:o,disabled:!m,schemaSource:d?.schema_source?.input},m||"no-agent"),e.jsx(Se,{schema:d?.output_schema,source:d?.schema_source?.output,darkMode:o})]})},Te=({logs:i,darkMode:t,onLogHover:n,onLogSelect:o,selectedLogId:f,selectedNodeId:b,onClearNodeFilter:N})=>{const w=g.useRef(null),m=g.useRef(null),[d,_]=g.useState(new Set),[l,y]=g.useState(""),[r,x]=g.useState("all");g.useEffect(()=>{w.current?.scrollIntoView({behavior:"smooth"})},[i]),g.useEffect(()=>{f&&m.current&&m.current.scrollIntoView({behavior:"smooth",block:"center"})},[f]);const h=a=>{_(L=>{const j=new Set(L);return j.has(a)?j.delete(a):j.add(a),j})},$=i.filter(a=>{const L=l===""||a.message.toLowerCase().includes(l.toLowerCase())||a.nodeName.toLowerCase().includes(l.toLowerCase()),j=r==="all"||a.type===r,Y=!b||a.nodeId===b;return L&&j&&Y}),u=a=>{switch(a){case"input":return"📥";case"output":return"📤";case"error":return"❌";case"info":return"ℹ️";case"debug":return"🐛";default:return"📝"}},S=a=>{switch(a){case"input":return t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800";case"output":return t?"bg-green-900 text-green-300":"bg-green-100 text-green-800";case"error":return t?"bg-red-900 text-red-300":"bg-red-100 text-red-800";case"info":return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800";case"debug":return t?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-800";default:return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800"}},p=(a,L=!1)=>{if(!a)return null;if(typeof a=="string")return L?a:a.length>100?a.substring(0,100)+"...":a;const j=JSON.stringify(a,null,L?2:0);return!L&&j.length>200?j.substring(0,200)+"...":j},C=a=>{const L=d.has(a.id),j=f===a.id;return e.jsxs("div",{ref:j?m:void 0,className:`rounded-lg border transition-all duration-300 ${j?`log-entry-selected ${t?"bg-blue-900/30 border-blue-500 shadow-lg":"bg-blue-50 border-blue-300 shadow-lg"}`:`${t?"bg-gray-700 border-gray-600 hover:bg-gray-650":"bg-white border-gray-200 hover:bg-gray-50"} hover:log-entry-hover`}`,onMouseEnter:()=>n(a.nodeId),onMouseLeave:()=>n(null),children:[e.jsxs("div",{className:"p-4 cursor-pointer",onClick:()=>{o(j?null:a.id),h(a.id)},children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${S(a.type)}`,children:e.jsx("span",{className:"text-sm",children:u(a.type)})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:`font-semibold text-sm ${t?"text-white":"text-gray-900"}`,children:a.nodeName}),e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${S(a.type)}`,children:a.type.toUpperCase()}),j&&e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${t?"bg-yellow-900 text-yellow-300":"bg-yellow-100 text-yellow-700"}`,children:"FOCUSED"})]}),e.jsxs("div",{className:`text-xs mt-1 ${t?"text-gray-400":"text-gray-500"}`,children:[a.timestamp.toLocaleTimeString()," • Node ID: ",a.nodeId]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[a.duration&&e.jsxs("div",{className:`px-3 py-1 rounded-lg text-xs font-medium ${t?"bg-gray-600 text-gray-300":"bg-gray-100 text-gray-600"}`,children:["⏱️ ",a.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform duration-200 ${L?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]}),e.jsx("div",{className:`text-sm mb-3 p-3 rounded-lg ${t?"bg-gray-800 text-gray-300":"bg-gray-50 text-gray-700"}`,children:e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx("span",{className:"text-lg",children:"💬"}),e.jsx("span",{children:a.message})]})}),a.data?.intermediate_results&&!L&&e.jsxs("div",{className:`p-3 rounded-lg border ${t?"bg-gray-800 border-gray-600":"bg-gray-50 border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Data Preview"}),e.jsx("span",{className:`text-xs ${t?"text-blue-400":"text-blue-600"}`,children:"Click to expand"})]}),e.jsx("div",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-800"}`,children:p(a.data,!1)})]})]}),L&&a.data&&e.jsx("div",{className:`border-t ${t?"border-gray-600":"border-gray-200"}`,children:e.jsxs("div",{className:"p-4 space-y-4",children:[a.data.performance&&e.jsxs("div",{className:`p-3 rounded-lg performance-card ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"⚡"}),"Performance Metrics"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsxs("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:[a.data.performance.duration_ms,"ms"]})]}),e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Node Type"}),e.jsx("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:a.data.performance.node_type})]})]})]}),a.data.state_updates&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔄"}),"State Updates"]}),e.jsx("div",{className:"space-y-2",children:Object.entries(a.data.state_updates).map(([Y,G])=>e.jsxs("div",{className:`p-2 rounded border-l-4 border-blue-500 state-update-indicator ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${t?"text-gray-300":"text-gray-700"}`,children:Y}),e.jsx("div",{className:`text-xs font-mono mt-1 ${t?"text-gray-400":"text-gray-600"}`,children:typeof G=="object"?JSON.stringify(G,null,2):String(G)})]},Y))})]}),a.data.output&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"📤"}),"Output Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.output,null,2)})]}),a.data.current_state&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔍"}),"Current State"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.current_state,null,2)})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🗂️"}),"Raw Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data,null,2)})]})]})})]},a.id)};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${t?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:`text-sm font-semibold flex items-center ${t?"text-white":"text-gray-900"}`,children:["Live Execution Logs",b&&e.jsxs("span",{className:`ml-3 px-2 py-1 rounded text-xs font-medium flex items-center ${t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800"}`,children:["Filtered: ",b,e.jsx("button",{onClick:N,className:"ml-2 hover:text-white hover:bg-blue-800 rounded-full w-4 h-4 flex items-center justify-center transition-colors",title:"Clear filter",children:"×"})]})]}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[$.length," / ",i.length]})})]}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("input",{type:"text",placeholder:"Search logs...",value:l,onChange:a=>y(a.target.value),className:`flex-1 px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`}),e.jsxs("select",{value:r,onChange:a=>x(a.target.value),className:`px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,children:[e.jsx("option",{value:"all",children:"All Types"}),e.jsx("option",{value:"input",children:"Input"}),e.jsx("option",{value:"output",children:"Output"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"info",children:"Info"}),e.jsx("option",{value:"debug",children:"Debug"})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-3 custom-scrollbar",children:[$.length===0?e.jsxs("div",{className:`text-center py-12 ${t?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-4xl mb-4",children:"📋"}),e.jsx("p",{className:"text-lg font-medium mb-2",children:i.length===0?"No execution logs yet":"No logs match your filter"}),e.jsx("p",{className:"text-sm",children:i.length===0?"Start graph execution to see live logs":"Try adjusting your search or filter"})]}):$.map(a=>C(a)),e.jsx("div",{ref:w})]})]})},Oe=({currentState:i,executionContext:t,darkMode:n})=>{const[o,f]=g.useState(new Set(["overview"])),[b,N]=g.useState(""),w=r=>{f(x=>{const h=new Set(x);return h.has(r)?h.delete(r):h.add(r),h})},m=r=>r===null?"null":r===void 0?"undefined":typeof r=="boolean"||typeof r=="number"?r.toString():typeof r=="string"?r.length>100?`${r.substring(0,100)}...`:r:Array.isArray(r)?`Array(${r.length})`:typeof r=="object"?`Object(${Object.keys(r).length} keys)`:String(r),d=r=>r==null?n?"text-gray-500":"text-gray-400":typeof r=="boolean"?n?"text-purple-400":"text-purple-600":typeof r=="number"?n?"text-blue-400":"text-blue-600":typeof r=="string"?n?"text-green-400":"text-green-600":Array.isArray(r)?n?"text-orange-400":"text-orange-600":typeof r=="object"?n?"text-cyan-400":"text-cyan-600":n?"text-gray-300":"text-gray-700",_=r=>r==null?"∅":typeof r=="boolean"?r?"✓":"✗":typeof r=="number"?"#":typeof r=="string"?'"':Array.isArray(r)?"[]":typeof r=="object"?"{}":"?",l=Object.entries(i||{}).filter(([r,x])=>b?r.toLowerCase().includes(b.toLowerCase())||String(x).toLowerCase().includes(b.toLowerCase()):!0),y={totalSteps:t.logs.length,errors:t.logs.filter(r=>r.type==="error").length,duration:t.startTime?(t.endTime||new Date).getTime()-t.startTime.getTime():0,status:t.isExecuting?t.isPaused?"Paused":"Running":"Idle"};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:`text-sm font-semibold ${n?"text-white":"text-gray-900"}`,children:"Current State"}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[Object.keys(i||{}).length," fields"]})})]}),e.jsx("input",{type:"text",placeholder:"Search state fields...",value:b,onChange:r=>N(r.target.value),className:`w-full px-3 py-2 text-xs border rounded-lg ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("overview"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("overview")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Execution Overview"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${y.status==="Running"?"bg-blue-100 text-blue-700":y.status==="Paused"?"bg-orange-100 text-orange-700":"bg-gray-100 text-gray-700"}`,children:y.status})]})}),o.has("overview")&&e.jsx("div",{className:`px-4 pb-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Total Steps"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.totalSteps})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Errors"}),e.jsx("div",{className:`text-lg font-bold ${y.errors>0?"text-red-500":n?"text-white":"text-gray-900"}`,children:y.errors})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.duration>0?`${(y.duration/1e3).toFixed(1)}s`:"0s"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Breakpoints"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:t.breakpoints.filter(r=>r.enabled).length})]})]})})]}),e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("fields"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("fields")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"State Fields"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:l.length})]})}),o.has("fields")&&e.jsx("div",{className:"space-y-1",children:l.length===0?e.jsxs("div",{className:`p-4 text-center ${n?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-2xl mb-2",children:"📭"}),e.jsx("p",{className:"text-sm",children:Object.keys(i||{}).length===0?"No state data":"No fields match your search"})]}):l.map(([r,x])=>e.jsxs("div",{className:`p-3 border-l-4 transition-colors ${n?"border-l-gray-600 hover:bg-gray-700":"border-l-gray-200 hover:bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[e.jsx("span",{className:`text-sm ${d(x)}`,children:_(x)}),e.jsx("span",{className:`font-medium text-sm truncate ${n?"text-white":"text-gray-900"}`,children:r})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded font-mono ${n?"bg-gray-800 text-gray-300":"bg-gray-100 text-gray-600"}`,children:typeof x})]}),e.jsx("div",{className:`mt-1 text-xs font-mono ${d(x)}`,children:m(x)})]},r))})]}),e.jsxs("div",{children:[e.jsx("button",{onClick:()=>w("raw"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("raw")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Raw JSON"})]})}),o.has("raw")&&e.jsx("div",{className:`p-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono p-3 rounded-lg overflow-x-auto ${n?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(i||{},null,2)})})]})]})]})},Ae=()=>{const{graphState:i,darkMode:t,error:n,executionContext:o,selectedAssistant:f,resumeExecution:b,stopExecution:N,setGraphExecutionState:w,addBreakpoint:m,removeBreakpoint:d,startGlobalExecution:_}=V(),[l,y]=g.useState(null),[r,x]=g.useState(1),[h,$]=g.useState({x:0,y:0}),[u,S]=g.useState(!1),[p,C]=g.useState("bottom"),[a,L]=g.useState(!1),[j,Y]=g.useState({x:0,y:0}),[G,K]=g.useState(null),[z,U]=g.useState("input"),[de,xe]=g.useState(null),[ne,R]=g.useState(null),I=g.useRef(null),ae=g.useRef(null),[Q,ie]=g.useState(null),M=(Array.isArray(f?.metadata?.capabilities)?f.metadata.capabilities:Array.isArray(f?.config?.capabilities)?f.config.capabilities:[]).includes("breakpoints"),ge=(s,c)=>{ie({nodeId:s,position:c})},oe=()=>{ie(null)};g.useEffect(()=>{o.isExecuting&&!o.isPaused&&U("logs")},[o.isExecuting,o.isPaused]),g.useEffect(()=>{ae.current&&ae.current.scrollIntoView({behavior:"smooth"})},[o.logs]),g.useEffect(()=>{i?.currentNode&&o.isExecuting&&!o.isPaused&&ee(i.currentNode)},[i?.currentNode,o.isExecuting,o.isPaused]),g.useEffect(()=>{const{selectedThread:s,selectedAssistant:c}=V.getState();if(s&&c){const v=`${s.name} • ${c.name}`;R(v),setTimeout(()=>R(null),3e3)}},[o.threadId,o.assistantId]);const ee=s=>{const c=i?.nodes?.find(q=>q.id===s);if(!c||!I.current)return;const v=I.current.getBoundingClientRect(),E=v.width,T=v.height,X=E/2-c.position.x*r-80,J=T/2-c.position.y*r-50,O={...h},k={x:X,y:J},H=800,A=Date.now(),B=()=>{const q=Date.now()-A,Z=Math.min(q/H,1),D=(W=>W<.5?4*W*W*W:(W-1)*(2*W-2)*(2*W-2)+1)(Z),P={x:O.x+(k.x-O.x)*D,y:O.y+(k.y-O.y)*D};$(P),Z<1&&requestAnimationFrame(B)};requestAnimationFrame(B)},te=()=>{if(i?.nodes?.length===0||!I.current)return;const s=i.nodes.reduce((D,P)=>({minX:Math.min(D.minX,P.position.x),maxX:Math.max(D.maxX,P.position.x+160),minY:Math.min(D.minY,P.position.y),maxY:Math.max(D.maxY,P.position.y+100)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0}),c=50,v=s.maxX-s.minX+c*2,E=s.maxY-s.minY+c*2,T=I.current.clientWidth,X=I.current.clientHeight,J=T/v,O=X/E,k=Math.min(J,O,1),H={x:-(s.minX-c)*k+(T-v*k)/2,y:-(s.minY-c)*k+(X-E*k)/2},A=r,B={...h},q=1e3,Z=Date.now(),se=()=>{const D=Date.now()-Z,P=Math.min(D/q,1),re=(F=>F<.5?4*F*F*F:(F-1)*(2*F-2)*(2*F-2)+1)(P),je=A+(k-A)*re,ve={x:B.x+(H.x-B.x)*re,y:B.y+(H.y-B.y)*re};x(je),$(ve),P<1&&requestAnimationFrame(se)};requestAnimationFrame(se)};if(g.useEffect(()=>{const s=V.getState();s.focusOnNode=ee,s.fitGraphToView=te},[r,h,i?.nodes]),g.useEffect(()=>{const s=I.current;if(!s)return;const c=v=>{v.preventDefault();const E=v.deltaY>0?-.02:.02;x(T=>Math.max(.1,Math.min(3,T+E)))};return s.addEventListener("wheel",c,{passive:!1}),()=>s.removeEventListener("wheel",c)},[]),!i)return e.jsx("div",{className:`flex items-center justify-center h-full ${t?"bg-gray-800 text-white":"bg-white text-gray-900"}`,children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{children:"Loading graph state..."})]})});const he=s=>{y(l===s?null:s),u&&S(!1),U("logs");const c=o.logs.filter(v=>v.nodeId===s);if(c.length>0){const v=c[c.length-1];K(v.id);const E=i.nodes.find(T=>T.id===s)?.data.label||s;R(`📋 Showing ${c.length} logs for ${E}`),setTimeout(()=>R(null),3e3),console.log(`Showing execution logs for node: ${s}`,{totalLogs:c.length,mostRecentLog:v,nodeState:o.currentState})}else{const v=i.nodes.find(E=>E.id===s)?.data.label||s;R(`ℹ️ No execution logs found for ${v}`),setTimeout(()=>R(null),2e3),console.log(`No execution logs found for node: ${s}`),K(null)}},me=s=>{if(!M){R("This agent does not publish server-side breakpoint support."),setTimeout(()=>R(null),3e3);return}o.breakpoints.some(v=>v.nodeId===s)?d(s):m(s)},ue=async(s={})=>{const c=s??{},v=c&&typeof c=="object"&&!Array.isArray(c)?c:{},E={context:{source:"graph"},timestamp:new Date().toISOString(),...v},{selectedThread:T,addMessageToThread:X,createPersistentThread:J}=V.getState();let O=T;if(!O){if(!f?.id){ce.error("Select a live Agentomatic agent before running the graph.");return}try{O=await J(f.id,"Graph Execution")}catch(A){ce.error(A instanceof Error?A.message:"Could not create a durable graph conversation.");return}}const k=JSON.stringify(c,null,2),H={id:`msg-${Date.now()}-graph-user`,role:"user",content:`🔄 **Graph Execution Initiated** +import{u as V,j as e,d as Ne,a as we,V as ce}from"./index-FSSL6O5F.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";import{S as $e}from"./SchemaForm-DyHc2s7z.js";import{O as Se}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const Ce=({nodeId:i,logs:t,darkMode:n,position:o,onClose:f})=>{const b=t.filter(w=>w.nodeId===i);if(b.length===0)return null;const N=b[b.length-1];return e.jsx("div",{className:"fixed z-50 pointer-events-none",style:{left:o.x+20,top:o.y-10,maxWidth:"400px"},children:e.jsxs("div",{className:`rounded-lg shadow-xl border p-4 pointer-events-auto ${n?"bg-gray-800 border-gray-600 text-white":"bg-white border-gray-200 text-gray-900"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-semibold text-sm",children:"Node Execution Details"}),e.jsx("button",{onClick:f,className:`text-xs px-2 py-1 rounded ${n?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,children:"✕"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Latest Execution"}),e.jsx("div",{className:"text-sm",children:N.message}),e.jsx("div",{className:`text-xs mt-1 ${n?"text-gray-500":"text-gray-400"}`,children:N.timestamp.toLocaleString()})]}),N.data?.intermediate_results&&e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium mb-2 ${n?"text-gray-400":"text-gray-500"}`,children:"Results Preview"}),e.jsx("div",{className:`text-xs p-2 rounded font-mono ${n?"bg-gray-900 text-gray-300":"bg-gray-50 text-gray-700"}`,children:Object.keys(N.data.intermediate_results).length>0?e.jsx("div",{children:Object.entries(N.data.intermediate_results).map(([w,m])=>e.jsxs("div",{className:"mb-1",children:[e.jsxs("span",{className:"font-semibold",children:[w,":"]})," ",typeof m=="object"&&m!==null&&"response"in m?`"${m.response?.substring(0,50)}..."`:JSON.stringify(m).substring(0,50)+"..."]},w))}):"No results available"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-gray-200 dark:border-gray-600",children:[e.jsxs("span",{className:`text-xs ${n?"text-gray-400":"text-gray-500"}`,children:[b.length," total execution",b.length!==1?"s":""]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:"Click node to view all logs"})]})]})]})})},Le=({node:i,isSelected:t,isActive:n,isHighlighted:o,hasBreakpoint:f,onClick:b,onBreakpointToggle:N,canManageBreakpoints:w,logs:m,onShowLogTooltip:d,onHideLogTooltip:_})=>{const{darkMode:l}=V(),y=m.filter(C=>C.nodeId===i.id),r=y.length>0,x=C=>{if(r){const a=C.currentTarget.getBoundingClientRect();d(i.id,{x:a.right,y:a.top})}},h=()=>{r&&_()},u=((C,a)=>{const L={start:{bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",text:l?"#bfdbfe":"#1e40af",indicator:"#3b82f6",icon:"🚀"},end:{bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",text:l?"#fecaca":"#991b1b",indicator:"#ef4444",icon:"🏁"},agent:{bg:l?"#581c87":"#f3e8ff",border:"#8b5cf6",text:l?"#ddd6fe":"#6b21a8",indicator:"#8b5cf6",icon:"🤖"},tool:{bg:l?"#14532d":"#dcfce7",border:"#10b981",text:l?"#bbf7d0":"#065f46",indicator:"#10b981",icon:"🔧"},human:{bg:l?"#92400e":"#fef3c7",border:"#f59e0b",text:l?"#fde68a":"#92400e",indicator:"#f59e0b",icon:"👤"},condition:{bg:l?"#7c2d12":"#fed7aa",border:"#ea580c",text:l?"#fed7aa":"#9a3412",indicator:"#ea580c",icon:"🔀"},retrieval:{bg:l?"#164e63":"#cffafe",border:"#0891b2",text:l?"#a5f3fc":"#164e63",indicator:"#0891b2",icon:"🔍"},processing:{bg:l?"#4c1d95":"#ede9fe",border:"#7c3aed",text:l?"#c4b5fd":"#4c1d95",indicator:"#7c3aed",icon:"⚙️"},generation:{bg:l?"#be185d":"#fce7f3",border:"#ec4899",text:l?"#fbcfe8":"#be185d",indicator:"#ec4899",icon:"✨"},validation:{bg:l?"#365314":"#ecfccb",border:"#65a30d",text:l?"#d9f99d":"#365314",indicator:"#65a30d",icon:"✅"},default:{bg:l?"#374151":"#f9fafb",border:l?"#6b7280":"#d1d5db",text:l?"#e5e7eb":"#374151",indicator:l?"#9ca3af":"#6b7280",icon:"📦"}},j=L[C]||L.default;return a==="running"?{...j,bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",indicator:"#3b82f6"}:a==="completed"?{...j,bg:l?"#14532d":"#dcfce7",border:"#10b981",indicator:"#10b981"}:a==="error"?{...j,bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",indicator:"#ef4444"}:a==="paused"?{...j,bg:l?"#92400e":"#fef3c7",border:"#f59e0b",indicator:"#f59e0b"}:j})(i.type,i.data.status),S=160,p=100;return e.jsxs("g",{transform:`translate(${i.position.x}, ${i.position.y})`,className:"cursor-pointer graph-node-group",onMouseEnter:x,onMouseLeave:h,children:[e.jsxs("defs",{children:[e.jsx("filter",{id:`shadow-${i.id}`,x:"-20%",y:"-20%",width:"140%",height:"140%",children:e.jsx("feDropShadow",{dx:"0",dy:"3",stdDeviation:"4",floodColor:l?"rgba(0,0,0,0.5)":"rgba(0,0,0,0.15)",floodOpacity:"1"})}),e.jsxs("linearGradient",{id:`gradient-${i.id}`,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:u.bg,stopOpacity:"1"}),e.jsx("stop",{offset:"100%",stopColor:u.bg,stopOpacity:"0.8"})]})]}),w&&e.jsxs("g",{className:"cursor-pointer",onClick:C=>{C.stopPropagation(),N(i.id)},children:[e.jsx("title",{children:f?"Remove breakpoint":"Add breakpoint"}),e.jsx("circle",{cx:-8,cy:8,r:7,fill:f?"#ef4444":l?"#374151":"#ffffff",stroke:f?"#fecaca":"#9ca3af",strokeWidth:2}),!f&&e.jsx("path",{d:"M-11 8h6M-8 5v6",stroke:"#6b7280",strokeWidth:1.5,strokeLinecap:"round"})]}),r&&e.jsx("circle",{cx:S-8,cy:8,r:8,fill:l?"#3b82f6":"#2563eb",stroke:l?"#1f2937":"#ffffff",strokeWidth:2,className:"cursor-pointer animate-pulse"}),r&&e.jsx("text",{x:S-8,y:8,textAnchor:"middle",dominantBaseline:"central",fontSize:"10",fill:"white",className:"pointer-events-none font-bold",children:"ℹ️"}),n&&e.jsx("rect",{width:S+12,height:p+12,x:-6,y:-6,rx:20,fill:u.indicator,opacity:"0.2",className:"animate-pulse"}),o&&e.jsx("rect",{width:S+16,height:p+16,x:-8,y:-8,rx:22,fill:"none",stroke:"#f59e0b",strokeWidth:3,strokeDasharray:"12,6",className:"animate-pulse",opacity:"0.8"}),e.jsx("rect",{width:S,height:p,rx:16,fill:`url(#gradient-${i.id})`,stroke:u.border,strokeWidth:t?3:o?2.5:2,filter:`url(#shadow-${i.id})`,onClick:()=>b(i.id),className:o?"animate-pulse":""}),e.jsx("foreignObject",{x:16,y:16,width:S-32,height:p-32,style:{pointerEvents:"none"},children:e.jsxs("div",{className:"h-full flex flex-col justify-between",style:{pointerEvents:"none"},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:"text-lg",children:u.icon}),e.jsx("span",{className:"font-semibold text-sm truncate",style:{color:u.text},children:i.data.label})]}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${i.data.status==="running"?"animate-pulse":""}`,style:{backgroundColor:u.indicator,boxShadow:i.data.status==="running"?`0 0 8px ${u.indicator}`:"none"}}),r&&e.jsx("div",{className:`text-xs px-1 py-0.5 rounded-full font-bold ${l?"bg-blue-600 text-white":"bg-blue-100 text-blue-700"}`,title:`${y.length} execution log${y.length!==1?"s":""}`,children:y.length})]})]}),e.jsx("div",{className:"text-xs px-2 py-1 rounded-full self-start font-medium",style:{backgroundColor:u.indicator+"20",color:u.text},children:i.type}),i.data.description&&e.jsx("div",{className:"text-xs mt-1 line-clamp-2 opacity-80 leading-relaxed",style:{color:u.text},children:i.data.description}),e.jsx("div",{className:"text-xs mt-1 opacity-60 font-medium",style:{color:u.text},children:r?`Click to view ${y.length} logs • Hover for details`:"Click to view • Right-click for breakpoint"})]})})]})},Ee=({edge:i,nodes:t,isActive:n,isInExecutionPath:o})=>{const{darkMode:f}=V(),b=t.find(S=>S.id===i.source),N=t.find(S=>S.id===i.target);if(!b||!N)return null;const w=160,m=100,d=b.position.x+w,_=b.position.y+m/2,l=N.position.x,y=N.position.y+m/2,r=(d+l)/2,x=`M ${d} ${_} C ${r} ${_}, ${r} ${y}, ${l} ${y}`,$=n?"#3b82f6":o?"#10b981":f?"#6b7280":"#9ca3af",u=n?3:o?2.5:2;return e.jsxs("g",{children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrowhead-${i.id}`,markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:$})})}),e.jsx("path",{d:x,fill:"none",stroke:f?"rgba(0,0,0,0.3)":"rgba(0,0,0,0.1)",strokeWidth:u+1,transform:"translate(1, 2)"}),e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u,className:`transition-all duration-300 ${n?"animate-pulse":""} ${o?"execution-path-animated":""}`,style:{filter:n?`drop-shadow(0 0 6px ${$})`:"none"},markerEnd:`url(#arrowhead-${i.id})`}),n&&e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u+4,opacity:"0.3",className:"animate-pulse"})]})},_e=({currentState:i,onStateChange:t,onStartExecution:n,darkMode:o})=>{const{selectedAgent:f,agentSchemas:b,schemasLoading:N,fetchAgentSchemas:w}=V(),m=f?.id,d=m?b[m]:void 0,[_,l]=g.useState({});g.useEffect(()=>{m&&w(m)},[m,w]),g.useEffect(()=>{const x=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object"),h=x?Ne(d?.input_schema):we(d?.input_schema),$=d?.input_schema?.properties,u=$&&typeof $=="object"?Object.fromEntries(Object.entries(i||{}).filter(([C])=>Object.prototype.hasOwnProperty.call($,C))):{};if(x){const C=i?.__root__??h;l(C),t({__root__:C});return}const p={...{...h&&typeof h=="object"&&!Array.isArray(h)?h:{},...u}};delete p.intermediate_results,delete p.execution_history,delete p.error_log,delete p.current_node,l(p),t(p)},[d?.input_schema,m]);const y=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x)},r=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x),n(x)};return e.jsxs("div",{className:`p-4 border-b space-y-3 ${o?"border-gray-600":"border-gray-200"}`,children:[N&&!d&&e.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:"Loading agent schema…"}),e.jsx($e,{schema:d?.input_schema,value:_,onChange:y,onSubmit:r,submitLabel:"Submit & Run",darkMode:o,disabled:!m,schemaSource:d?.schema_source?.input},m||"no-agent"),e.jsx(Se,{schema:d?.output_schema,source:d?.schema_source?.output,darkMode:o})]})},Te=({logs:i,darkMode:t,onLogHover:n,onLogSelect:o,selectedLogId:f,selectedNodeId:b,onClearNodeFilter:N})=>{const w=g.useRef(null),m=g.useRef(null),[d,_]=g.useState(new Set),[l,y]=g.useState(""),[r,x]=g.useState("all");g.useEffect(()=>{w.current?.scrollIntoView({behavior:"smooth"})},[i]),g.useEffect(()=>{f&&m.current&&m.current.scrollIntoView({behavior:"smooth",block:"center"})},[f]);const h=a=>{_(L=>{const j=new Set(L);return j.has(a)?j.delete(a):j.add(a),j})},$=i.filter(a=>{const L=l===""||a.message.toLowerCase().includes(l.toLowerCase())||a.nodeName.toLowerCase().includes(l.toLowerCase()),j=r==="all"||a.type===r,Y=!b||a.nodeId===b;return L&&j&&Y}),u=a=>{switch(a){case"input":return"📥";case"output":return"📤";case"error":return"❌";case"info":return"ℹ️";case"debug":return"🐛";default:return"📝"}},S=a=>{switch(a){case"input":return t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800";case"output":return t?"bg-green-900 text-green-300":"bg-green-100 text-green-800";case"error":return t?"bg-red-900 text-red-300":"bg-red-100 text-red-800";case"info":return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800";case"debug":return t?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-800";default:return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800"}},p=(a,L=!1)=>{if(!a)return null;if(typeof a=="string")return L?a:a.length>100?a.substring(0,100)+"...":a;const j=JSON.stringify(a,null,L?2:0);return!L&&j.length>200?j.substring(0,200)+"...":j},C=a=>{const L=d.has(a.id),j=f===a.id;return e.jsxs("div",{ref:j?m:void 0,className:`rounded-lg border transition-all duration-300 ${j?`log-entry-selected ${t?"bg-blue-900/30 border-blue-500 shadow-lg":"bg-blue-50 border-blue-300 shadow-lg"}`:`${t?"bg-gray-700 border-gray-600 hover:bg-gray-650":"bg-white border-gray-200 hover:bg-gray-50"} hover:log-entry-hover`}`,onMouseEnter:()=>n(a.nodeId),onMouseLeave:()=>n(null),children:[e.jsxs("div",{className:"p-4 cursor-pointer",onClick:()=>{o(j?null:a.id),h(a.id)},children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${S(a.type)}`,children:e.jsx("span",{className:"text-sm",children:u(a.type)})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:`font-semibold text-sm ${t?"text-white":"text-gray-900"}`,children:a.nodeName}),e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${S(a.type)}`,children:a.type.toUpperCase()}),j&&e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${t?"bg-yellow-900 text-yellow-300":"bg-yellow-100 text-yellow-700"}`,children:"FOCUSED"})]}),e.jsxs("div",{className:`text-xs mt-1 ${t?"text-gray-400":"text-gray-500"}`,children:[a.timestamp.toLocaleTimeString()," • Node ID: ",a.nodeId]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[a.duration&&e.jsxs("div",{className:`px-3 py-1 rounded-lg text-xs font-medium ${t?"bg-gray-600 text-gray-300":"bg-gray-100 text-gray-600"}`,children:["⏱️ ",a.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform duration-200 ${L?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]}),e.jsx("div",{className:`text-sm mb-3 p-3 rounded-lg ${t?"bg-gray-800 text-gray-300":"bg-gray-50 text-gray-700"}`,children:e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx("span",{className:"text-lg",children:"💬"}),e.jsx("span",{children:a.message})]})}),a.data?.intermediate_results&&!L&&e.jsxs("div",{className:`p-3 rounded-lg border ${t?"bg-gray-800 border-gray-600":"bg-gray-50 border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Data Preview"}),e.jsx("span",{className:`text-xs ${t?"text-blue-400":"text-blue-600"}`,children:"Click to expand"})]}),e.jsx("div",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-800"}`,children:p(a.data,!1)})]})]}),L&&a.data&&e.jsx("div",{className:`border-t ${t?"border-gray-600":"border-gray-200"}`,children:e.jsxs("div",{className:"p-4 space-y-4",children:[a.data.performance&&e.jsxs("div",{className:`p-3 rounded-lg performance-card ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"⚡"}),"Performance Metrics"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsxs("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:[a.data.performance.duration_ms,"ms"]})]}),e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Node Type"}),e.jsx("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:a.data.performance.node_type})]})]})]}),a.data.state_updates&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔄"}),"State Updates"]}),e.jsx("div",{className:"space-y-2",children:Object.entries(a.data.state_updates).map(([Y,G])=>e.jsxs("div",{className:`p-2 rounded border-l-4 border-blue-500 state-update-indicator ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${t?"text-gray-300":"text-gray-700"}`,children:Y}),e.jsx("div",{className:`text-xs font-mono mt-1 ${t?"text-gray-400":"text-gray-600"}`,children:typeof G=="object"?JSON.stringify(G,null,2):String(G)})]},Y))})]}),a.data.output&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"📤"}),"Output Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.output,null,2)})]}),a.data.current_state&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔍"}),"Current State"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.current_state,null,2)})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🗂️"}),"Raw Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data,null,2)})]})]})})]},a.id)};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${t?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:`text-sm font-semibold flex items-center ${t?"text-white":"text-gray-900"}`,children:["Live Execution Logs",b&&e.jsxs("span",{className:`ml-3 px-2 py-1 rounded text-xs font-medium flex items-center ${t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800"}`,children:["Filtered: ",b,e.jsx("button",{onClick:N,className:"ml-2 hover:text-white hover:bg-blue-800 rounded-full w-4 h-4 flex items-center justify-center transition-colors",title:"Clear filter",children:"×"})]})]}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[$.length," / ",i.length]})})]}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("input",{type:"text",placeholder:"Search logs...",value:l,onChange:a=>y(a.target.value),className:`flex-1 px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`}),e.jsxs("select",{value:r,onChange:a=>x(a.target.value),className:`px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,children:[e.jsx("option",{value:"all",children:"All Types"}),e.jsx("option",{value:"input",children:"Input"}),e.jsx("option",{value:"output",children:"Output"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"info",children:"Info"}),e.jsx("option",{value:"debug",children:"Debug"})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-3 custom-scrollbar",children:[$.length===0?e.jsxs("div",{className:`text-center py-12 ${t?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-4xl mb-4",children:"📋"}),e.jsx("p",{className:"text-lg font-medium mb-2",children:i.length===0?"No execution logs yet":"No logs match your filter"}),e.jsx("p",{className:"text-sm",children:i.length===0?"Start graph execution to see live logs":"Try adjusting your search or filter"})]}):$.map(a=>C(a)),e.jsx("div",{ref:w})]})]})},Oe=({currentState:i,executionContext:t,darkMode:n})=>{const[o,f]=g.useState(new Set(["overview"])),[b,N]=g.useState(""),w=r=>{f(x=>{const h=new Set(x);return h.has(r)?h.delete(r):h.add(r),h})},m=r=>r===null?"null":r===void 0?"undefined":typeof r=="boolean"||typeof r=="number"?r.toString():typeof r=="string"?r.length>100?`${r.substring(0,100)}...`:r:Array.isArray(r)?`Array(${r.length})`:typeof r=="object"?`Object(${Object.keys(r).length} keys)`:String(r),d=r=>r==null?n?"text-gray-500":"text-gray-400":typeof r=="boolean"?n?"text-purple-400":"text-purple-600":typeof r=="number"?n?"text-blue-400":"text-blue-600":typeof r=="string"?n?"text-green-400":"text-green-600":Array.isArray(r)?n?"text-orange-400":"text-orange-600":typeof r=="object"?n?"text-cyan-400":"text-cyan-600":n?"text-gray-300":"text-gray-700",_=r=>r==null?"∅":typeof r=="boolean"?r?"✓":"✗":typeof r=="number"?"#":typeof r=="string"?'"':Array.isArray(r)?"[]":typeof r=="object"?"{}":"?",l=Object.entries(i||{}).filter(([r,x])=>b?r.toLowerCase().includes(b.toLowerCase())||String(x).toLowerCase().includes(b.toLowerCase()):!0),y={totalSteps:t.logs.length,errors:t.logs.filter(r=>r.type==="error").length,duration:t.startTime?(t.endTime||new Date).getTime()-t.startTime.getTime():0,status:t.isExecuting?t.isPaused?"Paused":"Running":"Idle"};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:`text-sm font-semibold ${n?"text-white":"text-gray-900"}`,children:"Current State"}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[Object.keys(i||{}).length," fields"]})})]}),e.jsx("input",{type:"text",placeholder:"Search state fields...",value:b,onChange:r=>N(r.target.value),className:`w-full px-3 py-2 text-xs border rounded-lg ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("overview"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("overview")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Execution Overview"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${y.status==="Running"?"bg-blue-100 text-blue-700":y.status==="Paused"?"bg-orange-100 text-orange-700":"bg-gray-100 text-gray-700"}`,children:y.status})]})}),o.has("overview")&&e.jsx("div",{className:`px-4 pb-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Total Steps"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.totalSteps})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Errors"}),e.jsx("div",{className:`text-lg font-bold ${y.errors>0?"text-red-500":n?"text-white":"text-gray-900"}`,children:y.errors})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.duration>0?`${(y.duration/1e3).toFixed(1)}s`:"0s"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Breakpoints"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:t.breakpoints.filter(r=>r.enabled).length})]})]})})]}),e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("fields"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("fields")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"State Fields"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:l.length})]})}),o.has("fields")&&e.jsx("div",{className:"space-y-1",children:l.length===0?e.jsxs("div",{className:`p-4 text-center ${n?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-2xl mb-2",children:"📭"}),e.jsx("p",{className:"text-sm",children:Object.keys(i||{}).length===0?"No state data":"No fields match your search"})]}):l.map(([r,x])=>e.jsxs("div",{className:`p-3 border-l-4 transition-colors ${n?"border-l-gray-600 hover:bg-gray-700":"border-l-gray-200 hover:bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[e.jsx("span",{className:`text-sm ${d(x)}`,children:_(x)}),e.jsx("span",{className:`font-medium text-sm truncate ${n?"text-white":"text-gray-900"}`,children:r})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded font-mono ${n?"bg-gray-800 text-gray-300":"bg-gray-100 text-gray-600"}`,children:typeof x})]}),e.jsx("div",{className:`mt-1 text-xs font-mono ${d(x)}`,children:m(x)})]},r))})]}),e.jsxs("div",{children:[e.jsx("button",{onClick:()=>w("raw"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("raw")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Raw JSON"})]})}),o.has("raw")&&e.jsx("div",{className:`p-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono p-3 rounded-lg overflow-x-auto ${n?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(i||{},null,2)})})]})]})]})},Ae=()=>{const{graphState:i,darkMode:t,error:n,executionContext:o,selectedAssistant:f,resumeExecution:b,stopExecution:N,setGraphExecutionState:w,addBreakpoint:m,removeBreakpoint:d,startGlobalExecution:_}=V(),[l,y]=g.useState(null),[r,x]=g.useState(1),[h,$]=g.useState({x:0,y:0}),[u,S]=g.useState(!1),[p,C]=g.useState("bottom"),[a,L]=g.useState(!1),[j,Y]=g.useState({x:0,y:0}),[G,K]=g.useState(null),[z,U]=g.useState("input"),[de,xe]=g.useState(null),[ne,R]=g.useState(null),I=g.useRef(null),ae=g.useRef(null),[Q,ie]=g.useState(null),M=(Array.isArray(f?.metadata?.capabilities)?f.metadata.capabilities:Array.isArray(f?.config?.capabilities)?f.config.capabilities:[]).includes("breakpoints"),ge=(s,c)=>{ie({nodeId:s,position:c})},oe=()=>{ie(null)};g.useEffect(()=>{o.isExecuting&&!o.isPaused&&U("logs")},[o.isExecuting,o.isPaused]),g.useEffect(()=>{ae.current&&ae.current.scrollIntoView({behavior:"smooth"})},[o.logs]),g.useEffect(()=>{i?.currentNode&&o.isExecuting&&!o.isPaused&&ee(i.currentNode)},[i?.currentNode,o.isExecuting,o.isPaused]),g.useEffect(()=>{const{selectedThread:s,selectedAssistant:c}=V.getState();if(s&&c){const v=`${s.name} • ${c.name}`;R(v),setTimeout(()=>R(null),3e3)}},[o.threadId,o.assistantId]);const ee=s=>{const c=i?.nodes?.find(q=>q.id===s);if(!c||!I.current)return;const v=I.current.getBoundingClientRect(),E=v.width,T=v.height,X=E/2-c.position.x*r-80,J=T/2-c.position.y*r-50,O={...h},k={x:X,y:J},H=800,A=Date.now(),B=()=>{const q=Date.now()-A,Z=Math.min(q/H,1),D=(W=>W<.5?4*W*W*W:(W-1)*(2*W-2)*(2*W-2)+1)(Z),P={x:O.x+(k.x-O.x)*D,y:O.y+(k.y-O.y)*D};$(P),Z<1&&requestAnimationFrame(B)};requestAnimationFrame(B)},te=()=>{if(i?.nodes?.length===0||!I.current)return;const s=i.nodes.reduce((D,P)=>({minX:Math.min(D.minX,P.position.x),maxX:Math.max(D.maxX,P.position.x+160),minY:Math.min(D.minY,P.position.y),maxY:Math.max(D.maxY,P.position.y+100)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0}),c=50,v=s.maxX-s.minX+c*2,E=s.maxY-s.minY+c*2,T=I.current.clientWidth,X=I.current.clientHeight,J=T/v,O=X/E,k=Math.min(J,O,1),H={x:-(s.minX-c)*k+(T-v*k)/2,y:-(s.minY-c)*k+(X-E*k)/2},A=r,B={...h},q=1e3,Z=Date.now(),se=()=>{const D=Date.now()-Z,P=Math.min(D/q,1),re=(F=>F<.5?4*F*F*F:(F-1)*(2*F-2)*(2*F-2)+1)(P),je=A+(k-A)*re,ve={x:B.x+(H.x-B.x)*re,y:B.y+(H.y-B.y)*re};x(je),$(ve),P<1&&requestAnimationFrame(se)};requestAnimationFrame(se)};if(g.useEffect(()=>{const s=V.getState();s.focusOnNode=ee,s.fitGraphToView=te},[r,h,i?.nodes]),g.useEffect(()=>{const s=I.current;if(!s)return;const c=v=>{v.preventDefault();const E=v.deltaY>0?-.02:.02;x(T=>Math.max(.1,Math.min(3,T+E)))};return s.addEventListener("wheel",c,{passive:!1}),()=>s.removeEventListener("wheel",c)},[]),!i)return e.jsx("div",{className:`flex items-center justify-center h-full ${t?"bg-gray-800 text-white":"bg-white text-gray-900"}`,children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{children:"Loading graph state..."})]})});const he=s=>{y(l===s?null:s),u&&S(!1),U("logs");const c=o.logs.filter(v=>v.nodeId===s);if(c.length>0){const v=c[c.length-1];K(v.id);const E=i.nodes.find(T=>T.id===s)?.data.label||s;R(`📋 Showing ${c.length} logs for ${E}`),setTimeout(()=>R(null),3e3),console.log(`Showing execution logs for node: ${s}`,{totalLogs:c.length,mostRecentLog:v,nodeState:o.currentState})}else{const v=i.nodes.find(E=>E.id===s)?.data.label||s;R(`ℹ️ No execution logs found for ${v}`),setTimeout(()=>R(null),2e3),console.log(`No execution logs found for node: ${s}`),K(null)}},me=s=>{if(!M){R("This agent does not publish server-side breakpoint support."),setTimeout(()=>R(null),3e3);return}o.breakpoints.some(v=>v.nodeId===s)?d(s):m(s)},ue=async(s={})=>{const c=s??{},v=c&&typeof c=="object"&&!Array.isArray(c)?c:{},E={context:{source:"graph"},timestamp:new Date().toISOString(),...v},{selectedThread:T,addMessageToThread:X,createPersistentThread:J}=V.getState();let O=T;if(!O){if(!f?.id){ce.error("Select a live Agentomatic agent before running the graph.");return}try{O=await J(f.id,"Graph Execution")}catch(A){ce.error(A instanceof Error?A.message:"Could not create a durable graph conversation.");return}}const k=JSON.stringify(c,null,2),H={id:`msg-${Date.now()}-graph-user`,role:"user",content:`🔄 **Graph Execution Initiated** \`\`\`json ${k} \`\`\``,timestamp:new Date};X(O.id,H),_("graph",E,c)},be=s=>{s.button===0&&(L(!0),Y({x:s.clientX-h.x,y:s.clientY-h.y}))},pe=s=>{a&&$({x:s.clientX-j.x,y:s.clientY-j.y})},le=()=>{L(!1)},fe=()=>{x(1),$({x:0,y:0})},ye=()=>{te()};return e.jsxs("div",{className:"h-full w-full flex flex-col",children:[e.jsx("div",{className:`flex-shrink-0 border-b px-3 py-2 sm:px-4 toolbar ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center space-x-2 sm:space-x-4",children:[e.jsxs("h2",{className:`flex items-center text-base font-semibold sm:text-lg ${t?"text-white":"text-gray-900"}`,children:[e.jsx("svg",{className:"w-5 h-5 mr-2 text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"Graph Execution"]}),e.jsxs("div",{className:`hidden items-center space-x-2 text-sm md:flex ${t?"text-gray-300":"text-gray-600"}`,children:[e.jsxs("span",{className:`px-2 py-1 rounded status-indicator ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:["Current: ",i?.currentNode||"None"]}),e.jsx("span",{className:`px-2 py-1 rounded status-indicator ${o.isExecuting?o.isPaused?"bg-orange-100 text-orange-700 paused":"bg-blue-100 text-blue-700 active":t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:o.isExecuting?o.isPaused?"Paused":"Running":"Idle"}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:["Logs: ",o.logs.length]}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:["Breakpoints: ",o.breakpoints.filter(s=>s.enabled).length]})]})]}),e.jsxs("div",{className:"flex w-full flex-wrap items-center gap-1.5 sm:w-auto sm:gap-2",children:[e.jsx("div",{className:`flex items-center space-x-1 rounded-lg p-1 ${t?"bg-gray-700":"bg-gray-100"}`,children:o.isExecuting?e.jsx("button",{onClick:N,className:`px-3 py-1 text-xs font-medium rounded transition-colors ${t?"text-red-400 hover:bg-gray-600":"text-red-600 hover:bg-white"}`,title:"Stop receiving this live stream",children:"⏹️ Stop stream"}):e.jsx("button",{onClick:()=>{S(!1),U("input")},className:`px-3 py-1 text-xs font-medium rounded transition-colors ${t?"text-green-400 hover:bg-gray-600":"text-green-600 hover:bg-white"}`,title:"Start Execution",children:"✎ Configure input"})}),e.jsxs("div",{className:`flex items-center space-x-1 rounded-lg p-1 ${t?"bg-gray-700":"bg-gray-100"}`,children:[e.jsx("button",{onClick:fe,className:`px-3 py-1 text-xs font-medium rounded transition-colors ${t?"text-gray-300 hover:bg-gray-600":"text-gray-700 hover:bg-white"}`,title:"Reset View",children:"Reset"}),e.jsx("button",{onClick:ye,className:`px-3 py-1 text-xs font-medium rounded transition-colors ${t?"text-gray-300 hover:bg-gray-600":"text-gray-700 hover:bg-white"}`,title:"Fit to Screen",children:"Fit"}),i?.currentNode&&e.jsx("button",{onClick:()=>ee(i.currentNode),className:`px-3 py-1 text-xs font-medium rounded transition-colors ${t?"text-blue-400 hover:bg-gray-600":"text-blue-600 hover:bg-white"}`,title:"Focus on Current Node",children:"Focus"}),e.jsxs("span",{className:`px-2 py-1 text-xs ${t?"text-gray-400":"text-gray-600"}`,children:[Math.round(r*100),"%"]})]}),e.jsxs("div",{className:`flex items-center space-x-1 rounded-lg p-1 ${t?"bg-gray-700":"bg-gray-100"}`,children:[e.jsx("button",{onClick:()=>C("right"),className:`px-3 py-1 text-xs font-medium rounded transition-colors ${p==="right"?t?"bg-blue-600 text-white shadow-sm":"bg-white text-blue-600 shadow-sm":t?"text-gray-300 hover:bg-gray-600":"text-gray-700 hover:bg-white"}`,title:"Right Sidebar",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 3v18m0 0l-3-3m3 3l3-3M21 3H9"})})}),e.jsx("button",{onClick:()=>C("bottom"),className:`px-3 py-1 text-xs font-medium rounded transition-colors ${p==="bottom"?t?"bg-blue-600 text-white shadow-sm":"bg-white text-blue-600 shadow-sm":t?"text-gray-300 hover:bg-gray-600":"text-gray-700 hover:bg-white"}`,title:"Bottom Panel",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 15v6h18v-6M3 9l3 3 3-3m6 0l3 3 3-3"})})})]}),e.jsx("button",{onClick:()=>S(!u),className:`p-2 rounded-lg transition-colors ${t?"text-gray-400 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:u?"Show Controls":"Hide Controls",children:e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${p==="right"?u?"rotate-180":"":u?"rotate-90":"-rotate-90"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]})}),e.jsxs("div",{className:`flex-1 flex ${p==="bottom"?"flex-col":"flex-row"} min-h-0 overflow-hidden`,style:{height:"calc(100vh - 60px)"},children:[e.jsx("div",{className:"flex-1 relative min-h-0 overflow-hidden",children:e.jsxs("div",{className:`h-full relative overflow-hidden cursor-grab active:cursor-grabbing graph-canvas ${t?"bg-gray-900":"bg-gray-50"}`,onMouseDown:be,onMouseMove:pe,onMouseUp:le,onMouseLeave:le,ref:I,style:{cursor:a?"grabbing":"grab"},children:[n&&e.jsxs("div",{className:`absolute left-4 right-4 top-4 z-20 rounded-lg border p-3 text-sm shadow-lg ${t?"border-amber-700 bg-amber-950/95 text-amber-100":"border-amber-300 bg-amber-50/95 text-amber-950"}`,role:"alert",children:[e.jsx("span",{className:"font-semibold",children:"Live topology unavailable."})," ",n," The selected agent can still be invoked from the input panel."]}),e.jsxs("svg",{className:"w-full h-full graph-svg",viewBox:`${-h.x/r} ${-h.y/r} ${(I.current?.clientWidth||800)/r} ${(I.current?.clientHeight||600)/r}`,preserveAspectRatio:"xMidYMid meet",children:[e.jsx("rect",{width:"100%",height:"100%",fill:t?"#1f2937":"#f9fafb"}),i.edges.map(s=>e.jsx(Ee,{edge:s,nodes:i.nodes,isActive:s.source===i?.currentNode||s.target===i?.currentNode,isInExecutionPath:i.executionPath.includes(s.source)&&i.executionPath.includes(s.target)},s.id)),i.nodes.map(s=>e.jsx(Le,{node:s,isSelected:l===s.id,isActive:s.id===i?.currentNode,isHighlighted:de===s.id,hasBreakpoint:o.breakpoints.some(c=>c.nodeId===s.id&&c.enabled),onClick:he,onBreakpointToggle:me,canManageBreakpoints:M,logs:o.logs,onShowLogTooltip:ge,onHideLogTooltip:oe},s.id))]}),o.logs.filter(s=>s.type==="output"&&s.duration).map(s=>{const c=i.nodes.find(E=>E.id===s.nodeId);if(!c)return null;const v=s.duration>=1e3?`${(s.duration/1e3).toFixed(1)}s`:`${Math.round(s.duration)}ms`;return e.jsxs("div",{className:`absolute text-xs font-mono px-1.5 py-0.5 rounded-full pointer-events-none ${t?"bg-emerald-900/80 text-emerald-300 border border-emerald-700":"bg-emerald-50 text-emerald-700 border border-emerald-200"}`,style:{left:`${(c.position.x+80)*r+h.x-20}px`,top:`${(c.position.y+105)*r+h.y}px`,transform:`scale(${Math.min(r,1)})`,transformOrigin:"center top"},children:["⏱ ",v]},`duration-${s.id}`)}),e.jsx("div",{className:`absolute bottom-4 left-4 rounded-lg shadow-lg border p-3 backdrop-blur-sm ${t?"bg-gray-800/90 border-gray-600":"bg-white/90 border-gray-200"}`,children:e.jsxs("div",{className:`text-xs space-y-1 ${t?"text-gray-300":"text-gray-600"}`,children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("span",{className:`w-4 h-4 rounded mr-2 flex items-center justify-center text-xs ${t?"bg-gray-700":"bg-gray-100"}`,children:"🖱️"}),"Drag to pan"]}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("span",{className:`w-4 h-4 rounded mr-2 flex items-center justify-center text-xs ${t?"bg-gray-700":"bg-gray-100"}`,children:"⚡"}),"Scroll to zoom"]}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("span",{className:`w-4 h-4 rounded mr-2 flex items-center justify-center text-xs ${t?"bg-gray-700":"bg-gray-100"}`,children:"🔴"}),M?"Click the node marker to toggle a breakpoint":"Selected agent does not expose breakpoints"]})]})}),e.jsxs("div",{className:`absolute bottom-4 right-4 zoom-controls flex items-center rounded-lg shadow-lg ${t?"bg-gray-800/90 border border-gray-600":"bg-white/90 border border-gray-200"}`,children:[e.jsx("button",{onClick:()=>x(s=>Math.min(s*1.25,3)),className:`p-2 ${t?"text-gray-300 hover:bg-gray-700":"text-gray-700 hover:bg-gray-100"}`,title:"Zoom In",children:"+"}),e.jsxs("span",{className:`text-xs font-medium px-1 w-12 text-center ${t?"text-gray-400":"text-gray-500"}`,children:[Math.round(r*100),"%"]}),e.jsx("button",{onClick:()=>x(s=>Math.max(s/1.25,.2)),className:`p-2 ${t?"text-gray-300 hover:bg-gray-700":"text-gray-700 hover:bg-gray-100"}`,title:"Zoom Out",children:"−"}),e.jsx("div",{className:`w-px h-5 ${t?"bg-gray-600":"bg-gray-300"}`}),e.jsx("button",{onClick:te,className:`p-2 text-sm ${t?"text-gray-300 hover:bg-gray-700":"text-gray-700 hover:bg-gray-100"}`,title:"Fit to View",children:"⊡"})]}),ne&&e.jsx("div",{className:`absolute top-4 left-1/2 transform -translate-x-1/2 rounded-lg shadow-lg border p-3 backdrop-blur-sm context-switch-notification ${t?"bg-green-900/90 border-green-600":"bg-green-50/90 border-green-200"}`,children:e.jsxs("div",{className:`flex items-center space-x-2 ${t?"text-green-300":"text-green-700"}`,children:[e.jsx("span",{className:"text-lg",children:"🔄"}),e.jsx("span",{className:"text-sm font-medium",children:ne})]})}),e.jsx("div",{className:`absolute top-4 right-4 rounded-lg shadow-lg border p-3 backdrop-blur-sm ${t?"bg-gray-800/90 border-gray-600":"bg-white/90 border-gray-200"}`,children:e.jsxs("div",{className:`text-xs space-y-1 ${t?"text-gray-300":"text-gray-600"}`,children:[e.jsxs("div",{className:"flex items-center justify-between space-x-3",children:[e.jsx("span",{children:"Nodes:"}),e.jsx("span",{className:"font-medium",children:i.nodes.length})]}),e.jsxs("div",{className:"flex items-center justify-between space-x-3",children:[e.jsx("span",{children:"Edges:"}),e.jsx("span",{className:"font-medium",children:i.edges.length})]}),e.jsxs("div",{className:"flex items-center justify-between space-x-3",children:[e.jsx("span",{children:"Executed:"}),e.jsx("span",{className:"font-medium",children:i.executionPath.length})]}),o.threadId&&o.assistantId&&e.jsxs("div",{className:`mt-2 pt-2 border-t ${t?"border-gray-600":"border-gray-200"}`,children:[e.jsx("div",{className:"text-xs font-medium mb-1",children:"Context:"}),e.jsxs("div",{className:"text-xs opacity-75",children:["Thread: ",o.threadId.split("-")[0],"..."]}),e.jsxs("div",{className:"text-xs opacity-75",children:["Assistant: ",o.assistantId.split("-")[0],"..."]})]})]})})]})}),!u&&e.jsx("div",{className:` flex-shrink-0 transition-all duration-300 ease-in-out - ${p==="right"?"w-96 border-l":"border-t"} + ${p==="right"?"w-96 border-l":"border-t"} ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} `,style:{height:p==="bottom"?"40vh":"100%",minHeight:p==="bottom"?"300px":"0px",maxHeight:p==="bottom"?"50vh":"none"},children:e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsx("div",{className:`flex border-b ${t?"border-gray-600":"border-gray-200"}`,children:[{id:"input",label:"Input",icon:"📝"},{id:"logs",label:"Logs",icon:"📋",badge:o.logs.length},{id:"state",label:"State",icon:"🔍",badge:Object.keys(o.currentState||{}).length}].map(s=>e.jsx("button",{onClick:()=>U(s.id),className:`flex-1 px-4 py-3 text-sm font-medium transition-colors relative ${z===s.id?t?"bg-gray-700 text-white border-b-2 border-blue-500":"bg-gray-50 text-gray-900 border-b-2 border-blue-500":t?"text-gray-400 hover:text-gray-300 hover:bg-gray-700":"text-gray-600 hover:text-gray-900 hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[e.jsx("span",{children:s.icon}),e.jsx("span",{children:s.label}),s.badge!==void 0&&s.badge>0&&e.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${z===s.id?"bg-blue-500 text-white":t?"bg-gray-600 text-gray-300":"bg-gray-200 text-gray-700"}`,children:s.badge}),s.id==="logs"&&o.isExecuting&&!o.isPaused&&e.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"})]})},s.id))}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[z==="input"&&e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx(_e,{currentState:o.currentState,onStateChange:w,onStartExecution:ue,darkMode:t}),e.jsxs("div",{className:`p-4 border-t ${t?"border-gray-600":"border-gray-200"}`,children:[e.jsx("h3",{className:`text-sm font-semibold mb-3 ${t?"text-white":"text-gray-900"}`,children:"Execution Controls"}),e.jsx("div",{className:`${p==="bottom"?"flex space-x-2":"space-y-2"}`,children:o.isExecuting?e.jsxs(e.Fragment,{children:[o.isPaused?e.jsxs("button",{onClick:()=>{b()},className:`${p==="bottom"?"flex-1":"w-full"} px-3 py-2 text-sm font-medium rounded-lg transition-all duration-200 flex items-center justify-center shadow-sm hover:shadow-md bg-blue-600 hover:bg-blue-700 text-white hover:scale-105`,children:[e.jsx("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.828 14.828a4 4 0 01-5.656 0M9 10h1m4 0h1m-6 4h8m-9 5a9 9 0 1118 0 9 9 0 01-18 0z"})}),"Resume"]}):e.jsx("p",{className:"rounded-lg border border-gray-300 bg-gray-50 px-3 py-2 text-xs text-gray-600 dark:border-gray-600 dark:bg-gray-700/50 dark:text-gray-300",children:"Live server execution is in progress. Set a breakpoint before starting to pause a supported LangGraph run."}),e.jsxs("button",{onClick:N,className:`${p==="bottom"?"flex-1":"w-full"} px-3 py-2 text-sm font-medium rounded-lg transition-all duration-200 flex items-center justify-center shadow-sm hover:shadow-md bg-red-600 hover:bg-red-700 text-white hover:scale-105`,children:[e.jsxs("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 10h6v4H9z"})]}),"Stop live stream"]})]}):e.jsxs("p",{className:`rounded-lg border px-3 py-2 text-xs ${t?"border-gray-600 bg-gray-700/50 text-gray-300":"border-gray-200 bg-gray-50 text-gray-600"}`,children:["Complete the schema form above and use ",e.jsx("strong",{children:"Submit & Run"}),". This validates required fields before starting a real execution."]})})]})]}),z==="logs"&&e.jsx(Te,{logs:o.logs,darkMode:t,onLogHover:xe,onLogSelect:K,selectedLogId:G,selectedNodeId:l,onClearNodeFilter:()=>y(null)}),z==="state"&&e.jsx(Oe,{currentState:o.currentState,executionContext:o,darkMode:t})]})]})})]}),Q&&e.jsx(Ce,{nodeId:Q.nodeId,logs:o.logs,darkMode:t,position:Q.position,onClose:oe})]})};export{Ae as GraphView}; diff --git a/src/agentomatic/studio/static/assets/IngestorsView-q0ceZCW0.js b/src/agentomatic/studio/static/assets/IngestorsView-Cd56f61k.js similarity index 95% rename from src/agentomatic/studio/static/assets/IngestorsView-q0ceZCW0.js rename to src/agentomatic/studio/static/assets/IngestorsView-Cd56f61k.js index 771d3e66..1d667135 100644 --- a/src/agentomatic/studio/static/assets/IngestorsView-q0ceZCW0.js +++ b/src/agentomatic/studio/static/assets/IngestorsView-Cd56f61k.js @@ -1 +1 @@ -import{u as F,A as S,d as $,j as a}from"./index-A2k5j4o2.js";import{r as s}from"./react-vendor-BHJ3EV8m.js";import{S as L}from"./SchemaForm-bIikrW9E.js";import{O as _}from"./OutputSchemaSummary-DzWXQCQ1.js";import"./syntax-vendor-ru7AzRyY.js";const B=()=>{const{config:o,darkMode:r}=F(),[v,I]=s.useState([]),[p,E]=s.useState({}),[x,C]=s.useState({}),[R,j]=s.useState({}),[N,O]=s.useState({}),[b,w]=s.useState(null),[i,g]=s.useState(!0),[h,m]=s.useState(null),y=s.useCallback(async()=>{if(!o?.apiUrl){g(!1);return}g(!0);try{const e=new S(o.apiUrl,o.apiKey||void 0),n=await e.listIngestors(),l=await Promise.all(n.map(async t=>{try{return{name:t.name,contract:await e.getOperationContract(`/api/v1/ingestion/${encodeURIComponent(t.name)}/run`),error:null}}catch(d){return{name:t.name,contract:null,error:d?.message||"Could not load run contract"}}})),u=Object.fromEntries(l.flatMap(t=>t.contract?[[t.name,t.contract]]:[])),f=Object.fromEntries(l.flatMap(t=>t.error?[[t.name,t.error]]:[]));I(n),E(u),C(f),j(t=>Object.fromEntries(n.map(d=>[d.name,t[d.name]??$(u[d.name]?.input_schema||void 0)]))),m(null)}catch(e){m(e?.message||"Failed to fetch ingestors")}finally{g(!1)}},[o?.apiUrl,o?.apiKey]);s.useEffect(()=>{y()},[y]);const U=async(e,n)=>{if(o?.apiUrl){w(e.name),m(null);try{const u=await new S(o.apiUrl,o.apiKey||void 0).runIngestor(e.name,n);O(f=>({...f,[e.name]:u}))}catch(l){m(l?.message||`Failed to run ingestor '${e.name}'`)}finally{w(null)}}},k=r?"bg-gray-800 border-gray-700":"bg-white border-gray-200",c=r?"text-gray-400":"text-gray-600";return a.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[a.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold",children:"Ingestors"}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:"Run each live ingestion resource independently. Input forms and expected output are read from the deployed OpenAPI contract."})]}),a.jsx("button",{type:"button",onClick:()=>{y()},disabled:i||b!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:i?"Refreshing…":"Refresh"})]}),i&&a.jsx("div",{className:c,children:"Loading ingestors…"}),h&&a.jsx("div",{role:"alert",className:`mb-4 rounded-lg border p-4 ${r?"border-red-800 bg-red-900/30 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:h}),!i&&!h&&v.length===0&&a.jsx("div",{className:c,children:"No ingestors registered."}),a.jsx("div",{className:"grid grid-cols-1 gap-6 xl:grid-cols-2",children:v.map(e=>a.jsxs("section",{className:`rounded-xl border p-5 shadow-sm sm:p-6 ${k}`,children:[a.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("h2",{className:"truncate text-lg font-semibold",children:e.name}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:e.description||"No description provided"})]}),a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs",children:[a.jsx("span",{className:`h-2 w-2 rounded-full ${e.ready?"bg-green-500":"bg-gray-400"}`}),e.ready?"Ready":"Idle"]})]}),a.jsxs("div",{className:`mb-4 flex flex-wrap gap-2 text-xs ${c}`,children:[a.jsxs("span",{className:`rounded px-2 py-0.5 font-mono ${r?"bg-teal-950 text-teal-200":"bg-teal-50 text-teal-800"}`,children:["POST /api/v1/ingestion/",e.name,"/run"]}),a.jsxs("span",{children:["v",e.version]})]}),a.jsxs("div",{className:`space-y-3 border-t pt-4 ${r?"border-gray-700":"border-gray-200"}`,children:[x[e.name]&&a.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live run contract unavailable: ",x[e.name],". Execution stays disabled until the deployed schema can be read."]}),a.jsx(L,{schema:p[e.name]?.input_schema,value:R[e.name]??$(p[e.name]?.input_schema||void 0),onChange:n=>j(l=>({...l,[e.name]:n})),onSubmit:n=>{U(e,n)},submitLabel:b===e.name?"Running ingestor…":"Run ingestor",disabled:b!==null||!e.ready||!!x[e.name],darkMode:r}),a.jsx(_,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]!==void 0&&a.jsx("pre",{className:`mt-4 max-h-64 overflow-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${r?"bg-gray-950 text-gray-200":"bg-gray-50 text-gray-800"}`,children:JSON.stringify(N[e.name],null,2)})]},e.name))})]})};export{B as IngestorsView}; +import{u as F,A as S,d as $,j as a}from"./index-FSSL6O5F.js";import{r as s}from"./react-vendor-BHJ3EV8m.js";import{S as L}from"./SchemaForm-DyHc2s7z.js";import{O as _}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const B=()=>{const{config:o,darkMode:r}=F(),[v,I]=s.useState([]),[p,E]=s.useState({}),[x,C]=s.useState({}),[R,j]=s.useState({}),[N,O]=s.useState({}),[b,w]=s.useState(null),[i,g]=s.useState(!0),[h,m]=s.useState(null),y=s.useCallback(async()=>{if(!o?.apiUrl){g(!1);return}g(!0);try{const e=new S(o.apiUrl,o.apiKey||void 0),n=await e.listIngestors(),l=await Promise.all(n.map(async t=>{try{return{name:t.name,contract:await e.getOperationContract(`/api/v1/ingestion/${encodeURIComponent(t.name)}/run`),error:null}}catch(d){return{name:t.name,contract:null,error:d?.message||"Could not load run contract"}}})),u=Object.fromEntries(l.flatMap(t=>t.contract?[[t.name,t.contract]]:[])),f=Object.fromEntries(l.flatMap(t=>t.error?[[t.name,t.error]]:[]));I(n),E(u),C(f),j(t=>Object.fromEntries(n.map(d=>[d.name,t[d.name]??$(u[d.name]?.input_schema||void 0)]))),m(null)}catch(e){m(e?.message||"Failed to fetch ingestors")}finally{g(!1)}},[o?.apiUrl,o?.apiKey]);s.useEffect(()=>{y()},[y]);const U=async(e,n)=>{if(o?.apiUrl){w(e.name),m(null);try{const u=await new S(o.apiUrl,o.apiKey||void 0).runIngestor(e.name,n);O(f=>({...f,[e.name]:u}))}catch(l){m(l?.message||`Failed to run ingestor '${e.name}'`)}finally{w(null)}}},k=r?"bg-gray-800 border-gray-700":"bg-white border-gray-200",c=r?"text-gray-400":"text-gray-600";return a.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[a.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold",children:"Ingestors"}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:"Run each live ingestion resource independently. Input forms and expected output are read from the deployed OpenAPI contract."})]}),a.jsx("button",{type:"button",onClick:()=>{y()},disabled:i||b!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:i?"Refreshing…":"Refresh"})]}),i&&a.jsx("div",{className:c,children:"Loading ingestors…"}),h&&a.jsx("div",{role:"alert",className:`mb-4 rounded-lg border p-4 ${r?"border-red-800 bg-red-900/30 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:h}),!i&&!h&&v.length===0&&a.jsx("div",{className:c,children:"No ingestors registered."}),a.jsx("div",{className:"grid grid-cols-1 gap-6 xl:grid-cols-2",children:v.map(e=>a.jsxs("section",{className:`rounded-xl border p-5 shadow-sm sm:p-6 ${k}`,children:[a.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("h2",{className:"truncate text-lg font-semibold",children:e.name}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:e.description||"No description provided"})]}),a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs",children:[a.jsx("span",{className:`h-2 w-2 rounded-full ${e.ready?"bg-green-500":"bg-gray-400"}`}),e.ready?"Ready":"Idle"]})]}),a.jsxs("div",{className:`mb-4 flex flex-wrap gap-2 text-xs ${c}`,children:[a.jsxs("span",{className:`rounded px-2 py-0.5 font-mono ${r?"bg-teal-950 text-teal-200":"bg-teal-50 text-teal-800"}`,children:["POST /api/v1/ingestion/",e.name,"/run"]}),a.jsxs("span",{children:["v",e.version]})]}),a.jsxs("div",{className:`space-y-3 border-t pt-4 ${r?"border-gray-700":"border-gray-200"}`,children:[x[e.name]&&a.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live run contract unavailable: ",x[e.name],". Execution stays disabled until the deployed schema can be read."]}),a.jsx(L,{schema:p[e.name]?.input_schema,value:R[e.name]??$(p[e.name]?.input_schema||void 0),onChange:n=>j(l=>({...l,[e.name]:n})),onSubmit:n=>{U(e,n)},submitLabel:b===e.name?"Running ingestor…":"Run ingestor",disabled:b!==null||!e.ready||!!x[e.name],darkMode:r}),a.jsx(_,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]!==void 0&&a.jsx("pre",{className:`mt-4 max-h-64 overflow-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${r?"bg-gray-950 text-gray-200":"bg-gray-50 text-gray-800"}`,children:JSON.stringify(N[e.name],null,2)})]},e.name))})]})};export{B as IngestorsView}; diff --git a/src/agentomatic/studio/static/assets/OutputSchemaSummary-DzWXQCQ1.js b/src/agentomatic/studio/static/assets/OutputSchemaSummary-C65WaRqI.js similarity index 97% rename from src/agentomatic/studio/static/assets/OutputSchemaSummary-DzWXQCQ1.js rename to src/agentomatic/studio/static/assets/OutputSchemaSummary-C65WaRqI.js index 445a9158..a63b8ac3 100644 --- a/src/agentomatic/studio/static/assets/OutputSchemaSummary-DzWXQCQ1.js +++ b/src/agentomatic/studio/static/assets/OutputSchemaSummary-C65WaRqI.js @@ -1 +1 @@ -import{q as c,i as o,j as e}from"./index-A2k5j4o2.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";const y=({schema:a,source:r,darkMode:t=!1,className:i=""})=>{const[l,m]=g.useState(!1),x=c(a||void 0),n=o(a||void 0);return e.jsxs("div",{className:`rounded-lg border ${t?"border-gray-600 bg-gray-800/50":"border-gray-200 bg-gray-50"} ${i}`,children:[e.jsxs("button",{type:"button",onClick:()=>m(s=>!s),className:`w-full flex items-center justify-between px-3 py-2 text-left ${t?"hover:bg-gray-700/50":"hover:bg-gray-100"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`text-xs font-semibold ${t?"text-gray-200":"text-gray-800"}`,children:"Expected output"}),r?.source&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-medium ${r.source==="custom"?t?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":t?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${r.convention||r.source}`,children:[r.source==="custom"?"Custom":"Default",r.model?` · ${r.model}`:""]})]}),e.jsx("div",{className:`text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:n?"No output schema available":`${x.length} field${x.length===1?"":"s"}`})]}),e.jsx("svg",{className:`w-4 h-4 transition-transform ${l?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),l&&e.jsxs("div",{className:`px-3 pb-3 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[n?e.jsx("p",{className:`text-[10px] mt-2 italic ${t?"text-gray-500":"text-gray-400"}`,children:"Agent did not expose an output schema."}):e.jsx("ul",{className:"mt-2 space-y-1.5",children:x.map(s=>e.jsxs("li",{className:"text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("code",{className:`px-1.5 py-0.5 rounded font-mono text-[10px] ${t?"bg-gray-700 text-blue-300":"bg-white text-blue-700 border border-gray-200"}`,children:s.name}),e.jsx("span",{className:`text-[10px] ${t?"text-gray-400":"text-gray-500"}`,children:s.type}),s.required&&e.jsx("span",{className:"text-[10px] text-red-500 font-medium",children:"required"})]}),s.description&&e.jsx("p",{className:`mt-0.5 text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:s.description})]},s.name))}),!n&&e.jsxs("details",{className:"mt-2",children:[e.jsx("summary",{className:`text-[10px] cursor-pointer ${t?"text-gray-400":"text-gray-500"}`,children:"View raw schema"}),e.jsx("pre",{className:`mt-1 p-2 rounded text-[10px] font-mono overflow-x-auto max-h-40 ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-700 border border-gray-200"}`,children:JSON.stringify(a,null,2)})]})]})]})};export{y as O}; +import{q as c,i as o,j as e}from"./index-FSSL6O5F.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";const y=({schema:a,source:r,darkMode:t=!1,className:i=""})=>{const[l,m]=g.useState(!1),x=c(a||void 0),n=o(a||void 0);return e.jsxs("div",{className:`rounded-lg border ${t?"border-gray-600 bg-gray-800/50":"border-gray-200 bg-gray-50"} ${i}`,children:[e.jsxs("button",{type:"button",onClick:()=>m(s=>!s),className:`w-full flex items-center justify-between px-3 py-2 text-left ${t?"hover:bg-gray-700/50":"hover:bg-gray-100"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`text-xs font-semibold ${t?"text-gray-200":"text-gray-800"}`,children:"Expected output"}),r?.source&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-medium ${r.source==="custom"?t?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":t?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${r.convention||r.source}`,children:[r.source==="custom"?"Custom":"Default",r.model?` · ${r.model}`:""]})]}),e.jsx("div",{className:`text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:n?"No output schema available":`${x.length} field${x.length===1?"":"s"}`})]}),e.jsx("svg",{className:`w-4 h-4 transition-transform ${l?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),l&&e.jsxs("div",{className:`px-3 pb-3 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[n?e.jsx("p",{className:`text-[10px] mt-2 italic ${t?"text-gray-500":"text-gray-400"}`,children:"Agent did not expose an output schema."}):e.jsx("ul",{className:"mt-2 space-y-1.5",children:x.map(s=>e.jsxs("li",{className:"text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("code",{className:`px-1.5 py-0.5 rounded font-mono text-[10px] ${t?"bg-gray-700 text-blue-300":"bg-white text-blue-700 border border-gray-200"}`,children:s.name}),e.jsx("span",{className:`text-[10px] ${t?"text-gray-400":"text-gray-500"}`,children:s.type}),s.required&&e.jsx("span",{className:"text-[10px] text-red-500 font-medium",children:"required"})]}),s.description&&e.jsx("p",{className:`mt-0.5 text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:s.description})]},s.name))}),!n&&e.jsxs("details",{className:"mt-2",children:[e.jsx("summary",{className:`text-[10px] cursor-pointer ${t?"text-gray-400":"text-gray-500"}`,children:"View raw schema"}),e.jsx("pre",{className:`mt-1 p-2 rounded text-[10px] font-mono overflow-x-auto max-h-40 ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-700 border border-gray-200"}`,children:JSON.stringify(a,null,2)})]})]})]})};export{y as O}; diff --git a/src/agentomatic/studio/static/assets/PipelinesView-8o6MHHuZ.js b/src/agentomatic/studio/static/assets/PipelinesView-DacXbEMw.js similarity index 96% rename from src/agentomatic/studio/static/assets/PipelinesView-8o6MHHuZ.js rename to src/agentomatic/studio/static/assets/PipelinesView-DacXbEMw.js index e2b87c60..ca7cfa5a 100644 --- a/src/agentomatic/studio/static/assets/PipelinesView-8o6MHHuZ.js +++ b/src/agentomatic/studio/static/assets/PipelinesView-DacXbEMw.js @@ -1 +1 @@ -import{u as _,A as E,p as $,a as K,j as t}from"./index-A2k5j4o2.js";import{r as n}from"./react-vendor-BHJ3EV8m.js";import{S as A}from"./SchemaForm-bIikrW9E.js";import{O as I}from"./OutputSchemaSummary-DzWXQCQ1.js";import"./syntax-vendor-ru7AzRyY.js";const z=()=>{const{config:o,darkMode:r,setCurrentView:C,setBuilderPipelineToLoad:P}=_(),[y,R]=n.useState([]),[c,u]=n.useState(!0),[x,v]=n.useState(null),[f,k]=n.useState({}),[b,O]=n.useState({}),[L,j]=n.useState({}),[g,N]=n.useState(null),[d,B]=n.useState({}),[w,S]=n.useState(null),h=n.useCallback(async()=>{if(!o?.apiUrl){u(!1);return}u(!0);try{const e=new E(o.apiUrl,o.apiKey||void 0),s=await e.listPipelines(),l=await Promise.all(s.map(async a=>{try{const i=await e.getPipelineConfig(a.name);return{name:a.name,schema:{input:$(i.input_schema),output:$(i.output_schema)},error:null}}catch(i){return{name:a.name,schema:{input:null,output:null},error:i?.message||"Could not load pipeline contract"}}})),m=Object.fromEntries(l.map(a=>[a.name,a.schema])),p=Object.fromEntries(l.flatMap(a=>a.error?[[a.name,a.error]]:[]));R(s),k(m),O(p),j(a=>Object.fromEntries(s.map(i=>[i.name,a[i.name]??K(m[i.name]?.input||void 0)]))),v(null)}catch(e){v(e.message||"Failed to fetch pipelines")}finally{u(!1)}},[o?.apiUrl,o?.apiKey]);n.useEffect(()=>{h()},[h]);const U=async(e,s)=>{if(o?.apiUrl){N(e),S(null);try{const m=await new E(o.apiUrl,o.apiKey||void 0).runPipeline(e,{input:s});B(p=>({...p,[e]:m}))}catch(l){S(l?.message||`Failed to run pipeline '${e}'`)}finally{N(null)}}},F=e=>{P(e),C("builder")};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Pipelines"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Run live pipeline contracts independently and refresh their deployed schemas without reconnecting."})]}),t.jsx("button",{type:"button",onClick:()=>{h()},disabled:c||g!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:c?"Refreshing…":"Refresh"})]}),c&&t.jsx("div",{className:"text-gray-500",children:"Loading pipelines..."}),x&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:x}),w&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:w}),!c&&!x&&y.length===0&&t.jsx("div",{className:"text-gray-500",children:"No pipelines found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:y.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm`,children:[t.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[t.jsx("h2",{className:"min-w-0 truncate text-lg font-semibold",children:e.name}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-blue-900 text-blue-200":"bg-blue-100 text-blue-800"}`,children:["v",e.version]}),t.jsx("button",{type:"button",onClick:()=>F(e.name),className:`rounded-lg border px-2.5 py-1.5 text-xs font-semibold transition-colors ${r?"border-violet-700 bg-violet-950/50 text-violet-200 hover:bg-violet-900/70":"border-violet-200 bg-violet-50 text-violet-800 hover:bg-violet-100"}`,title:`Load ${e.name} into the visual Builder`,children:"Edit in Builder"})]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4",children:[t.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2",children:"Steps"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:e.steps.map((s,l)=>t.jsx("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:s},l))})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[b[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live pipeline contract unavailable: ",b[e.name],". Running stays disabled until the deployed schema can be read."]}),t.jsx(A,{schema:f[e.name]?.input,value:L[e.name]||{},onChange:s=>j(l=>({...l,[e.name]:s})),onSubmit:s=>{U(e.name,s)},submitLabel:g===e.name?"Running pipeline…":"Run pipeline",disabled:g!==null||!!b[e.name],darkMode:r}),t.jsx(I,{schema:f[e.name]?.output,darkMode:r})]}),d[e.name]&&t.jsxs("div",{className:`mt-4 rounded-lg p-3 text-xs ${r?"bg-gray-900":"bg-gray-50"}`,children:[t.jsxs("div",{className:"font-medium mb-2",children:[d[e.name].status," · ",d[e.name].duration_ms," ms"]}),t.jsx("pre",{className:"whitespace-pre-wrap break-words",children:JSON.stringify(d[e.name].output,null,2)}),t.jsx("div",{className:"mt-3 border-t border-gray-200 pt-2 dark:border-gray-700",children:Object.values(d[e.name].steps).map(s=>t.jsxs("div",{className:"flex justify-between gap-2 py-0.5 font-mono",children:[t.jsx("span",{children:s.name}),t.jsxs("span",{children:[s.status," · ",s.duration_ms," ms"]})]},s.name))})]})]},e.name))})]})};export{z as PipelinesView}; +import{u as _,A as E,p as $,a as K,j as t}from"./index-FSSL6O5F.js";import{r as n}from"./react-vendor-BHJ3EV8m.js";import{S as A}from"./SchemaForm-DyHc2s7z.js";import{O as I}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const z=()=>{const{config:o,darkMode:r,setCurrentView:C,setBuilderPipelineToLoad:P}=_(),[y,R]=n.useState([]),[c,u]=n.useState(!0),[x,v]=n.useState(null),[f,k]=n.useState({}),[b,O]=n.useState({}),[L,j]=n.useState({}),[g,N]=n.useState(null),[d,B]=n.useState({}),[w,S]=n.useState(null),h=n.useCallback(async()=>{if(!o?.apiUrl){u(!1);return}u(!0);try{const e=new E(o.apiUrl,o.apiKey||void 0),s=await e.listPipelines(),l=await Promise.all(s.map(async a=>{try{const i=await e.getPipelineConfig(a.name);return{name:a.name,schema:{input:$(i.input_schema),output:$(i.output_schema)},error:null}}catch(i){return{name:a.name,schema:{input:null,output:null},error:i?.message||"Could not load pipeline contract"}}})),m=Object.fromEntries(l.map(a=>[a.name,a.schema])),p=Object.fromEntries(l.flatMap(a=>a.error?[[a.name,a.error]]:[]));R(s),k(m),O(p),j(a=>Object.fromEntries(s.map(i=>[i.name,a[i.name]??K(m[i.name]?.input||void 0)]))),v(null)}catch(e){v(e.message||"Failed to fetch pipelines")}finally{u(!1)}},[o?.apiUrl,o?.apiKey]);n.useEffect(()=>{h()},[h]);const U=async(e,s)=>{if(o?.apiUrl){N(e),S(null);try{const m=await new E(o.apiUrl,o.apiKey||void 0).runPipeline(e,{input:s});B(p=>({...p,[e]:m}))}catch(l){S(l?.message||`Failed to run pipeline '${e}'`)}finally{N(null)}}},F=e=>{P(e),C("builder")};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Pipelines"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Run live pipeline contracts independently and refresh their deployed schemas without reconnecting."})]}),t.jsx("button",{type:"button",onClick:()=>{h()},disabled:c||g!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:c?"Refreshing…":"Refresh"})]}),c&&t.jsx("div",{className:"text-gray-500",children:"Loading pipelines..."}),x&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:x}),w&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:w}),!c&&!x&&y.length===0&&t.jsx("div",{className:"text-gray-500",children:"No pipelines found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:y.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm`,children:[t.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[t.jsx("h2",{className:"min-w-0 truncate text-lg font-semibold",children:e.name}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-blue-900 text-blue-200":"bg-blue-100 text-blue-800"}`,children:["v",e.version]}),t.jsx("button",{type:"button",onClick:()=>F(e.name),className:`rounded-lg border px-2.5 py-1.5 text-xs font-semibold transition-colors ${r?"border-violet-700 bg-violet-950/50 text-violet-200 hover:bg-violet-900/70":"border-violet-200 bg-violet-50 text-violet-800 hover:bg-violet-100"}`,title:`Load ${e.name} into the visual Builder`,children:"Edit in Builder"})]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4",children:[t.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2",children:"Steps"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:e.steps.map((s,l)=>t.jsx("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:s},l))})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[b[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live pipeline contract unavailable: ",b[e.name],". Running stays disabled until the deployed schema can be read."]}),t.jsx(A,{schema:f[e.name]?.input,value:L[e.name]||{},onChange:s=>j(l=>({...l,[e.name]:s})),onSubmit:s=>{U(e.name,s)},submitLabel:g===e.name?"Running pipeline…":"Run pipeline",disabled:g!==null||!!b[e.name],darkMode:r}),t.jsx(I,{schema:f[e.name]?.output,darkMode:r})]}),d[e.name]&&t.jsxs("div",{className:`mt-4 rounded-lg p-3 text-xs ${r?"bg-gray-900":"bg-gray-50"}`,children:[t.jsxs("div",{className:"font-medium mb-2",children:[d[e.name].status," · ",d[e.name].duration_ms," ms"]}),t.jsx("pre",{className:"whitespace-pre-wrap break-words",children:JSON.stringify(d[e.name].output,null,2)}),t.jsx("div",{className:"mt-3 border-t border-gray-200 pt-2 dark:border-gray-700",children:Object.values(d[e.name].steps).map(s=>t.jsxs("div",{className:"flex justify-between gap-2 py-0.5 font-mono",children:[t.jsx("span",{children:s.name}),t.jsxs("span",{children:[s.status," · ",s.duration_ms," ms"]})]},s.name))})]})]},e.name))})]})};export{z as PipelinesView}; diff --git a/src/agentomatic/studio/static/assets/PluginsView-T_czY3dU.js b/src/agentomatic/studio/static/assets/PluginsView-COAn7Q5V.js similarity index 96% rename from src/agentomatic/studio/static/assets/PluginsView-T_czY3dU.js rename to src/agentomatic/studio/static/assets/PluginsView-COAn7Q5V.js index 754ea70a..5bf2186a 100644 --- a/src/agentomatic/studio/static/assets/PluginsView-T_czY3dU.js +++ b/src/agentomatic/studio/static/assets/PluginsView-COAn7Q5V.js @@ -1 +1 @@ -import{u as J,A as C,d as P,j as t}from"./index-A2k5j4o2.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as K}from"./SchemaForm-bIikrW9E.js";import{O as A}from"./OutputSchemaSummary-DzWXQCQ1.js";import"./syntax-vendor-ru7AzRyY.js";const G=()=>{const{config:c,darkMode:r}=J(),[v,j]=d.useState([]),[u,x]=d.useState(!0),[g,l]=d.useState(null),[p,E]=d.useState({}),[h,k]=d.useState({}),[M,w]=d.useState({}),[i,m]=d.useState(null),[N,O]=d.useState({}),[$,_]=d.useState({}),[S,L]=d.useState({}),y=d.useCallback(async()=>{if(!c?.apiUrl){x(!1);return}x(!0);try{const e=new C(c.apiUrl,c.apiKey||void 0),a=await e.listPlugins(),s=await Promise.all(a.map(async o=>{try{return{name:o.name,contract:await e.getOperationContract(`/api/v1/plugins/${encodeURIComponent(o.name)}/predict`),error:null}}catch(b){return{name:o.name,contract:null,error:b?.message||"Could not load predict contract"}}})),n=Object.fromEntries(s.flatMap(o=>o.contract?[[o.name,o.contract]]:[])),B=Object.fromEntries(s.flatMap(o=>o.error?[[o.name,o.error]]:[]));j(a),E(n),k(B),w(o=>Object.fromEntries(a.map(b=>[b.name,o[b.name]??P(n[b.name]?.input_schema||void 0)]))),l(null)}catch(e){l(e.message||"Failed to fetch plugins")}finally{x(!1)}},[c?.apiUrl,c?.apiKey]);d.useEffect(()=>{y()},[y]);const f=()=>new C(c.apiUrl,c.apiKey||void 0),R=async e=>{m(`card:${e}`),l(null);try{const a=await f().getPluginModelCard(e);O(s=>({...s,[e]:a}))}catch(a){l(a?.message||`Failed to load model card for '${e}'`)}finally{m(null)}},F=async(e,a)=>{m(`predict:${e}`),l(null);try{const s=await f().runPluginPredict(e,a);_(n=>({...n,[e]:s}))}catch(s){l(s?.message||`Failed to run '${e}'`)}finally{m(null)}},U=async e=>{m(`reload:${e}`),l(null);try{const a=await f().reloadPlugin(e);L(s=>({...s,[e]:a})),j(s=>s.map(n=>n.name===e?{...n,is_loaded:!!a.is_loaded}:n))}catch(a){l(a?.message||`Failed to reload '${e}'`)}finally{m(null)}};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"ML Plugins"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Reload the live inventory and its published prediction contracts without reconnecting Studio."})]}),t.jsx("button",{type:"button",onClick:()=>{y()},disabled:u||i!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:u?"Refreshing…":"Refresh"})]}),u&&t.jsx("div",{className:"text-gray-500",children:"Loading plugins..."}),g&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:g}),!u&&!g&&v.length===0&&t.jsx("div",{className:"text-gray-500",children:"No ML plugins found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:v.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm flex flex-col justify-between`,children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-start mb-4",children:[t.jsx("h2",{className:"text-lg font-semibold",children:e.name}),t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-purple-900 text-purple-200":"bg-purple-100 text-purple-800"}`,children:["v",e.version]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4 flex items-center",children:[t.jsx("span",{className:`w-2 h-2 rounded-full mr-2 ${e.is_loaded?"bg-green-500":"bg-red-500"}`}),t.jsx("span",{className:"text-sm",children:e.is_loaded?"Loaded":"Unloaded"})]})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 flex flex-wrap justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{U(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-violet-800 hover:bg-violet-700":"bg-violet-100 text-violet-900 hover:bg-violet-200"}`,children:i===`reload:${e.name}`?"Reloading…":"Reload"}),t.jsx("button",{type:"button",onClick:()=>{R(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-gray-700 hover:bg-gray-600":"bg-gray-200 hover:bg-gray-300"}`,children:i===`card:${e.name}`?"Loading…":"Model Card"})]}),t.jsxs("div",{className:"space-y-3",children:[h[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live predict contract unavailable: ",h[e.name],". Prediction stays disabled until the deployed schema can be read."]}),t.jsx(K,{schema:p[e.name]?.input_schema,value:M[e.name]??P(p[e.name]?.input_schema||void 0),onChange:a=>w(s=>({...s,[e.name]:a})),onSubmit:a=>{F(e.name,a)},submitLabel:i===`predict:${e.name}`?"Predicting…":"Predict",disabled:i!==null||!e.is_loaded||!!h[e.name],darkMode:r}),t.jsx(A,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(N[e.name],null,2)}),S[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(S[e.name],null,2)}),$[e.name]!==void 0&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify($[e.name],null,2)})]},e.name))})]})};export{G as PluginsView}; +import{u as J,A as C,d as P,j as t}from"./index-FSSL6O5F.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as K}from"./SchemaForm-DyHc2s7z.js";import{O as A}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const G=()=>{const{config:c,darkMode:r}=J(),[v,j]=d.useState([]),[u,x]=d.useState(!0),[g,l]=d.useState(null),[p,E]=d.useState({}),[h,k]=d.useState({}),[M,w]=d.useState({}),[i,m]=d.useState(null),[N,O]=d.useState({}),[$,_]=d.useState({}),[S,L]=d.useState({}),y=d.useCallback(async()=>{if(!c?.apiUrl){x(!1);return}x(!0);try{const e=new C(c.apiUrl,c.apiKey||void 0),a=await e.listPlugins(),s=await Promise.all(a.map(async o=>{try{return{name:o.name,contract:await e.getOperationContract(`/api/v1/plugins/${encodeURIComponent(o.name)}/predict`),error:null}}catch(b){return{name:o.name,contract:null,error:b?.message||"Could not load predict contract"}}})),n=Object.fromEntries(s.flatMap(o=>o.contract?[[o.name,o.contract]]:[])),B=Object.fromEntries(s.flatMap(o=>o.error?[[o.name,o.error]]:[]));j(a),E(n),k(B),w(o=>Object.fromEntries(a.map(b=>[b.name,o[b.name]??P(n[b.name]?.input_schema||void 0)]))),l(null)}catch(e){l(e.message||"Failed to fetch plugins")}finally{x(!1)}},[c?.apiUrl,c?.apiKey]);d.useEffect(()=>{y()},[y]);const f=()=>new C(c.apiUrl,c.apiKey||void 0),R=async e=>{m(`card:${e}`),l(null);try{const a=await f().getPluginModelCard(e);O(s=>({...s,[e]:a}))}catch(a){l(a?.message||`Failed to load model card for '${e}'`)}finally{m(null)}},F=async(e,a)=>{m(`predict:${e}`),l(null);try{const s=await f().runPluginPredict(e,a);_(n=>({...n,[e]:s}))}catch(s){l(s?.message||`Failed to run '${e}'`)}finally{m(null)}},U=async e=>{m(`reload:${e}`),l(null);try{const a=await f().reloadPlugin(e);L(s=>({...s,[e]:a})),j(s=>s.map(n=>n.name===e?{...n,is_loaded:!!a.is_loaded}:n))}catch(a){l(a?.message||`Failed to reload '${e}'`)}finally{m(null)}};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"ML Plugins"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Reload the live inventory and its published prediction contracts without reconnecting Studio."})]}),t.jsx("button",{type:"button",onClick:()=>{y()},disabled:u||i!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:u?"Refreshing…":"Refresh"})]}),u&&t.jsx("div",{className:"text-gray-500",children:"Loading plugins..."}),g&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:g}),!u&&!g&&v.length===0&&t.jsx("div",{className:"text-gray-500",children:"No ML plugins found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:v.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm flex flex-col justify-between`,children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-start mb-4",children:[t.jsx("h2",{className:"text-lg font-semibold",children:e.name}),t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-purple-900 text-purple-200":"bg-purple-100 text-purple-800"}`,children:["v",e.version]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4 flex items-center",children:[t.jsx("span",{className:`w-2 h-2 rounded-full mr-2 ${e.is_loaded?"bg-green-500":"bg-red-500"}`}),t.jsx("span",{className:"text-sm",children:e.is_loaded?"Loaded":"Unloaded"})]})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 flex flex-wrap justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{U(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-violet-800 hover:bg-violet-700":"bg-violet-100 text-violet-900 hover:bg-violet-200"}`,children:i===`reload:${e.name}`?"Reloading…":"Reload"}),t.jsx("button",{type:"button",onClick:()=>{R(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-gray-700 hover:bg-gray-600":"bg-gray-200 hover:bg-gray-300"}`,children:i===`card:${e.name}`?"Loading…":"Model Card"})]}),t.jsxs("div",{className:"space-y-3",children:[h[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live predict contract unavailable: ",h[e.name],". Prediction stays disabled until the deployed schema can be read."]}),t.jsx(K,{schema:p[e.name]?.input_schema,value:M[e.name]??P(p[e.name]?.input_schema||void 0),onChange:a=>w(s=>({...s,[e.name]:a})),onSubmit:a=>{F(e.name,a)},submitLabel:i===`predict:${e.name}`?"Predicting…":"Predict",disabled:i!==null||!e.is_loaded||!!h[e.name],darkMode:r}),t.jsx(A,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(N[e.name],null,2)}),S[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(S[e.name],null,2)}),$[e.name]!==void 0&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify($[e.name],null,2)})]},e.name))})]})};export{G as PluginsView}; diff --git a/src/agentomatic/studio/static/assets/SchemaForm-bIikrW9E.js b/src/agentomatic/studio/static/assets/SchemaForm-DyHc2s7z.js similarity index 99% rename from src/agentomatic/studio/static/assets/SchemaForm-bIikrW9E.js rename to src/agentomatic/studio/static/assets/SchemaForm-DyHc2s7z.js index 47f8e5e5..13a57e3a 100644 --- a/src/agentomatic/studio/static/assets/SchemaForm-bIikrW9E.js +++ b/src/agentomatic/studio/static/assets/SchemaForm-DyHc2s7z.js @@ -1 +1 @@ -import{j as e,n as I,s as W,h as X,a as Y,k as Z,l as T,o as k,i as P,d as M,m as ee}from"./index-A2k5j4o2.js";import{r as v}from"./react-vendor-BHJ3EV8m.js";const D=()=>`row_${Math.random().toString(36).slice(2,10)}`;function te(n){if(n==null)return"string";if(Array.isArray(n))return"array";switch(typeof n){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"object"}}function U(n,g){const a=n?.properties;if(!a||typeof a!="object")return null;const s=I(a[g],n).type;return s==="string"||s==="number"||s==="integer"||s==="boolean"||s==="array"||s==="object"||s==="null"?s==="integer"?"number":s:null}function z(n){return!n||typeof n!="object"||Array.isArray(n)?[]:Object.entries(n).map(([g,a])=>{const r=te(a);return{id:D(),key:g,type:r,value:r==="object"||r==="array"||r==="null"?a==null?"null":JSON.stringify(a,null,2):String(a),error:null}})}function G(n){const g={};for(const a of n){const r=a.key.trim();if(r&&!a.error)switch(a.type){case"string":g[r]=a.value;break;case"number":{const s=a.value.trim()===""?0:Number(a.value);g[r]=Number.isNaN(s)?a.value:s;break}case"boolean":g[r]=a.value==="true";break;case"null":g[r]=null;break;case"object":case"array":{try{const s=JSON.parse(a.value);g[r]=s}catch{}break}}}return g}const V=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`;function re(n,g){let a=n,r=1;for(;g.has(a);)a=`${n}_${r++}`;return a}const se=({value:n,onChange:g,schema:a,darkMode:r=!1,disabled:s=!1,className:m=""})=>{const[h,f]=v.useState(()=>z(n)),b=t=>{f(t),g(G(t))},o=(t,i)=>{const j=h.map(l=>{if(l.id!==t)return l;const x={...l,...i};if(i.type==="object"||i.type==="array")try{JSON.parse(x.value),x.error=null}catch{x.error="Invalid JSON"}else x.error=null;return x});b(j)},y=()=>{const t="string",i=re(`field_${h.length+1}`,new Set(h.map(j=>j.key)));b([...h,{id:D(),key:i,type:t,value:"",error:null}])},A=t=>b(h.filter(i=>i.id!==t)),J=t=>t.type==="boolean"?e.jsx("input",{type:"checkbox",checked:t.value==="true",disabled:s,onChange:i=>o(t.id,{value:String(i.target.checked)}),className:"h-4 w-4 rounded border-gray-300"}):t.type==="null"?e.jsx("span",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"null"}):t.type==="object"||t.type==="array"?e.jsxs("div",{children:[e.jsx("textarea",{value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),rows:3,spellCheck:!1,placeholder:t.type==="array"?"[]":"{}",className:`${V(r)} font-mono ${t.error?"border-red-500":""}`}),t.error&&e.jsx("p",{className:"mt-0.5 text-[10px] text-red-500",children:t.error})]}):e.jsx("input",{type:t.type==="number"?"number":"text",value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),placeholder:t.type==="number"?"0":`Enter ${t.key||"value"}...`,className:V(r),step:t.type==="number"?"any":void 0}),N=v.useMemo(()=>JSON.stringify(n),[n]),[$,S]=v.useState(N);return N!==$&&(S(N),JSON.stringify(G(h))!==N&&f(z(n))),e.jsxs("div",{className:`space-y-2 ${m}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[10px] ${r?"text-gray-500":"text-gray-400"}`,children:"Generic dict — add any fields your agent accepts"}),e.jsx("button",{type:"button",disabled:s,onClick:y,className:`px-2 py-0.5 text-[10px] rounded ${r?"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-600":"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-300"}`,children:"+ Add field"})]}),h.length===0?e.jsx("p",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"No fields yet — click “Add field” to pass custom inputs."}):e.jsx("div",{className:"space-y-2",children:h.map(t=>e.jsx("div",{className:"flex items-start gap-1.5",children:e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",value:t.key,disabled:s,onChange:i=>o(t.id,{key:i.target.value}),placeholder:"field_name",className:`${V(r)} font-mono flex-1`}),e.jsxs("select",{value:t.type,disabled:s,onChange:i=>{const j=i.target.value;let l=t.value;if(j==="object"||j==="array")try{l=JSON.stringify(JSON.parse(t.value),null,2)}catch{l=j==="array"?"[]":"{}"}else j==="null"?l="null":t.type==="object"||t.type==="array"?l="":j==="boolean"&&(l=t.value==="true"?"true":"false");o(t.id,{type:j,value:l})},className:`${V(r)} w-24 flex-shrink-0`,children:[e.jsx("option",{value:"string",children:"string"}),e.jsx("option",{value:"number",children:"number"}),e.jsx("option",{value:"boolean",children:"boolean"}),e.jsx("option",{value:"object",children:"object"}),e.jsx("option",{value:"array",children:"array"}),e.jsx("option",{value:"null",children:"null"})]}),e.jsx("button",{type:"button",disabled:s,onClick:()=>A(t.id),title:"Remove field",className:`px-1.5 py-1 text-xs rounded ${r?"bg-red-700 hover:bg-red-600 text-white disabled:bg-gray-600":"bg-red-600 hover:bg-red-700 text-white disabled:bg-gray-300"}`,children:"×"})]}),e.jsx("div",{className:"pl-0",children:J(t)})]})},t.id))}),a&&e.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(a.properties||{}).filter(t=>!h.some(i=>i.key===t)).slice(0,8).map(t=>e.jsx(ne,{keyName:t,type:U(a,t),darkMode:r,disabled:s,onClick:()=>b([...h,{id:D(),key:t,type:U(a,t)||"string",value:"",error:null}])},t))})]})},ne=({keyName:n,type:g,darkMode:a,disabled:r,onClick:s})=>e.jsxs("button",{type:"button",disabled:r,onClick:s,className:`px-1.5 py-0.5 text-[10px] rounded border ${a?"border-gray-600 text-gray-400 hover:border-blue-500 hover:text-blue-300":"border-gray-200 text-gray-500 hover:border-blue-400 hover:text-blue-600"}`,children:["+ ",n,g?`:${g}`:""]}),O=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`,_=n=>`text-xs font-medium ${n?"text-gray-300":"text-gray-700"}`,F=({name:n,schema:g,rootSchema:a,value:r,required:s=!1,darkMode:m=!1,depth:h=0,onChange:f})=>{const b=v.useId(),o=I(g,a),y=W(g,a),[A,J]=v.useState(0);v.useEffect(()=>{J(l=>Math.min(l,Math.max(y.length-1,0)))},[y.length]);const N=X(n,o),$=typeof o.description=="string"?o.description:void 0,S=o.type||(o.properties?"object":"string"),t=e.jsx("div",{className:"flex items-center justify-between gap-2 mb-1",children:e.jsxs("label",{htmlFor:b,className:_(m),children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"}),e.jsx("span",{className:`ml-2 text-[10px] font-normal ${m?"text-gray-500":"text-gray-400"}`,children:String(S)})]})}),i=$?e.jsx("p",{className:`text-[10px] mb-1 ${m?"text-gray-500":"text-gray-400"}`,children:$}):null;if(y.length>0){const l=y[A]||y[0],x=(u,c)=>typeof u.title=="string"&&u.title?u.title:typeof u.$ref=="string"?u.$ref.split("/").at(-1)||`Option ${c+1}`:u.type?String(u.type):`Option ${c+1}`;return e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-violet-800/70 bg-violet-950/20":"border-violet-200 bg-violet-50/50"}`,children:[t,i,e.jsxs("label",{className:_(m),children:["Input shape",e.jsx("select",{value:A,onChange:u=>{const c=Number(u.target.value),d=y[c]||y[0];J(c),f(Y(d,a))},className:`${O(m)} mt-1`,children:y.map((u,c)=>e.jsx("option",{value:c,children:x(u,c)},`${x(u,c)}-${c}`))})]}),e.jsx(F,{name:n,schema:l,rootSchema:a,value:r,required:s,darkMode:m,depth:h,onChange:f})]})}if(Array.isArray(o.enum)&&o.enum.length>0){const l=Z(o.enum,r);return e.jsxs("div",{children:[t,i,e.jsxs("select",{id:b,value:l>=0?String(l):"",onChange:x=>f(k(o.enum,x.target.value)),className:O(m),children:[!s&&e.jsx("option",{value:"",children:"—"}),o.enum.map((x,u)=>e.jsx("option",{value:String(u),children:T(x)},`${T(x)}-${u}`))]})]})}if(o.const!==void 0)return e.jsxs("div",{children:[t,i,e.jsx("output",{"aria-label":`${N} fixed value`,className:`block w-full rounded border px-2 py-1.5 text-xs font-mono ${m?"border-gray-600 bg-gray-800 text-gray-300":"border-gray-300 bg-gray-50 text-gray-700"}`,children:T(o.const)})]});if(S==="boolean")return e.jsxs("div",{children:[e.jsxs("label",{className:`flex items-center gap-2 cursor-pointer ${_(m)}`,children:[e.jsx("input",{type:"checkbox",checked:!!r,onChange:l=>f(l.target.checked),className:"rounded border-gray-300"}),e.jsxs("span",{children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]})]}),i]});if(S==="number"||S==="integer")return e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"number",step:S==="integer"?1:"any",value:r??"",onChange:l=>{const x=l.target.value;if(x===""){f(void 0);return}const u=S==="integer"?parseInt(x,10):parseFloat(x);f(Number.isNaN(u)?x:u)},className:O(m),placeholder:o.examples?.[0]!=null?String(o.examples[0]):N})]});if(S==="array"){const x=I(o.items||{type:"string"},a).type||"string",u=Array.isArray(r)?r:[];return x==="string"||x==="number"||x==="integer"?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t,e.jsx("button",{type:"button",onClick:()=>f([...u,x==="string"?"":0]),className:"px-2 py-0.5 text-[10px] rounded bg-blue-600 hover:bg-blue-700 text-white",children:"+ Add"})]}),i,e.jsxs("div",{className:"space-y-1",children:[u.length===0&&e.jsx("p",{className:`text-[10px] italic ${m?"text-gray-500":"text-gray-400"}`,children:"Empty array"}),u.map((c,d)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:x==="string"?"text":"number",value:c??"",onChange:w=>{const C=[...u];if(x==="string")C[d]=w.target.value;else{const E=x==="integer"?parseInt(w.target.value,10):parseFloat(w.target.value);C[d]=Number.isNaN(E)?w.target.value:E}f(C)},className:O(m)}),e.jsx("button",{type:"button",onClick:()=>f(u.filter((w,C)=>C!==d)),className:`px-2 py-1 text-xs rounded ${m?"bg-red-700 hover:bg-red-600 text-white":"bg-red-600 hover:bg-red-700 text-white"}`,children:"×"})]},d))]})]}):e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"[]"})]})}if(S==="object"||o.properties){const l=o.properties||{},x=new Set(Array.isArray(o.required)?o.required:[]),u=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return h>=2||Object.keys(l).length===0?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);d&&typeof d=="object"&&!Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"{}"})]}):e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-gray-600 bg-gray-800/40":"border-gray-200 bg-gray-50"}`,children:[t,i,Object.entries(l).map(([c,d])=>e.jsx(F,{name:c,schema:d,rootSchema:a,value:u[c],required:x.has(c),darkMode:m,depth:h+1,onChange:w=>f({...u,[c]:w})},c))]})}return o.format==="textarea"||o.maxLength>200||["query","current_query","message","prompt","content","text"].includes(n)?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:r??"",onChange:l=>f(l.target.value),rows:3,className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]}):e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"text",value:r??"",onChange:l=>f(l.target.value),className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]})},ae={type:"object",title:"Unspecified input",additionalProperties:!0,properties:{}},oe=({schema:n,value:g,onChange:a,onSubmit:r,darkMode:s=!1,showViewToggle:m=!0,disabled:h=!1,submitLabel:f,schemaSource:b,className:o=""})=>{const y=v.useMemo(()=>P(n||void 0)?ae:I(n,n),[n]),A=v.useMemo(()=>M(y,y),[y]),[J,N]=v.useState(()=>g!==void 0?g:A),[$,S]=v.useState("form"),[t,i]=v.useState(""),[j,l]=v.useState(null),[x,u]=v.useState(null),c=g!==void 0?g:J;v.useEffect(()=>{g===void 0&&N(A),i(JSON.stringify(g!==void 0?g:A,null,2)),l(null)},[y]),v.useEffect(()=>{$!=="raw"&&i(JSON.stringify(c,null,2))},[c,$]);const d=p=>{g===void 0&&N(p),a?.(p)},w=y.properties||{},C=new Set(Array.isArray(y.required)?y.required:[]),E=Object.entries(w),H=P(n||void 0),q=E.length===0&&!!(y.type&&y.type!=="object"),L=c&&typeof c=="object"&&!Array.isArray(c)?c:{},K=()=>{try{const p=JSON.parse(t);l(null),d(p)}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}},B=p=>{const R=ee(y,p,y);return R.length?(u(`Complete required field${R.length===1?"":"s"}: ${R.join(", ")}`),!1):(u(null),!0)};return e.jsxs("div",{className:`space-y-3 ${o}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:`text-sm font-semibold truncate ${s?"text-white":"text-gray-900"}`,children:y.title||"Input"}),b?.source&&e.jsxs("span",{className:`flex-shrink-0 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${b.source==="custom"?s?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":s?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${b.convention||b.source}`,children:[b.source==="custom"?"Custom schema":"Default schema",b.model?` · ${b.model}`:""]})]}),H&&!b?.source&&e.jsx("p",{className:`text-[10px] ${s?"text-amber-400":"text-amber-600"}`,children:"No input schema published — use Dict or Raw JSON for this operation"})]}),m&&e.jsx("div",{className:`inline-flex rounded-lg p-0.5 text-xs ${s?"bg-gray-700":"bg-gray-100"}`,children:["form","dict","raw"].map(p=>e.jsx("button",{type:"button",disabled:h||p==="dict"&&q,onClick:()=>{p==="raw"?(i(JSON.stringify(c,null,2)),l(null)):$==="raw"&&K(),S(p)},className:`px-2 py-1 rounded-md transition-colors ${$===p?s?"bg-gray-600 text-white":"bg-white text-gray-900 shadow-sm":s?"text-gray-300 hover:text-white":"text-gray-600 hover:text-gray-900"}`,children:p==="form"?"Form":p==="dict"?"Dict":"Raw JSON"},p))})]}),y.description&&e.jsx("p",{className:`text-xs ${s?"text-gray-400":"text-gray-500"}`,children:y.description}),$==="form"?e.jsx("div",{className:`space-y-3 max-h-96 overflow-y-auto pr-1 ${h?"opacity-60 pointer-events-none":""}`,children:q?e.jsx(F,{name:y.title||"value",schema:y,rootSchema:y,value:c,darkMode:s,onChange:d}):E.length===0?e.jsx("p",{className:`text-xs italic ${s?"text-gray-500":"text-gray-400"}`,children:"Schema has no properties to render."}):E.map(([p,R])=>e.jsx(F,{name:p,schema:R,rootSchema:y,value:L[p],required:C.has(p),darkMode:s,onChange:Q=>d({...L,[p]:Q})},p))}):$==="dict"&&!q?e.jsx(se,{value:L,onChange:d,schema:y,darkMode:s,disabled:h}):e.jsxs("div",{children:[e.jsx("textarea",{value:t,disabled:h,onChange:p=>{i(p.target.value),l(null)},onBlur:K,rows:12,className:`w-full px-2 py-2 text-xs font-mono border rounded ${s?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} ${j?"border-red-500":""}`,spellCheck:!1}),j&&e.jsx("p",{className:"mt-1 text-[10px] text-red-500",children:j})]}),f&&r&&e.jsx("button",{type:"button",disabled:h,onClick:()=>{if($==="raw"){try{const p=JSON.parse(t);l(null),d(p),B(p)&&r(p);return}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}return}B(c)&&r(c)},className:`w-full px-3 py-2 text-sm font-medium rounded-lg transition-colors ${s?"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-600":"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-300"}`,children:f}),x&&e.jsx("p",{role:"alert",className:"text-xs text-red-500",children:x})]})};export{oe as S}; +import{j as e,n as I,s as W,h as X,a as Y,k as Z,l as T,o as k,i as P,d as M,m as ee}from"./index-FSSL6O5F.js";import{r as v}from"./react-vendor-BHJ3EV8m.js";const D=()=>`row_${Math.random().toString(36).slice(2,10)}`;function te(n){if(n==null)return"string";if(Array.isArray(n))return"array";switch(typeof n){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"object"}}function U(n,g){const a=n?.properties;if(!a||typeof a!="object")return null;const s=I(a[g],n).type;return s==="string"||s==="number"||s==="integer"||s==="boolean"||s==="array"||s==="object"||s==="null"?s==="integer"?"number":s:null}function z(n){return!n||typeof n!="object"||Array.isArray(n)?[]:Object.entries(n).map(([g,a])=>{const r=te(a);return{id:D(),key:g,type:r,value:r==="object"||r==="array"||r==="null"?a==null?"null":JSON.stringify(a,null,2):String(a),error:null}})}function G(n){const g={};for(const a of n){const r=a.key.trim();if(r&&!a.error)switch(a.type){case"string":g[r]=a.value;break;case"number":{const s=a.value.trim()===""?0:Number(a.value);g[r]=Number.isNaN(s)?a.value:s;break}case"boolean":g[r]=a.value==="true";break;case"null":g[r]=null;break;case"object":case"array":{try{const s=JSON.parse(a.value);g[r]=s}catch{}break}}}return g}const V=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`;function re(n,g){let a=n,r=1;for(;g.has(a);)a=`${n}_${r++}`;return a}const se=({value:n,onChange:g,schema:a,darkMode:r=!1,disabled:s=!1,className:m=""})=>{const[h,f]=v.useState(()=>z(n)),b=t=>{f(t),g(G(t))},o=(t,i)=>{const j=h.map(l=>{if(l.id!==t)return l;const x={...l,...i};if(i.type==="object"||i.type==="array")try{JSON.parse(x.value),x.error=null}catch{x.error="Invalid JSON"}else x.error=null;return x});b(j)},y=()=>{const t="string",i=re(`field_${h.length+1}`,new Set(h.map(j=>j.key)));b([...h,{id:D(),key:i,type:t,value:"",error:null}])},A=t=>b(h.filter(i=>i.id!==t)),J=t=>t.type==="boolean"?e.jsx("input",{type:"checkbox",checked:t.value==="true",disabled:s,onChange:i=>o(t.id,{value:String(i.target.checked)}),className:"h-4 w-4 rounded border-gray-300"}):t.type==="null"?e.jsx("span",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"null"}):t.type==="object"||t.type==="array"?e.jsxs("div",{children:[e.jsx("textarea",{value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),rows:3,spellCheck:!1,placeholder:t.type==="array"?"[]":"{}",className:`${V(r)} font-mono ${t.error?"border-red-500":""}`}),t.error&&e.jsx("p",{className:"mt-0.5 text-[10px] text-red-500",children:t.error})]}):e.jsx("input",{type:t.type==="number"?"number":"text",value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),placeholder:t.type==="number"?"0":`Enter ${t.key||"value"}...`,className:V(r),step:t.type==="number"?"any":void 0}),N=v.useMemo(()=>JSON.stringify(n),[n]),[$,S]=v.useState(N);return N!==$&&(S(N),JSON.stringify(G(h))!==N&&f(z(n))),e.jsxs("div",{className:`space-y-2 ${m}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[10px] ${r?"text-gray-500":"text-gray-400"}`,children:"Generic dict — add any fields your agent accepts"}),e.jsx("button",{type:"button",disabled:s,onClick:y,className:`px-2 py-0.5 text-[10px] rounded ${r?"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-600":"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-300"}`,children:"+ Add field"})]}),h.length===0?e.jsx("p",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"No fields yet — click “Add field” to pass custom inputs."}):e.jsx("div",{className:"space-y-2",children:h.map(t=>e.jsx("div",{className:"flex items-start gap-1.5",children:e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",value:t.key,disabled:s,onChange:i=>o(t.id,{key:i.target.value}),placeholder:"field_name",className:`${V(r)} font-mono flex-1`}),e.jsxs("select",{value:t.type,disabled:s,onChange:i=>{const j=i.target.value;let l=t.value;if(j==="object"||j==="array")try{l=JSON.stringify(JSON.parse(t.value),null,2)}catch{l=j==="array"?"[]":"{}"}else j==="null"?l="null":t.type==="object"||t.type==="array"?l="":j==="boolean"&&(l=t.value==="true"?"true":"false");o(t.id,{type:j,value:l})},className:`${V(r)} w-24 flex-shrink-0`,children:[e.jsx("option",{value:"string",children:"string"}),e.jsx("option",{value:"number",children:"number"}),e.jsx("option",{value:"boolean",children:"boolean"}),e.jsx("option",{value:"object",children:"object"}),e.jsx("option",{value:"array",children:"array"}),e.jsx("option",{value:"null",children:"null"})]}),e.jsx("button",{type:"button",disabled:s,onClick:()=>A(t.id),title:"Remove field",className:`px-1.5 py-1 text-xs rounded ${r?"bg-red-700 hover:bg-red-600 text-white disabled:bg-gray-600":"bg-red-600 hover:bg-red-700 text-white disabled:bg-gray-300"}`,children:"×"})]}),e.jsx("div",{className:"pl-0",children:J(t)})]})},t.id))}),a&&e.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(a.properties||{}).filter(t=>!h.some(i=>i.key===t)).slice(0,8).map(t=>e.jsx(ne,{keyName:t,type:U(a,t),darkMode:r,disabled:s,onClick:()=>b([...h,{id:D(),key:t,type:U(a,t)||"string",value:"",error:null}])},t))})]})},ne=({keyName:n,type:g,darkMode:a,disabled:r,onClick:s})=>e.jsxs("button",{type:"button",disabled:r,onClick:s,className:`px-1.5 py-0.5 text-[10px] rounded border ${a?"border-gray-600 text-gray-400 hover:border-blue-500 hover:text-blue-300":"border-gray-200 text-gray-500 hover:border-blue-400 hover:text-blue-600"}`,children:["+ ",n,g?`:${g}`:""]}),O=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`,_=n=>`text-xs font-medium ${n?"text-gray-300":"text-gray-700"}`,F=({name:n,schema:g,rootSchema:a,value:r,required:s=!1,darkMode:m=!1,depth:h=0,onChange:f})=>{const b=v.useId(),o=I(g,a),y=W(g,a),[A,J]=v.useState(0);v.useEffect(()=>{J(l=>Math.min(l,Math.max(y.length-1,0)))},[y.length]);const N=X(n,o),$=typeof o.description=="string"?o.description:void 0,S=o.type||(o.properties?"object":"string"),t=e.jsx("div",{className:"flex items-center justify-between gap-2 mb-1",children:e.jsxs("label",{htmlFor:b,className:_(m),children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"}),e.jsx("span",{className:`ml-2 text-[10px] font-normal ${m?"text-gray-500":"text-gray-400"}`,children:String(S)})]})}),i=$?e.jsx("p",{className:`text-[10px] mb-1 ${m?"text-gray-500":"text-gray-400"}`,children:$}):null;if(y.length>0){const l=y[A]||y[0],x=(u,c)=>typeof u.title=="string"&&u.title?u.title:typeof u.$ref=="string"?u.$ref.split("/").at(-1)||`Option ${c+1}`:u.type?String(u.type):`Option ${c+1}`;return e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-violet-800/70 bg-violet-950/20":"border-violet-200 bg-violet-50/50"}`,children:[t,i,e.jsxs("label",{className:_(m),children:["Input shape",e.jsx("select",{value:A,onChange:u=>{const c=Number(u.target.value),d=y[c]||y[0];J(c),f(Y(d,a))},className:`${O(m)} mt-1`,children:y.map((u,c)=>e.jsx("option",{value:c,children:x(u,c)},`${x(u,c)}-${c}`))})]}),e.jsx(F,{name:n,schema:l,rootSchema:a,value:r,required:s,darkMode:m,depth:h,onChange:f})]})}if(Array.isArray(o.enum)&&o.enum.length>0){const l=Z(o.enum,r);return e.jsxs("div",{children:[t,i,e.jsxs("select",{id:b,value:l>=0?String(l):"",onChange:x=>f(k(o.enum,x.target.value)),className:O(m),children:[!s&&e.jsx("option",{value:"",children:"—"}),o.enum.map((x,u)=>e.jsx("option",{value:String(u),children:T(x)},`${T(x)}-${u}`))]})]})}if(o.const!==void 0)return e.jsxs("div",{children:[t,i,e.jsx("output",{"aria-label":`${N} fixed value`,className:`block w-full rounded border px-2 py-1.5 text-xs font-mono ${m?"border-gray-600 bg-gray-800 text-gray-300":"border-gray-300 bg-gray-50 text-gray-700"}`,children:T(o.const)})]});if(S==="boolean")return e.jsxs("div",{children:[e.jsxs("label",{className:`flex items-center gap-2 cursor-pointer ${_(m)}`,children:[e.jsx("input",{type:"checkbox",checked:!!r,onChange:l=>f(l.target.checked),className:"rounded border-gray-300"}),e.jsxs("span",{children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]})]}),i]});if(S==="number"||S==="integer")return e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"number",step:S==="integer"?1:"any",value:r??"",onChange:l=>{const x=l.target.value;if(x===""){f(void 0);return}const u=S==="integer"?parseInt(x,10):parseFloat(x);f(Number.isNaN(u)?x:u)},className:O(m),placeholder:o.examples?.[0]!=null?String(o.examples[0]):N})]});if(S==="array"){const x=I(o.items||{type:"string"},a).type||"string",u=Array.isArray(r)?r:[];return x==="string"||x==="number"||x==="integer"?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t,e.jsx("button",{type:"button",onClick:()=>f([...u,x==="string"?"":0]),className:"px-2 py-0.5 text-[10px] rounded bg-blue-600 hover:bg-blue-700 text-white",children:"+ Add"})]}),i,e.jsxs("div",{className:"space-y-1",children:[u.length===0&&e.jsx("p",{className:`text-[10px] italic ${m?"text-gray-500":"text-gray-400"}`,children:"Empty array"}),u.map((c,d)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:x==="string"?"text":"number",value:c??"",onChange:w=>{const C=[...u];if(x==="string")C[d]=w.target.value;else{const E=x==="integer"?parseInt(w.target.value,10):parseFloat(w.target.value);C[d]=Number.isNaN(E)?w.target.value:E}f(C)},className:O(m)}),e.jsx("button",{type:"button",onClick:()=>f(u.filter((w,C)=>C!==d)),className:`px-2 py-1 text-xs rounded ${m?"bg-red-700 hover:bg-red-600 text-white":"bg-red-600 hover:bg-red-700 text-white"}`,children:"×"})]},d))]})]}):e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"[]"})]})}if(S==="object"||o.properties){const l=o.properties||{},x=new Set(Array.isArray(o.required)?o.required:[]),u=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return h>=2||Object.keys(l).length===0?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);d&&typeof d=="object"&&!Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"{}"})]}):e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-gray-600 bg-gray-800/40":"border-gray-200 bg-gray-50"}`,children:[t,i,Object.entries(l).map(([c,d])=>e.jsx(F,{name:c,schema:d,rootSchema:a,value:u[c],required:x.has(c),darkMode:m,depth:h+1,onChange:w=>f({...u,[c]:w})},c))]})}return o.format==="textarea"||o.maxLength>200||["query","current_query","message","prompt","content","text"].includes(n)?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:r??"",onChange:l=>f(l.target.value),rows:3,className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]}):e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"text",value:r??"",onChange:l=>f(l.target.value),className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]})},ae={type:"object",title:"Unspecified input",additionalProperties:!0,properties:{}},oe=({schema:n,value:g,onChange:a,onSubmit:r,darkMode:s=!1,showViewToggle:m=!0,disabled:h=!1,submitLabel:f,schemaSource:b,className:o=""})=>{const y=v.useMemo(()=>P(n||void 0)?ae:I(n,n),[n]),A=v.useMemo(()=>M(y,y),[y]),[J,N]=v.useState(()=>g!==void 0?g:A),[$,S]=v.useState("form"),[t,i]=v.useState(""),[j,l]=v.useState(null),[x,u]=v.useState(null),c=g!==void 0?g:J;v.useEffect(()=>{g===void 0&&N(A),i(JSON.stringify(g!==void 0?g:A,null,2)),l(null)},[y]),v.useEffect(()=>{$!=="raw"&&i(JSON.stringify(c,null,2))},[c,$]);const d=p=>{g===void 0&&N(p),a?.(p)},w=y.properties||{},C=new Set(Array.isArray(y.required)?y.required:[]),E=Object.entries(w),H=P(n||void 0),q=E.length===0&&!!(y.type&&y.type!=="object"),L=c&&typeof c=="object"&&!Array.isArray(c)?c:{},K=()=>{try{const p=JSON.parse(t);l(null),d(p)}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}},B=p=>{const R=ee(y,p,y);return R.length?(u(`Complete required field${R.length===1?"":"s"}: ${R.join(", ")}`),!1):(u(null),!0)};return e.jsxs("div",{className:`space-y-3 ${o}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:`text-sm font-semibold truncate ${s?"text-white":"text-gray-900"}`,children:y.title||"Input"}),b?.source&&e.jsxs("span",{className:`flex-shrink-0 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${b.source==="custom"?s?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":s?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${b.convention||b.source}`,children:[b.source==="custom"?"Custom schema":"Default schema",b.model?` · ${b.model}`:""]})]}),H&&!b?.source&&e.jsx("p",{className:`text-[10px] ${s?"text-amber-400":"text-amber-600"}`,children:"No input schema published — use Dict or Raw JSON for this operation"})]}),m&&e.jsx("div",{className:`inline-flex rounded-lg p-0.5 text-xs ${s?"bg-gray-700":"bg-gray-100"}`,children:["form","dict","raw"].map(p=>e.jsx("button",{type:"button",disabled:h||p==="dict"&&q,onClick:()=>{p==="raw"?(i(JSON.stringify(c,null,2)),l(null)):$==="raw"&&K(),S(p)},className:`px-2 py-1 rounded-md transition-colors ${$===p?s?"bg-gray-600 text-white":"bg-white text-gray-900 shadow-sm":s?"text-gray-300 hover:text-white":"text-gray-600 hover:text-gray-900"}`,children:p==="form"?"Form":p==="dict"?"Dict":"Raw JSON"},p))})]}),y.description&&e.jsx("p",{className:`text-xs ${s?"text-gray-400":"text-gray-500"}`,children:y.description}),$==="form"?e.jsx("div",{className:`space-y-3 max-h-96 overflow-y-auto pr-1 ${h?"opacity-60 pointer-events-none":""}`,children:q?e.jsx(F,{name:y.title||"value",schema:y,rootSchema:y,value:c,darkMode:s,onChange:d}):E.length===0?e.jsx("p",{className:`text-xs italic ${s?"text-gray-500":"text-gray-400"}`,children:"Schema has no properties to render."}):E.map(([p,R])=>e.jsx(F,{name:p,schema:R,rootSchema:y,value:L[p],required:C.has(p),darkMode:s,onChange:Q=>d({...L,[p]:Q})},p))}):$==="dict"&&!q?e.jsx(se,{value:L,onChange:d,schema:y,darkMode:s,disabled:h}):e.jsxs("div",{children:[e.jsx("textarea",{value:t,disabled:h,onChange:p=>{i(p.target.value),l(null)},onBlur:K,rows:12,className:`w-full px-2 py-2 text-xs font-mono border rounded ${s?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} ${j?"border-red-500":""}`,spellCheck:!1}),j&&e.jsx("p",{className:"mt-1 text-[10px] text-red-500",children:j})]}),f&&r&&e.jsx("button",{type:"button",disabled:h,onClick:()=>{if($==="raw"){try{const p=JSON.parse(t);l(null),d(p),B(p)&&r(p);return}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}return}B(c)&&r(c)},className:`w-full px-3 py-2 text-sm font-medium rounded-lg transition-colors ${s?"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-600":"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-300"}`,children:f}),x&&e.jsx("p",{role:"alert",className:"text-xs text-red-500",children:x})]})};export{oe as S}; diff --git a/src/agentomatic/studio/static/assets/TasksView-HJeIPOTt.js b/src/agentomatic/studio/static/assets/TasksView-DAoR0f0z.js similarity index 98% rename from src/agentomatic/studio/static/assets/TasksView-HJeIPOTt.js rename to src/agentomatic/studio/static/assets/TasksView-DAoR0f0z.js index 5de03759..24c8f486 100644 --- a/src/agentomatic/studio/static/assets/TasksView-HJeIPOTt.js +++ b/src/agentomatic/studio/static/assets/TasksView-DAoR0f0z.js @@ -1,3 +1,3 @@ -import{u as le,A as ie,j as e,d as oe,m as z}from"./index-A2k5j4o2.js";import{r as l}from"./react-vendor-BHJ3EV8m.js";import{S as de}from"./SchemaForm-bIikrW9E.js";import{O as ce}from"./OutputSchemaSummary-DzWXQCQ1.js";import"./syntax-vendor-ru7AzRyY.js";const me=["agent","plugin","pipeline","endpoint","ingestion"],L=new Set(["succeeded","failed","cancelled"]),ue={agent:[],plugin:[],pipeline:[],endpoint:[],ingestion:[]},B=p=>({agent:"Agent",plugin:"Plugin",pipeline:"Pipeline",endpoint:"Endpoint",ingestion:"Ingestor"})[p],pe=p=>p?new Date(p*1e3).toLocaleTimeString():"—",ge=(p,a)=>(a?{queued:"bg-amber-900/60 text-amber-200",running:"bg-blue-900/60 text-blue-200",succeeded:"bg-emerald-900/60 text-emerald-200",failed:"bg-red-900/60 text-red-200",cancelled:"bg-gray-700 text-gray-200"}:{queued:"bg-amber-100 text-amber-800",running:"bg-blue-100 text-blue-800",succeeded:"bg-emerald-100 text-emerald-800",failed:"bg-red-100 text-red-800",cancelled:"bg-gray-200 text-gray-700"})[p],ve=()=>{const{config:p,darkMode:a}=le(),[f,H]=l.useState(ue),[Q,X]=l.useState({}),[Z,T]=l.useState({}),[k,F]=l.useState(!1),[w,P]=l.useState([]),[m,ee]=l.useState("agent"),[i,E]=l.useState(""),[$,S]=l.useState({}),[h,te]=l.useState("async"),[U,R]=l.useState(`[ +import{u as le,A as ie,j as e,d as oe,m as z}from"./index-FSSL6O5F.js";import{r as l}from"./react-vendor-BHJ3EV8m.js";import{S as de}from"./SchemaForm-DyHc2s7z.js";import{O as ce}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const me=["agent","plugin","pipeline","endpoint","ingestion"],L=new Set(["succeeded","failed","cancelled"]),ue={agent:[],plugin:[],pipeline:[],endpoint:[],ingestion:[]},B=p=>({agent:"Agent",plugin:"Plugin",pipeline:"Pipeline",endpoint:"Endpoint",ingestion:"Ingestor"})[p],pe=p=>p?new Date(p*1e3).toLocaleTimeString():"—",ge=(p,a)=>(a?{queued:"bg-amber-900/60 text-amber-200",running:"bg-blue-900/60 text-blue-200",succeeded:"bg-emerald-900/60 text-emerald-200",failed:"bg-red-900/60 text-red-200",cancelled:"bg-gray-700 text-gray-200"}:{queued:"bg-amber-100 text-amber-800",running:"bg-blue-100 text-blue-800",succeeded:"bg-emerald-100 text-emerald-800",failed:"bg-red-100 text-red-800",cancelled:"bg-gray-200 text-gray-700"})[p],ve=()=>{const{config:p,darkMode:a}=le(),[f,H]=l.useState(ue),[Q,X]=l.useState({}),[Z,T]=l.useState({}),[k,F]=l.useState(!1),[w,P]=l.useState([]),[m,ee]=l.useState("agent"),[i,E]=l.useState(""),[$,S]=l.useState({}),[h,te]=l.useState("async"),[U,R]=l.useState(`[ {} ]`),[J,se]=l.useState(!1),[M,q]=l.useState(!0),[_,D]=l.useState(!1),[C,K]=l.useState(null),[V,x]=l.useState(null),[b,I]=l.useState(null),r=l.useMemo(()=>p?.apiUrl?new ie(p.apiUrl,p.apiKey||void 0):null,[p?.apiKey,p?.apiUrl]),y=`${m}:${i}`,v=Q[y],O=Z[y],A=!!(i&&v&&!k&&!O),j=l.useCallback(async(t=!1)=>{if(r)try{const d=await r.listTasks({limit:100});P(d.tasks),I(s=>s&&d.tasks.find(o=>o.id===s.id)||null),t||x(null)}catch(d){t||x(d?.message||"Failed to load task board")}},[r]);l.useEffect(()=>{if(!r)return;let t=!0;return(async()=>{q(!0);try{const[s,o,c,g,N]=await Promise.all([r.listAgents(),r.listPlugins(),r.listPipelines(),r.listEndpoints(),r.listIngestors()]);if(!t)return;const Y={agent:s.map(n=>({name:n.name,label:n.description||n.name})),plugin:o.map(n=>({name:n.name,label:n.description||n.name})),pipeline:c.map(n=>({name:n.name,label:n.description||n.name})),endpoint:g.map(n=>({name:n.name,label:n.description||n.name})),ingestion:N.map(n=>({name:n.name,label:n.description||n.name}))};H(Y),E(n=>n||Y.agent[0]?.name||""),x(null),await j()}catch(s){t&&x(s?.message||"Failed to discover platform resources")}finally{t&&q(!1)}})(),()=>{t=!1}},[r,j]),l.useEffect(()=>{if(!r||!i)return;let t=!0;return(async()=>{F(!0),T(s=>{const o={...s};return delete o[y],o});try{let s=null;if(m==="agent"){const c=await r.getSchemas(i);s={input_schema:c.input_schema,output_schema:c.output_schema,method:"POST",path:`/api/v1/${i}/invoke`}}else{const c=m==="plugin"?`/api/v1/plugins/${encodeURIComponent(i)}/predict`:m==="pipeline"?`/api/v1/pipelines/${encodeURIComponent(i)}/run`:m==="endpoint"?f.endpoint.find(g=>g.name===i)?.name?`/api/v1/endpoints/${encodeURIComponent(i)}`:"":`/api/v1/ingestion/${encodeURIComponent(i)}/run`;if(m==="endpoint"){const g=(await r.listEndpoints()).find(N=>N.name===i);g?.path&&(s=await r.getEndpointContract(g))}else c&&(s=await r.getOperationContract(c),m==="pipeline"&&s.input_schema?.properties?.input&&(s={...s,input_schema:s.input_schema.properties.input}))}if(!t||!s)return;X(c=>({...c,[y]:s}));const o=oe(s.input_schema||void 0);S(o),R(JSON.stringify([o],null,2)),T(c=>{const g={...c};return delete g[y],g})}catch(s){if(t){const o=s?.message||`Failed to load the input contract for '${i}'`;T(c=>({...c,[y]:o})),x(o)}}finally{t&&F(!1)}})(),()=>{t=!1}},[r,y,f.endpoint,i,m]),l.useEffect(()=>{if(!w.some(d=>!L.has(d.status)))return;const t=window.setInterval(()=>{j(!0)},1500);return()=>window.clearInterval(t)},[j,w]);const ae=t=>{ee(t),E(f[t][0]?.name||""),S({})},re=()=>{R(JSON.stringify([$],null,2))},ne=async()=>{if(!(!r||!i)){D(!0),x(null);try{let t;if(h==="batch"){const s=JSON.parse(U);if(!Array.isArray(s)||s.length===0)throw new Error("Batch input must be a non-empty JSON array.");const o=s.flatMap((c,g)=>z(v?.input_schema||void 0,c).map(N=>`item ${g+1}: ${N}`));if(o.length)throw new Error(`Complete required field${o.length===1?"":"s"}: ${o.join(", ")}`);t=s}else{const s=z(v?.input_schema||void 0,$);if(s.length)throw new Error(`Complete required field${s.length===1?"":"s"}: ${s.join(", ")}`)}const d=await r.submitTask({target_type:m,target:i,input:h==="batch"?void 0:$,batch:t,mode:h==="sync"?"sync":"async",wait:h==="sync",retry:J?{max_attempts:3,backoff:"exponential",base_delay:1}:void 0});P(s=>[d,...s.filter(o=>o.id!==d.id)]),I(d)}catch(t){x(t?.message||"Task submission failed")}finally{D(!1)}}},G=async(t,d)=>{if(r){K(`${d}:${t.id}`),x(null);try{d==="cancel"?await r.cancelTask(t.id):await r.deleteTask(t.id),await j()}catch(s){x(s?.message||`Could not ${d} task`)}finally{K(null)}}},W=a?"border-gray-700 bg-gray-800":"border-gray-200 bg-white",u=a?"text-gray-400":"text-gray-600";return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${a?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-col justify-between gap-3 sm:flex-row sm:items-start",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Task Board"}),e.jsx("p",{className:`mt-1 max-w-3xl text-sm ${u}`,children:"Submit real platform work, inspect its durable progress, and safely cancel or remove completed records. Inputs are generated from the deployed resource contract."})]}),e.jsx("button",{type:"button",onClick:()=>{j()},className:`self-start rounded-lg border px-3 py-2 text-sm font-medium ${a?"border-gray-600 hover:bg-gray-700":"border-gray-300 hover:bg-gray-100"}`,children:"Refresh"})]}),V&&e.jsx("div",{role:"alert",className:`mb-5 rounded-lg border p-3 text-sm ${a?"border-red-800 bg-red-950/50 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:V}),M&&e.jsx("p",{className:u,children:"Discovering live resources and task records…"}),!M&&e.jsxs("div",{className:"grid grid-cols-1 gap-6 2xl:grid-cols-[minmax(26rem,0.85fr)_minmax(32rem,1.15fr)]",children:[e.jsxs("section",{className:`rounded-xl border p-4 shadow-sm sm:p-5 ${W}`,children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Submit work"}),e.jsx("p",{className:`mt-1 text-xs ${u}`,children:"Choose the real resource first; its published request schema appears below."}),e.jsxs("div",{className:"mt-5 grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-sm font-medium",children:["Resource type",e.jsx("select",{value:m,onChange:t=>ae(t.target.value),className:`mt-1 block w-full rounded-lg border p-2.5 ${a?"border-gray-600 bg-gray-900":"border-gray-300 bg-white"}`,children:me.map(t=>e.jsx("option",{value:t,children:B(t)},t))})]}),e.jsxs("label",{className:"text-sm font-medium",children:["Resource",e.jsxs("select",{value:i,onChange:t=>{E(t.target.value),S({})},disabled:!f[m].length,className:`mt-1 block w-full rounded-lg border p-2.5 disabled:opacity-50 ${a?"border-gray-600 bg-gray-900":"border-gray-300 bg-white"}`,children:[!f[m].length&&e.jsxs("option",{value:"",children:["No live ",B(m).toLowerCase()," available"]}),f[m].map(t=>e.jsx("option",{value:t.name,children:t.name},t.name))]})]})]}),i&&e.jsxs("p",{className:`mt-2 text-xs ${u}`,children:["Target: ",e.jsx("code",{children:i})," · ",v?.method||"POST"," ",v?.path||(k?"Loading contract…":"Contract unavailable")]}),i&&k&&e.jsx("p",{role:"status",className:`mt-2 text-xs ${u}`,children:"Reading the deployed input contract before enabling execution…"}),i&&O&&e.jsxs("p",{role:"status",className:`mt-2 rounded-md border p-2 text-xs ${a?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live input contract unavailable: ",O,". Submission stays disabled until it can be read."]}),e.jsxs("div",{className:`mt-4 border-t pt-4 ${a?"border-gray-700":"border-gray-200"}`,children:[e.jsx(de,{schema:v?.input_schema,value:$,onChange:S,darkMode:a,submitLabel:void 0,disabled:!A||_}),e.jsx(ce,{schema:v?.output_schema,darkMode:a,className:"mt-3"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-sm font-medium",children:["Execution mode",e.jsxs("select",{value:h,onChange:t=>te(t.target.value),className:`mt-1 block w-full rounded-lg border p-2.5 ${a?"border-gray-600 bg-gray-900":"border-gray-300 bg-white"}`,children:[e.jsx("option",{value:"async",children:"Async (tracked)"}),e.jsx("option",{value:"sync",children:"Sync (wait for result)"}),e.jsx("option",{value:"batch",children:"Batch (tracked)"})]})]}),e.jsxs("label",{className:`flex items-center gap-2 pt-6 text-sm ${u}`,children:[e.jsx("input",{type:"checkbox",checked:J,onChange:t=>se(t.target.checked)})," Retry failed work up to 3 times"]})]}),h==="batch"&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("label",{className:"block text-sm font-medium",children:["Batch payloads ",e.jsx("span",{className:u,children:"(non-empty JSON array)"})]}),e.jsx("button",{type:"button",onClick:re,disabled:!A,className:`rounded-md border px-2.5 py-1.5 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-700":"border-gray-300 hover:bg-gray-100"}`,children:"Use current form as first item"})]}),e.jsx("p",{className:`mt-1 text-xs ${u}`,children:"The first item is generated from this resource’s live input schema; duplicate or edit it to create the batch. Items may be objects, arrays, or scalar JSON values when that is what the selected resource publishes."}),e.jsx("textarea",{"aria-label":"Batch payloads",value:U,onChange:t=>R(t.target.value),rows:7,spellCheck:!1,className:`mt-2 block w-full rounded-lg border p-3 font-mono text-xs ${a?"border-gray-600 bg-gray-950":"border-gray-300 bg-gray-50"}`})]}),e.jsx("button",{type:"button",disabled:!A||_,onClick:()=>{ne()},className:"mt-5 w-full rounded-lg bg-violet-600 px-4 py-3 text-sm font-semibold text-white hover:bg-violet-700 disabled:cursor-not-allowed disabled:opacity-50",children:_?"Submitting…":h==="sync"?"Run and wait for result":h==="batch"?"Submit batch task":"Submit tracked task"})]}),e.jsxs("section",{className:`rounded-xl border shadow-sm ${W}`,children:[e.jsx("div",{className:`flex flex-wrap items-center justify-between gap-2 border-b p-4 sm:p-5 ${a?"border-gray-700":"border-gray-200"}`,children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Live tasks"}),e.jsxs("p",{className:`text-xs ${u}`,children:[w.length," most recent records · active records refresh every 1.5 seconds"]})]})}),w.length===0?e.jsx("p",{className:`p-5 text-sm ${u}`,children:"No tasks have been submitted from this deployment."}):e.jsx("div",{className:"divide-y overflow-x-auto divide-gray-200 dark:divide-gray-700",children:w.map(t=>e.jsxs("article",{className:`min-w-0 p-4 transition-colors ${b?.id===t.id?a?"bg-violet-950/25":"bg-violet-50/60":""}`,children:[e.jsxs("div",{className:"flex flex-col items-start justify-between gap-3 sm:flex-row",children:[e.jsxs("button",{type:"button",onClick:()=>I(t),className:"min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-semibold",children:t.target}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${ge(t.status,a)}`,children:t.status})]}),e.jsxs("p",{className:`mt-1 text-xs ${u}`,children:[B(t.target_type)," · ",t.mode," · started ",pe(t.started_at||t.created_at)]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!L.has(t.status)&&e.jsx("button",{type:"button",onClick:()=>{G(t,"cancel")},disabled:C!==null,className:"rounded border border-amber-400 px-2 py-1 text-xs text-amber-700 hover:bg-amber-50 disabled:opacity-50 dark:text-amber-300 dark:hover:bg-amber-950",children:C===`cancel:${t.id}`?"Cancelling…":"Cancel"}),L.has(t.status)&&e.jsx("button",{type:"button",onClick:()=>{G(t,"delete")},disabled:C!==null,className:`rounded border px-2 py-1 text-xs disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-700":"border-gray-300 hover:bg-gray-100"}`,children:C===`delete:${t.id}`?"Removing…":"Remove"})]})]}),(t.progress.message||t.progress.percent!==null)&&e.jsxs("div",{className:`mt-3 text-xs ${u}`,children:[e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t.progress.stage||t.progress.message||"Working"}),e.jsx("span",{children:t.progress.percent===null?"In progress":`${Math.round(t.progress.percent)}%`})]}),e.jsx("div",{className:`mt-1 h-1.5 overflow-hidden rounded-full ${a?"bg-gray-700":"bg-gray-200"}`,children:e.jsx("div",{className:"h-full bg-violet-500 transition-all",style:{width:`${t.progress.percent??8}%`}})})]}),t.error&&e.jsx("p",{className:"mt-2 rounded bg-red-50 p-2 text-xs text-red-700 dark:bg-red-950/40 dark:text-red-200",children:t.error})]},t.id))}),b&&e.jsxs("div",{className:`border-t p-4 sm:p-5 ${a?"border-gray-700 bg-gray-950/35":"border-gray-100 bg-gray-50/70"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold",children:"Task detail"}),e.jsx("code",{className:`max-w-full truncate text-xs ${u}`,children:b.id})]}),e.jsxs("div",{className:`mt-2 grid grid-cols-2 gap-2 text-xs ${u}`,children:[e.jsxs("span",{children:["Attempts: ",b.attempts]}),e.jsxs("span",{children:["Duration: ",b.duration_ms===null?"—":`${Math.round(b.duration_ms)} ms`]})]}),e.jsx("pre",{className:`mt-3 max-h-64 overflow-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${a?"bg-gray-950 text-gray-200":"bg-white text-gray-800"}`,children:JSON.stringify(b.error?{error:b.error}:b.result??b.input,null,2)})]})]})]})]})};export{ve as TasksView}; diff --git a/src/agentomatic/studio/static/assets/index-A2k5j4o2.js b/src/agentomatic/studio/static/assets/index-A2k5j4o2.js deleted file mode 100644 index b5048f2a..00000000 --- a/src/agentomatic/studio/static/assets/index-A2k5j4o2.js +++ /dev/null @@ -1,197 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GraphView-bgnAIRJp.js","assets/react-vendor-BHJ3EV8m.js","assets/SchemaForm-bIikrW9E.js","assets/OutputSchemaSummary-DzWXQCQ1.js","assets/syntax-vendor-ru7AzRyY.js","assets/ChatView-SPDbgpwb.js","assets/ClipboardDocumentIcon-Cnz7XqGa.js","assets/DebugView-v__T__mW.js","assets/PipelinesView-8o6MHHuZ.js","assets/BuilderView-Aw10hiXI.js","assets/ui-vendor-DIaV1y77.js","assets/PluginsView-T_czY3dU.js","assets/IngestorsView-q0ceZCW0.js","assets/TasksView-HJeIPOTt.js","assets/ControlPlaneView-ba4D_JM4.js","assets/EndpointsView-uQLIFHRE.js","assets/ConnectionsView-wfIgs5wX.js"])))=>i.map(i=>d[i]); -import{a as Qe,b as Dt,g as St,r as h,R as z,c as Mt,u as Pt,B as It,d as Lt,e as Re,N as et}from"./react-vendor-BHJ3EV8m.js";import{_ as Et,a as K}from"./syntax-vendor-ru7AzRyY.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function t(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=t(a);fetch(a.href,o)}})();var De={exports:{}},fe={};var tt;function Ut(){if(tt)return fe;tt=1;var r=Qe(),e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,a=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function s(i,l,d){var u,m={},p=null,y=null;d!==void 0&&(p=""+d),l.key!==void 0&&(p=""+l.key),l.ref!==void 0&&(y=l.ref);for(u in l)n.call(l,u)&&!o.hasOwnProperty(u)&&(m[u]=l[u]);if(i&&i.defaultProps)for(u in l=i.defaultProps,l)m[u]===void 0&&(m[u]=l[u]);return{$$typeof:e,type:i,key:p,ref:y,props:m,_owner:a.current}}return fe.Fragment=t,fe.jsx=s,fe.jsxs=s,fe}var rt;function qt(){return rt||(rt=1,De.exports=Ut()),De.exports}var c=qt(),we={},nt;function Vt(){if(nt)return we;nt=1;var r=Dt();return we.createRoot=r.createRoot,we.hydrateRoot=r.hydrateRoot,we}var Wt=Vt();const Ft=St(Wt);let Bt={data:""},zt=r=>typeof window=="object"?((r?r.querySelector("#_goober"):window._goober)||Object.assign((r||document.head).appendChild(document.createElement("style")),{innerHTML:" ",id:"_goober"})).firstChild:r||Bt,Yt=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,Ht=/\/\*[^]*?\*\/| +/g,at=/\n+/g,re=(r,e)=>{let t="",n="",a="";for(let o in r){let s=r[o];o[0]=="@"?o[1]=="i"?t=o+" "+s+";":n+=o[1]=="f"?re(s,o):o+"{"+re(s,o[1]=="k"?"":e)+"}":typeof s=="object"?n+=re(s,e?e.replace(/([^,])+/g,i=>o.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,l=>/&/.test(l)?l.replace(/&/g,i):i?i+" "+l:l)):o):s!=null&&(o=/^--/.test(o)?o:o.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=re.p?re.p(o,s):o+":"+s+";")}return t+(e&&a?e+"{"+a+"}":a)+n},Z={},kt=r=>{if(typeof r=="object"){let e="";for(let t in r)e+=t+kt(r[t]);return e}return r},Gt=(r,e,t,n,a)=>{let o=kt(r),s=Z[o]||(Z[o]=(l=>{let d=0,u=11;for(;d>>0;return"go"+u})(o));if(!Z[s]){let l=o!==r?r:(d=>{let u,m,p=[{}];for(;u=Yt.exec(d.replace(Ht,""));)u[4]?p.shift():u[3]?(m=u[3].replace(at," ").trim(),p.unshift(p[0][m]=p[0][m]||{})):p[0][u[1]]=u[2].replace(at," ").trim();return p[0]})(r);Z[s]=re(a?{["@keyframes "+s]:l}:l,t?"":"."+s)}let i=t&&Z.g?Z.g:null;return t&&(Z.g=Z[s]),((l,d,u,m)=>{m?d.data=d.data.replace(m,l):d.data.indexOf(l)===-1&&(d.data=u?l+d.data:d.data+l)})(Z[s],e,n,i),s},Kt=(r,e,t)=>r.reduce((n,a,o)=>{let s=e[o];if(s&&s.call){let i=s(t),l=i&&i.props&&i.props.className||/^go/.test(i)&&i;s=l?"."+l:i&&typeof i=="object"?i.props?"":re(i,""):i===!1?"":i}return n+a+(s??"")},"");function $e(r){let e=this||{},t=r.call?r(e.p):r;return Gt(t.unshift?t.raw?Kt(t,[].slice.call(arguments,1),e.p):t.reduce((n,a)=>Object.assign(n,a&&a.call?a(e.p):a),{}):t,zt(e.target),e.g,e.o,e.k)}let Tt,He,Ge;$e.bind({g:1});let ee=$e.bind({k:1});function Jt(r,e,t,n){re.p=e,Tt=r,He=t,Ge=n}function ne(r,e){let t=this||{};return function(){let n=arguments;function a(o,s){let i=Object.assign({},o),l=i.className||a.className;t.p=Object.assign({theme:He&&He()},i),t.o=/ *go\d+/.test(l),i.className=$e.apply(t,n)+(l?" "+l:"");let d=r;return r[0]&&(d=i.as||r,delete i.as),Ge&&d[0]&&Ge(i),Tt(d,i)}return a}}var Xt=r=>typeof r=="function",Te=(r,e)=>Xt(r)?r(e):r,Qt=(()=>{let r=0;return()=>(++r).toString()})(),At=(()=>{let r;return()=>{if(r===void 0&&typeof window<"u"){let e=matchMedia("(prefers-reduced-motion: reduce)");r=!e||e.matches}return r}})(),Zt=20,jt=(r,e)=>{switch(e.type){case 0:return{...r,toasts:[e.toast,...r.toasts].slice(0,Zt)};case 1:return{...r,toasts:r.toasts.map(o=>o.id===e.toast.id?{...o,...e.toast}:o)};case 2:let{toast:t}=e;return jt(r,{type:r.toasts.find(o=>o.id===t.id)?1:0,toast:t});case 3:let{toastId:n}=e;return{...r,toasts:r.toasts.map(o=>o.id===n||n===void 0?{...o,dismissed:!0,visible:!1}:o)};case 4:return e.toastId===void 0?{...r,toasts:[]}:{...r,toasts:r.toasts.filter(o=>o.id!==e.toastId)};case 5:return{...r,pausedAt:e.time};case 6:let a=e.time-(r.pausedAt||0);return{...r,pausedAt:void 0,toasts:r.toasts.map(o=>({...o,pauseDuration:o.pauseDuration+a}))}}},ke=[],ie={toasts:[],pausedAt:void 0},de=r=>{ie=jt(ie,r),ke.forEach(e=>{e(ie)})},er={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},tr=(r={})=>{let[e,t]=h.useState(ie),n=h.useRef(ie);h.useEffect(()=>(n.current!==ie&&t(ie),ke.push(t),()=>{let o=ke.indexOf(t);o>-1&&ke.splice(o,1)}),[]);let a=e.toasts.map(o=>{var s,i,l;return{...r,...r[o.type],...o,removeDelay:o.removeDelay||((s=r[o.type])==null?void 0:s.removeDelay)||r?.removeDelay,duration:o.duration||((i=r[o.type])==null?void 0:i.duration)||r?.duration||er[o.type],style:{...r.style,...(l=r[o.type])==null?void 0:l.style,...o.style}}});return{...e,toasts:a}},rr=(r,e="blank",t)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:e,ariaProps:{role:"status","aria-live":"polite"},message:r,pauseDuration:0,...t,id:t?.id||Qt()}),be=r=>(e,t)=>{let n=rr(e,r,t);return de({type:2,toast:n}),n.id},F=(r,e)=>be("blank")(r,e);F.error=be("error");F.success=be("success");F.loading=be("loading");F.custom=be("custom");F.dismiss=r=>{de({type:3,toastId:r})};F.remove=r=>de({type:4,toastId:r});F.promise=(r,e,t)=>{let n=F.loading(e.loading,{...t,...t?.loading});return typeof r=="function"&&(r=r()),r.then(a=>{let o=e.success?Te(e.success,a):void 0;return o?F.success(o,{id:n,...t,...t?.success}):F.dismiss(n),a}).catch(a=>{let o=e.error?Te(e.error,a):void 0;o?F.error(o,{id:n,...t,...t?.error}):F.dismiss(n)}),r};var nr=(r,e)=>{de({type:1,toast:{id:r,height:e}})},ar=()=>{de({type:5,time:Date.now()})},xe=new Map,or=1e3,sr=(r,e=or)=>{if(xe.has(r))return;let t=setTimeout(()=>{xe.delete(r),de({type:4,toastId:r})},e);xe.set(r,t)},ir=r=>{let{toasts:e,pausedAt:t}=tr(r);h.useEffect(()=>{if(t)return;let o=Date.now(),s=e.map(i=>{if(i.duration===1/0)return;let l=(i.duration||0)+i.pauseDuration-(o-i.createdAt);if(l<0){i.visible&&F.dismiss(i.id);return}return setTimeout(()=>F.dismiss(i.id),l)});return()=>{s.forEach(i=>i&&clearTimeout(i))}},[e,t]);let n=h.useCallback(()=>{t&&de({type:6,time:Date.now()})},[t]),a=h.useCallback((o,s)=>{let{reverseOrder:i=!1,gutter:l=8,defaultPosition:d}=s||{},u=e.filter(y=>(y.position||d)===(o.position||d)&&y.height),m=u.findIndex(y=>y.id===o.id),p=u.filter((y,b)=>by.visible).slice(...i?[p+1]:[0,p]).reduce((y,b)=>y+(b.height||0)+l,0)},[e]);return h.useEffect(()=>{e.forEach(o=>{if(o.dismissed)sr(o.id,o.removeDelay);else{let s=xe.get(o.id);s&&(clearTimeout(s),xe.delete(o.id))}})},[e]),{toasts:e,handlers:{updateHeight:nr,startPause:ar,endPause:n,calculateOffset:a}}},cr=ee` -from { - transform: scale(0) rotate(45deg); - opacity: 0; -} -to { - transform: scale(1) rotate(45deg); - opacity: 1; -}`,dr=ee` -from { - transform: scale(0); - opacity: 0; -} -to { - transform: scale(1); - opacity: 1; -}`,lr=ee` -from { - transform: scale(0) rotate(90deg); - opacity: 0; -} -to { - transform: scale(1) rotate(90deg); - opacity: 1; -}`,ur=ne("div")` - width: 20px; - opacity: 0; - height: 20px; - border-radius: 10px; - background: ${r=>r.primary||"#ff4b4b"}; - position: relative; - transform: rotate(45deg); - - animation: ${cr} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; - animation-delay: 100ms; - - &:after, - &:before { - content: ''; - animation: ${dr} 0.15s ease-out forwards; - animation-delay: 150ms; - position: absolute; - border-radius: 3px; - opacity: 0; - background: ${r=>r.secondary||"#fff"}; - bottom: 9px; - left: 4px; - height: 2px; - width: 12px; - } - - &:before { - animation: ${lr} 0.15s ease-out forwards; - animation-delay: 180ms; - transform: rotate(90deg); - } -`,mr=ee` - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -`,fr=ne("div")` - width: 12px; - height: 12px; - box-sizing: border-box; - border: 2px solid; - border-radius: 100%; - border-color: ${r=>r.secondary||"#e0e0e0"}; - border-right-color: ${r=>r.primary||"#616161"}; - animation: ${mr} 1s linear infinite; -`,pr=ee` -from { - transform: scale(0) rotate(45deg); - opacity: 0; -} -to { - transform: scale(1) rotate(45deg); - opacity: 1; -}`,hr=ee` -0% { - height: 0; - width: 0; - opacity: 0; -} -40% { - height: 0; - width: 6px; - opacity: 1; -} -100% { - opacity: 1; - height: 10px; -}`,gr=ne("div")` - width: 20px; - opacity: 0; - height: 20px; - border-radius: 10px; - background: ${r=>r.primary||"#61d345"}; - position: relative; - transform: rotate(45deg); - - animation: ${pr} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; - animation-delay: 100ms; - &:after { - content: ''; - box-sizing: border-box; - animation: ${hr} 0.2s ease-out forwards; - opacity: 0; - animation-delay: 200ms; - position: absolute; - border-right: 2px solid; - border-bottom: 2px solid; - border-color: ${r=>r.secondary||"#fff"}; - bottom: 6px; - left: 6px; - height: 10px; - width: 6px; - } -`,yr=ne("div")` - position: absolute; -`,xr=ne("div")` - position: relative; - display: flex; - justify-content: center; - align-items: center; - min-width: 20px; - min-height: 20px; -`,br=ee` -from { - transform: scale(0.6); - opacity: 0.4; -} -to { - transform: scale(1); - opacity: 1; -}`,vr=ne("div")` - position: relative; - transform: scale(0.6); - opacity: 0.4; - min-width: 20px; - animation: ${br} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; -`,wr=({toast:r})=>{let{icon:e,type:t,iconTheme:n}=r;return e!==void 0?typeof e=="string"?h.createElement(vr,null,e):e:t==="blank"?null:h.createElement(xr,null,h.createElement(fr,{...n}),t!=="loading"&&h.createElement(yr,null,t==="error"?h.createElement(ur,{...n}):h.createElement(gr,{...n})))},Cr=r=>` -0% {transform: translate3d(0,${r*-200}%,0) scale(.6); opacity:.5;} -100% {transform: translate3d(0,0,0) scale(1); opacity:1;} -`,Sr=r=>` -0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} -100% {transform: translate3d(0,${r*-150}%,-1px) scale(.6); opacity:0;} -`,Er="0%{opacity:0;} 100%{opacity:1;}",kr="0%{opacity:1;} 100%{opacity:0;}",Tr=ne("div")` - display: flex; - align-items: center; - background: #fff; - color: #363636; - line-height: 1.3; - will-change: transform; - box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05); - max-width: 350px; - pointer-events: auto; - padding: 8px 10px; - border-radius: 8px; -`,Ar=ne("div")` - display: flex; - justify-content: center; - margin: 4px 10px; - color: inherit; - flex: 1 1 auto; - white-space: pre-line; -`,jr=(r,e)=>{let t=r.includes("top")?1:-1,[n,a]=At()?[Er,kr]:[Cr(t),Sr(t)];return{animation:e?`${ee(n)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${ee(a)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},_r=h.memo(({toast:r,position:e,style:t,children:n})=>{let a=r.height?jr(r.position||e||"top-center",r.visible):{opacity:0},o=h.createElement(wr,{toast:r}),s=h.createElement(Ar,{...r.ariaProps},Te(r.message,r));return h.createElement(Tr,{className:r.className,style:{...a,...t,...r.style}},typeof n=="function"?n({icon:o,message:s}):h.createElement(h.Fragment,null,o,s))});Jt(h.createElement);var Nr=({id:r,className:e,style:t,onHeightUpdate:n,children:a})=>{let o=h.useCallback(s=>{if(s){let i=()=>{let l=s.getBoundingClientRect().height;n(r,l)};i(),new MutationObserver(i).observe(s,{subtree:!0,childList:!0,characterData:!0})}},[r,n]);return h.createElement("div",{ref:o,className:e,style:t},a)},$r=(r,e)=>{let t=r.includes("top"),n=t?{top:0}:{bottom:0},a=r.includes("center")?{justifyContent:"center"}:r.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:At()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${e*(t?1:-1)}px)`,...n,...a}},Or=$e` - z-index: 9999; - > * { - pointer-events: auto; - } -`,Ce=16,Rr=({reverseOrder:r,position:e="top-center",toastOptions:t,gutter:n,children:a,containerStyle:o,containerClassName:s})=>{let{toasts:i,handlers:l}=ir(t);return h.createElement("div",{id:"_rht_toaster",style:{position:"fixed",zIndex:9999,top:Ce,left:Ce,right:Ce,bottom:Ce,pointerEvents:"none",...o},className:s,onMouseEnter:l.startPause,onMouseLeave:l.endPause},i.map(d=>{let u=d.position||e,m=l.calculateOffset(d,{reverseOrder:r,gutter:n,defaultPosition:e}),p=$r(u,m);return h.createElement(Nr,{id:d.id,key:d.id,onHeightUpdate:l.updateHeight,className:d.visible?Or:"",style:p},d.type==="custom"?Te(d.message,d):a?a(d):h.createElement(_r,{toast:d,position:u}))}))},Se=F;const Dr={},ot=r=>{let e;const t=new Set,n=(u,m)=>{const p=typeof u=="function"?u(e):u;if(!Object.is(p,e)){const y=e;e=m??(typeof p!="object"||p===null)?p:Object.assign({},e,p),t.forEach(b=>b(e,y))}},a=()=>e,l={setState:n,getState:a,getInitialState:()=>d,subscribe:u=>(t.add(u),()=>t.delete(u)),destroy:()=>{(Dr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),t.clear()}},d=e=r(n,a,l);return l},Mr=r=>r?ot(r):ot;var Me={exports:{}},Pe={},Ie={exports:{}},Le={};var st;function Pr(){if(st)return Le;st=1;var r=Qe();function e(m,p){return m===p&&(m!==0||1/m===1/p)||m!==m&&p!==p}var t=typeof Object.is=="function"?Object.is:e,n=r.useState,a=r.useEffect,o=r.useLayoutEffect,s=r.useDebugValue;function i(m,p){var y=p(),b=n({inst:{value:y,getSnapshot:p}}),f=b[0].inst,x=b[1];return o(function(){f.value=y,f.getSnapshot=p,l(f)&&x({inst:f})},[m,y,p]),a(function(){return l(f)&&x({inst:f}),m(function(){l(f)&&x({inst:f})})},[m]),s(y),y}function l(m){var p=m.getSnapshot;m=m.value;try{var y=p();return!t(m,y)}catch{return!0}}function d(m,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:i;return Le.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:u,Le}var it;function Ir(){return it||(it=1,Ie.exports=Pr()),Ie.exports}var ct;function Lr(){if(ct)return Pe;ct=1;var r=Qe(),e=Ir();function t(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var n=typeof Object.is=="function"?Object.is:t,a=e.useSyncExternalStore,o=r.useRef,s=r.useEffect,i=r.useMemo,l=r.useDebugValue;return Pe.useSyncExternalStoreWithSelector=function(d,u,m,p,y){var b=o(null);if(b.current===null){var f={hasValue:!1,value:null};b.current=f}else f=b.current;b=i(function(){function g(A){if(!C){if(C=!0,k=A,A=p(A),y!==void 0&&f.hasValue){var I=f.value;if(y(I,A))return j=I}return j=A}if(I=j,n(k,A))return I;var U=p(A);return y!==void 0&&y(I,U)?(k=A,I):(k=A,j=U)}var C=!1,k,j,_=m===void 0?null:m;return[function(){return g(u())},_===null?void 0:function(){return g(_())}]},[u,m,p,y]);var x=a(d,b[0],b[1]);return s(function(){f.hasValue=!0,f.value=x},[x]),l(x),x},Pe}var dt;function Ur(){return dt||(dt=1,Me.exports=Lr()),Me.exports}var qr=Ur();const Vr=St(qr),_t={},{useDebugValue:Wr}=z,{useSyncExternalStoreWithSelector:Fr}=Vr;let lt=!1;const Br=r=>r;function zr(r,e=Br,t){(_t?"production":void 0)!=="production"&&t&&!lt&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),lt=!0);const n=Fr(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return Wr(n),n}const Yr=r=>{(_t?"production":void 0)!=="production"&&typeof r!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof r=="function"?Mr(r):r,t=(n,a)=>zr(e,n,a);return Object.assign(t,e),t},Hr=r=>Yr,Ue={BASE_URL:"/studio/ui/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_BASE_URL:"/studio/ui/"},Ke=new Map,Ee=r=>{const e=Ke.get(r);return e?Object.fromEntries(Object.entries(e.stores).map(([t,n])=>[t,n.getState()])):{}},Gr=(r,e,t)=>{if(r===void 0)return{type:"untracked",connection:e.connect(t)};const n=Ke.get(t.name);if(n)return{type:"tracked",store:r,...n};const a={connection:e.connect(t),stores:{}};return Ke.set(t.name,a),{type:"tracked",store:r,...a}},Kr=(r,e={})=>(t,n,a)=>{const{enabled:o,anonymousActionType:s,store:i,...l}=e;let d;try{d=(o??(Ue?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return(Ue?"production":void 0)!=="production"&&o&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),r(t,n,a);const{connection:u,...m}=Gr(i,d,l);let p=!0;a.setState=(f,x,g)=>{const C=t(f,x);if(!p)return C;const k=g===void 0?{type:s||"anonymous"}:typeof g=="string"?{type:g}:g;return i===void 0?(u?.send(k,n()),C):(u?.send({...k,type:`${i}/${k.type}`},{...Ee(l.name),[i]:a.getState()}),C)};const y=(...f)=>{const x=p;p=!1,t(...f),p=x},b=r(a.setState,n,a);if(m.type==="untracked"?u?.init(b):(m.stores[m.store]=a,u?.init(Object.fromEntries(Object.entries(m.stores).map(([f,x])=>[f,f===m.store?b:x.getState()])))),a.dispatchFromDevtools&&typeof a.dispatch=="function"){let f=!1;const x=a.dispatch;a.dispatch=(...g)=>{(Ue?"production":void 0)!=="production"&&g[0].type==="__setState"&&!f&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),f=!0),x(...g)}}return u.subscribe(f=>{var x;switch(f.type){case"ACTION":if(typeof f.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return qe(f.payload,g=>{if(g.type==="__setState"){if(i===void 0){y(g.state);return}Object.keys(g.state).length!==1&&console.error(` - [zustand devtools middleware] Unsupported __setState action format. - When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(), - and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } } - `);const C=g.state[i];if(C==null)return;JSON.stringify(a.getState())!==JSON.stringify(C)&&y(C);return}a.dispatchFromDevtools&&typeof a.dispatch=="function"&&a.dispatch(g)});case"DISPATCH":switch(f.payload.type){case"RESET":return y(b),i===void 0?u?.init(a.getState()):u?.init(Ee(l.name));case"COMMIT":if(i===void 0){u?.init(a.getState());return}return u?.init(Ee(l.name));case"ROLLBACK":return qe(f.state,g=>{if(i===void 0){y(g),u?.init(a.getState());return}y(g[i]),u?.init(Ee(l.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return qe(f.state,g=>{if(i===void 0){y(g);return}JSON.stringify(a.getState())!==JSON.stringify(g[i])&&y(g[i])});case"IMPORT_STATE":{const{nextLiftedState:g}=f.payload,C=(x=g.computedStates.slice(-1)[0])==null?void 0:x.state;if(!C)return;y(i===void 0?C:C[i]),u?.send(null,g);return}case"PAUSE_RECORDING":return p=!p}return}}),b},Jr=Kr,qe=(r,e)=>{let t;try{t=JSON.parse(r)}catch(n){console.error("[zustand devtools middleware] Could not parse the received json",n)}t!==void 0&&e(t)},Xr="agentomatic-studio:lastUrl",ut="http://127.0.0.1:8000";function Qr(){return typeof window>"u"?!1:(window.location.pathname||"").includes("/studio/ui")}function Zr(r){try{const e=new URL(r),t=e.hostname,n=e.port||(e.protocol==="https:"?"443":"80");return(t==="127.0.0.1"||t==="localhost")&&(n==="8000"||n==="3000")}catch{return!1}}function Ae(){if(typeof window>"u")return ut;const r=Qr();try{const e=localStorage.getItem(Xr);if(e&&/^https?:\/\//i.test(e)){const t=e.replace(/\/$/,"");if(!(r&&Zr(t)))return t}}catch{}return r?window.location.origin:ut}function mt(r){return(r||"").trim().replace(/\/$/,"")}class ft{static connect(e,t,n,a){const o=new AbortController;return(async()=>{try{const i=await fetch(e,{method:"POST",headers:{...n,Accept:"text/event-stream"},body:JSON.stringify(t),signal:o.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);const l=i.body?.getReader();if(!l)throw new Error("No response body");const d=new TextDecoder;let u="",m="";for(;;){const{done:p,value:y}=await l.read();if(p){a.onDone?.();break}u+=d.decode(y,{stream:!0});const b=u.split(` -`);u=b.pop()||"";for(const f of b){if(f.startsWith("event: ")){m=f.slice(7).trim();continue}if(f.startsWith("data: ")){const x=f.slice(6).trim();if(x==="[DONE]"){a.onDone?.(),m="";return}try{const g=JSON.parse(x);switch(m&&!g.event&&(g.event=m),m="",a.onEvent?.(g),g.event){case"run_start":a.onRunStart?.(g);break;case"node_start":a.onNodeStart?.(g);break;case"node_end":a.onNodeEnd?.(g);break;case"state_update":a.onStateUpdate?.(g);break;case"message_chunk":a.onMessageChunk?.(g);break;case"run_complete":a.onRunComplete?.(g);break;case"run_error":a.onRunError?.(g);break;case"breakpoint_hit":a.onBreakpointHit?.(g);break}}catch(g){console.warn("Failed to parse SSE event:",x,g)}}f.trim()===""&&(m="")}}}catch(i){i.name!=="AbortError"&&a.onError?.(i)}})(),o}}function wo(r){if(!r||typeof r!="object")return null;if(r.type||r.properties||r.$ref||r.anyOf||r.oneOf||r.allOf)return r;const e={str:"string",string:"string",int:"integer",integer:"integer",float:"number",number:"number",bool:"boolean",boolean:"boolean",dict:"object",object:"object",list:"array",array:"array"},t={},n=[];for(const[a,o]of Object.entries(r)){const s=o&&typeof o=="object"&&!Array.isArray(o)?o:{type:o},i=typeof s.type=="string"?s.type:void 0;t[a]={...s,type:i?e[i]||i:void 0},s.default===void 0&&n.push(a)}return{type:"object",properties:t,...n.length?{required:n}:{}}}function Ze(r,e){if(!r||typeof r!="object")return{};if(!r.$ref||typeof r.$ref!="string")return r;const t=r.$ref;if(!t.startsWith("#/"))return r;const n=t.slice(2).split("/");let a=e;for(const s of n){if(a==null||typeof a!="object")return r;a=a[s]}if(!a||typeof a!="object")return r;const o={...r};return delete o.$ref,{...a,...o}}function H(r,e){if(!r||typeof r!="object")return{};let t=Ze(r,e);if(Array.isArray(t.allOf)){const{allOf:n,...a}=t,o=n.reduce((s,i)=>{const l=H(i,e),d=Array.from(new Set([...Array.isArray(s.required)?s.required:[],...Array.isArray(l.required)?l.required:[]]));return{...s,...l,properties:{...s.properties||{},...l.properties||{}},...d.length?{required:d}:{}}},{});t={...o,...a,properties:{...o.properties||{},...a.properties||{}}}}if(!t.type&&Array.isArray(t.anyOf)){const n=t.anyOf.find(a=>a&&(a.type||a.$ref||a.properties));if(n){const a={...t};delete a.anyOf,t={...H(n,e),...a}}}if(!t.type&&Array.isArray(t.oneOf)){const n=t.oneOf.find(a=>a&&(a.type||a.$ref||a.properties));if(n){const a={...t};delete a.oneOf,t={...H(n,e),...a}}}if(Array.isArray(t.type)){const n=t.type.find(a=>a!=="null")||t.type[0];t={...t,type:n}}return t}function Co(r,e){if(!r||typeof r!="object")return[];const t=Ze(r,e),a=(Array.isArray(t.oneOf)?t.oneOf:Array.isArray(t.anyOf)?t.anyOf:[]).map(o=>H(o,e)).filter(o=>o.type!=="null");return a.length>1?a:[]}function So(r,e){return e?.title&&typeof e.title=="string"?e.title:r.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}function Eo(r){if(typeof r=="string")return r;if(r===null)return"null";if(typeof r>"u")return"undefined";try{return JSON.stringify(r)}catch{return String(r)}}function ko(r,e){return r.findIndex(t=>{if(Object.is(t,e))return!0;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}})}function To(r,e){if(e==="")return;const t=Number(e);return Number.isInteger(t)&&t>=0&&t0||r.type&&r.type!=="object"||r.$ref||r.allOf||r.anyOf||r.oneOf)}function Nt(r,e){if(!r||typeof r!="object")return{};const t=e||r,n=H(r,t);if(n.default!==void 0)return typeof n.default=="object"&&!Array.isArray(n.default)?{...n.default}:{};const a=n.properties||{},o={};for(const[s,i]of Object.entries(a)){const l=H(i,t);if(l.const!==void 0){o[s]=l.const;continue}if(l.default!==void 0){o[s]=l.default;continue}switch(l.type){case"string":o[s]="";break;case"number":case"integer":o[s]=l.minimum??0;break;case"boolean":o[s]=!1;break;case"array":o[s]=[];break;case"object":o[s]=Nt(l,t);break}}return o}function jo(r,e){if(!r||typeof r!="object")return{};const t=e||r,n=H(r,t);if(n.const!==void 0)return n.const;if(n.default!==void 0)return n.default;if(n.type==="object"||n.properties)return Nt(n,t);switch(n.type){case"array":return[];case"boolean":return!1;case"number":case"integer":return n.minimum??0;case"null":return null;case"string":return"";default:return{}}}function _o(r,e,t){if(!r||typeof r!="object")return[];const n=t||r,a=s=>s==null||typeof s=="string"&&!s.trim(),o=(s,i,l,d)=>{if(d>12)return[];const u=Ze(s,n),m=(Array.isArray(u.oneOf)?u.oneOf:u.anyOf)?.filter(g=>H(g,n).type!=="null")||[];if(m.length>1){const g=m.map(C=>o(C,i,l,d+1));return g.find(C=>C.length===0)??g.sort((C,k)=>C.length-k.length)[0]??[]}const p=[],y=H(s,n),b=y.properties||{},f=new Set(Array.isArray(y.required)?y.required:[]),x=i&&typeof i=="object"&&!Array.isArray(i)?i:void 0;for(const g of Array.from(f)){const C=x?.[g],k=l?`${l}.${g}`:g;if(a(C)){p.push(k);continue}p.push(...o(b[g]||{},C,k,d+1))}if(x)for(const[g,C]of Object.entries(b))f.has(g)||a(x[g])||p.push(...o(C,x[g],l?`${l}.${g}`:g,d+1));return Array.isArray(i)&&y.items&&i.forEach((g,C)=>p.push(...o(y.items,g,`${l}[${C}]`,d+1))),p};return o(r,e,"",0)}function en(r){if(!r||typeof r!="object")return"";if(typeof r.query=="string"&&r.query.trim())return r.query;if(typeof r.current_query=="string"&&r.current_query.trim())return r.current_query;for(const[e,t]of Object.entries(r))if(e.endsWith("_query")&&typeof t=="string"&&t.trim())return t;for(const e of["message","text","input","prompt","content"]){const t=r[e];if(typeof t=="string"&&t.trim())return t}for(const e of Object.values(r))if(typeof e=="string"&&e.trim())return e;try{const e=JSON.stringify(r);return e==="{}"?"":e}catch{return""}}function No(r){if(!r||typeof r!="object")return[];const e=H(r,r),t=e.properties||{},n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(t).map(([a,o])=>{const s=H(o,r);let i=s.type||"any";return i==="array"&&s.items&&(i=`array<${H(s.items,r).type||"any"}>`),{name:a,type:String(i),required:n.has(a),description:typeof s.description=="string"?s.description:typeof s.title=="string"?s.title:void 0}})}const le=r=>{if(!r)return"";const e=["tool:","llm:","retriever:","subagent:"];for(const t of e)if(r.startsWith(t))return r.slice(t.length);return r},tn=(r,e)=>{if(r.length===0)return r;const t=new Map,n=new Map;r.forEach(f=>{t.set(f.id,[]),n.set(f.id,[])}),e.forEach(f=>{t.get(f.source)?.push(f.target),n.get(f.target)?.push(f.source)});const a=r.filter(f=>n.get(f.id)?.length===0);r.filter(f=>t.get(f.id)?.length===0);const o=[],s=new Set,i=new Map,l=[];for(a.forEach(f=>{l.push({nodeId:f.id,layer:0})}),l.length===0&&r.length>0&&l.push({nodeId:r[0].id,layer:0});l.length>0;){const{nodeId:f,layer:x}=l.shift();if(s.has(f))continue;for(s.add(f);o.length<=x;)o.push([]);o[x].push(f),i.set(f,x),(t.get(f)||[]).forEach(C=>{s.has(C)||l.push({nodeId:C,layer:x+1})})}r.forEach(f=>{if(!s.has(f.id)){const x=o.length;o.length===0?o.push([]):o.push([]),o[x].push(f.id),i.set(f.id,x)}});const d=100,u=220,m=140,p=100,y=100;return r.map(f=>{const x=i.get(f.id)||0,g=o[x]||[],C=g.indexOf(f.id),k=g.length*d+(g.length-1)*m,j=y-k/2+(g.length>1?0:k/2),_=p+x*u,A=j+C*(d+m);return{...f,position:{x:_,y:A}}})};class rn{constructor(){this.listeners=new Map,this.globalListeners=new Set}subscribe(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}subscribeAll(e){return this.globalListeners.add(e),()=>{this.globalListeners.delete(e)}}emit(e){this.listeners.get(e.type)?.forEach(t=>{try{t(e)}catch(n){console.error("Error in live update listener:",n)}}),this.globalListeners.forEach(t=>{try{t(e)}catch(n){console.error("Error in global live update listener:",n)}})}getListenerCount(){const e={};return this.listeners.forEach((t,n)=>{e[n]=t.size}),{total:this.globalListeners.size+Array.from(this.listeners.values()).reduce((t,n)=>t+n.size,0),byType:e}}}const R=new rn;let P=null;const Je=r=>{P=r},nn=r=>{const e=r.nodes.map(n=>({id:n.id,type:n.type||"processing",data:{label:n.name,description:n.metadata?.description||"",status:"idle",metadata:n.metadata},position:{x:0,y:0}})),t=r.edges.map(n=>({id:n.id,source:n.source,target:n.target,type:n.condition?"conditional":"default",data:{label:n.condition||void 0}}));return{nodes:tn(e,t),edges:t}},Ve=(r,e)=>({id:r?.id||r?.thread_id||"",name:r?.title||`Thread ${(r?.id||r?.thread_id||"").slice(-8)}`,messages:[],createdAt:new Date(r?.created_at||Date.now()),updatedAt:new Date(r?.updated_at||r?.created_at||Date.now()),metadata:r?.metadata||{},agentId:e}),an=r=>({id:r?.id||r?.message_id||`message-${Date.now()}`,role:r?.role==="user"||r?.role==="system"?r.role:"assistant",content:typeof r?.content=="string"?r.content:JSON.stringify(r?.content??r?.message??""),timestamp:new Date(r?.timestamp||r?.created_at||Date.now()),metadata:r?.metadata||{}}),on=(r,e)=>{if(e&&e.trim().length>0)return e.trim();const t=r.filter(l=>l.data?.intermediate_results);for(const l of t.reverse()){const d=l.data.intermediate_results;for(const[u,m]of Object.entries(d))if(m&&typeof m=="object"){const p=m,y=p.output&&typeof p.output=="object"?p.output:p;if(y.response&&typeof y.response=="string"&&y.response.trim().length>0)return y.response}}const n=r.filter(l=>l.type==="output"&&l.data?.output);for(const l of n.reverse()){const d=l.data.output;if(d&&typeof d=="object"){const u=d.output&&typeof d.output=="object"?d.output:d;if(u.response&&typeof u.response=="string"&&u.response.trim().length>0)return u.response;const m=["result","content","text","message","answer"];for(const p of m)if(u[p]&&typeof u[p]=="string"&&u[p].trim().length>0)return u[p]}if(typeof d=="string"&&d.trim().length>0)return d}const a=r.filter(l=>l.data?.final_response&&typeof l.data.final_response=="string"&&l.data.final_response.trim().length>0);if(a.length>0)return a[a.length-1].data.final_response;const o=r.filter(l=>l.data?.state_updates?.intermediate_results);for(const l of o.reverse()){const d=l.data.state_updates.intermediate_results;for(const[u,m]of Object.entries(d))if(u.includes("respond")&&m&&typeof m=="object"){const p=m.response;if(p&&typeof p=="string"&&p.trim().length>0)return p}}const s=r.filter(l=>(l.nodeId.includes("respond")||l.nodeId.includes("generation")||l.nodeName.toLowerCase().includes("respond")||l.nodeName.toLowerCase().includes("generation"))&&l.type==="output"&&l.data?.output);for(const l of s.reverse()){const d=l.data.output;if(d.response&&typeof d.response=="string"&&d.response.trim().length>0)return d.response;if(d.result&&typeof d.result=="string"&&d.result.trim().length>0)return d.result;if(d.content&&typeof d.content=="string"&&d.content.trim().length>0)return d.content}const i=r.filter(l=>l.type==="output"&&l.data?.output&&typeof l.data.output=="object").slice(-5);for(const l of i.reverse()){const d=l.data.output,u=[d.response,d.result,d.content,d.text,d.message,d.answer,d.clarification_request];for(const m of u)if(m&&typeof m=="string"&&m.trim().length>20)return m}return null},We={currentView:"graph",graphState:{nodes:[],edges:[],currentNode:void 0,executionPath:[]},isConnected:!1,isLoading:!1},Fe={isExecuting:!1,isPaused:!1,currentState:{},logs:[],breakpoints:[]},me=Hr()(Jr((r,e)=>({...We,threads:[],agents:[],assistants:[],runs:[],config:{apiUrl:Ae(),agentId:void 0,apiKey:void 0},graphState:We.graphState,activeInterrupts:[],subAgentResults:[],agentSchemas:{},schemasLoading:!1,setCurrentView:t=>r({currentView:t}),builderPipelineToLoad:null,setBuilderPipelineToLoad:t=>r({builderPipelineToLoad:t}),setSelectedThread:t=>{r({selectedThread:t});const n=e();t&&n.selectedAgent&&n.switchToExecutionContext(t.id,n.selectedAgent.id)},setSelectedAgent:t=>{const n=t?{...t,config:{},graph_id:t.graph?.id||""}:void 0;r({selectedAgent:t,selectedAssistant:n});const a=e();t&&a.selectedThread&&a.switchToExecutionContext(a.selectedThread.id,t.id),t?.id&&a.fetchAgentSchemas(t.id)},setSelectedAssistant:t=>{r({selectedAssistant:t,selectedAgent:t});const n=e();t&&n.selectedThread&&n.switchToExecutionContext(n.selectedThread.id,t.id),t?.id&&n.fetchAgentSchemas(t.id)},setCurrentRun:t=>r({currentRun:t}),setGraphState:t=>{r({graphState:t}),R.emit({type:"GRAPH_STATE_CHANGED",data:t})},setIsConnected:t=>r({isConnected:t}),setIsLoading:t=>r({isLoading:t}),setError:t=>r({error:t}),sidebarCollapsed:!1,setSidebarCollapsed:t=>r({sidebarCollapsed:t}),darkMode:!1,setDarkMode:t=>r({darkMode:t}),isStreaming:!1,setIsStreaming:t=>r({isStreaming:t}),streamingMessage:"",setStreamingMessage:t=>r({streamingMessage:t}),activeAbortController:null,setActiveAbortController:t=>r({activeAbortController:t}),connectionStatus:"disconnected",setConnectionStatus:t=>r({connectionStatus:t}),retryAttempts:0,maxRetryAttempts:3,attemptReconnection:async()=>{const t=e();if(t.retryAttempts>=t.maxRetryAttempts){r({connectionStatus:"failed"});return}r({connectionStatus:"reconnecting",retryAttempts:t.retryAttempts+1});try{if(P)try{if(await P.healthCheck()){r({connectionStatus:"connected",isConnected:!0,retryAttempts:0,error:void 0}),R.emit({type:"GRAPH_STATE_CHANGED",data:t.graphState});return}}catch{console.log("Studio API health check failed, trying legacy endpoints...")}const n=["/studio/info","/health","/ready","/status","/"];let a=!1,o=null;for(const s of n)try{console.log(`🔍 Testing connectivity with endpoint: ${s}`);const i=await fetch(`${t.config.apiUrl}${s}`,{method:"GET",headers:{"Content-Type":"application/json",...t.config.apiKey&&{"X-Api-Key":t.config.apiKey,Authorization:`Bearer ${t.config.apiKey}`}}});if(i.status<500){console.log(`✅ Server responding on ${s} with status ${i.status}`),a=!0;break}}catch(i){console.log(`❌ Failed to connect to ${s}:`,i),o=i;continue}if(a)r({connectionStatus:"connected",isConnected:!0,retryAttempts:0,error:void 0}),R.emit({type:"GRAPH_STATE_CHANGED",data:t.graphState});else throw o||new Error("All endpoints failed to respond")}catch(n){console.error(`Reconnection attempt ${t.retryAttempts} failed:`,n),t.retryAttempts>=t.maxRetryAttempts?r({connectionStatus:"failed",isConnected:!1,error:`Failed to reconnect after ${t.maxRetryAttempts} attempts`}):setTimeout(()=>{const a=e();a.connectionStatus==="reconnecting"&&a.attemptReconnection()},2e3*t.retryAttempts)}},replaceThreads:t=>r(n=>({threads:t,selectedThread:n.selectedThread?t.find(a=>a.id===n.selectedThread?.id):void 0})),refreshThreads:async t=>{if(!P||!t)return[];const n=await P.listThreads(t),a=e().threads,o=n.map(s=>{const i=Ve(s,t),l=a.find(d=>d.id===i.id);return l?.messages.length?{...i,messages:l.messages}:i});return e().replaceThreads(o),o},hydrateThreadMessages:async(t,n)=>{if(!P||!t||!n)return;const a=(await P.getMessages(n,t)).map(i=>an(i)),o=e().threads.find(i=>i.id===t);if(!o)return;const s={...o,messages:a,updatedAt:new Date};return e().updateThread(t,{messages:s.messages,updatedAt:s.updatedAt}),s},createPersistentThread:async(t,n="New Chat")=>{if(!P||!t)throw new Error("Connect Studio to a live agent before creating a thread.");const a=await P.createThread(t,"studio-user",n),o=Ve(a,t);return e().addThread(o),e().setSelectedThread(o),o},deletePersistentThread:async t=>{const n=t.agentId||e().selectedAssistant?.id;if(!P||!n)throw new Error("Connect Studio to the thread agent before deleting this conversation.");await P.deleteThread(n,t.id),e().deleteThread(t.id)},addThread:t=>r(n=>({threads:[...n.threads,t]})),updateThread:(t,n)=>r(a=>{const o=a.threads.map(s=>s.id===t?{...s,...n}:s);return R.emit({type:"THREAD_UPDATED",data:{threadId:t,updates:n}}),{threads:o}}),deleteThread:t=>r(n=>({threads:n.threads.filter(a=>a.id!==t),selectedThread:n.selectedThread?.id===t?void 0:n.selectedThread})),addMessageToThread:(t,n)=>r(a=>{const o=a.threads.map(i=>i.id===t?{...i,messages:[...i.messages,n],updatedAt:new Date}:i),s=a.selectedThread?.id===t?{...a.selectedThread,messages:[...a.selectedThread.messages,n],updatedAt:new Date}:a.selectedThread;return R.emit({type:"MESSAGE_ADDED",data:{threadId:t,message:n}}),{threads:o,selectedThread:s}}),addAgent:t=>r(n=>({agents:[...n.agents,t],assistants:[...n.assistants,{...t,config:{},graph_id:t.graph?.id||""}]})),updateAgent:(t,n)=>r(a=>({agents:a.agents.map(o=>o.id===t?{...o,...n}:o),assistants:a.assistants.map(o=>o.id===t?{...o,...n,config:{},graph_id:o.graph_id}:o)})),deleteAgent:t=>r(n=>({agents:n.agents.filter(a=>a.id!==t),assistants:n.assistants.filter(a=>a.id!==t),selectedAgent:n.selectedAgent?.id===t?void 0:n.selectedAgent,selectedAssistant:n.selectedAssistant?.id===t?void 0:n.selectedAssistant})),clearAgents:()=>r({agents:[],assistants:[],selectedAgent:void 0,selectedAssistant:void 0}),addAssistant:t=>r(n=>({assistants:[...n.assistants,t],agents:[...n.agents,{...t,type:"chat",model:"",provider:"",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:!1,timeout:3e4}]})),updateAssistant:(t,n)=>r(a=>({assistants:a.assistants.map(o=>o.id===t?{...o,...n}:o),agents:a.agents.map(o=>o.id===t?{...o,...n}:o)})),deleteAssistant:t=>r(n=>({assistants:n.assistants.filter(a=>a.id!==t),agents:n.agents.filter(a=>a.id!==t),selectedAssistant:n.selectedAssistant?.id===t?void 0:n.selectedAssistant,selectedAgent:n.selectedAgent?.id===t?void 0:n.selectedAgent})),clearAssistants:()=>r({assistants:[],agents:[],selectedAssistant:void 0,selectedAgent:void 0}),addRun:t=>r(n=>({runs:[...n.runs,t]})),updateRun:(t,n)=>r(a=>({runs:a.runs.map(o=>o.id===t?{...o,...n}:o)})),setConfig:t=>r({config:t}),fetchAgentSchemas:async(t,n=!1)=>{if(!t)return null;const a=e();if(!n&&a.agentSchemas[t])return a.agentSchemas[t];if(!P)return console.warn("fetchAgentSchemas: Studio API client not initialized"),null;try{r({schemasLoading:!0});const o=await P.getSchemas(t);return r(s=>({agentSchemas:{...s.agentSchemas,[t]:o},schemasLoading:!1})),o}catch(o){return console.warn(`Failed to fetch schemas for ${t}:`,o),r({schemasLoading:!1}),null}},fetchGraphData:async t=>{try{r({isLoading:!0,error:void 0}),console.log(`🔍 Fetching graph data for agent: ${t}`);let n=new Error("The Studio API client is not initialized");if(P)try{const o=await P.getGraph(t);console.log("📊 Received graph topology from API:",o);const{nodes:s,edges:i}=nn(o);r({graphState:{nodes:s,edges:i,currentNode:void 0,executionPath:[]},isLoading:!1}),console.log(`✅ Loaded graph for ${t}: ${s.length} nodes, ${i.length} edges`);return}catch(o){n=o,console.warn("⚠️ Could not fetch graph from Studio API:",o)}const a=n instanceof Error?n.message:String(n);r({graphState:{nodes:[],edges:[],currentNode:void 0,executionPath:[]},isLoading:!1,error:"Unable to load live graph topology for "+t+": "+a});return}catch(n){console.error("❌ Error fetching graph data:",n);const a=e();a.connectionStatus!=="reconnecting"&&a.retryAttempts{const a=e(),o=t||a.selectedThread?.id||"default",s=n||a.selectedAgent?.id||"default";return`${o}-${s}`},switchToExecutionContext:(t,n)=>{const a=e(),o=a.getExecutionContextKey(t,n),s=a.executionContexts.get(o);if(s)r({executionContext:s});else{const i={...Fe,threadId:t||a.selectedThread?.id,agentId:n||a.selectedAgent?.id,assistantId:n||a.selectedAgent?.id},l=new Map(a.executionContexts);l.set(o,i),r({executionContext:i,executionContexts:l})}},setExecutionContext:t=>r(n=>{const a={...n.executionContext,...t},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),startExecution:(t={},n)=>{const a=`exec_${Date.now()}`;e(),r(o=>{const s={...o.executionContext,isExecuting:!0,isPaused:!1,currentState:t,executionId:a,startTime:new Date,endTime:void 0,threadId:o.selectedThread?.id,agentId:o.selectedAgent?.id,assistantId:o.selectedAgent?.id},i=o.getExecutionContextKey(),l=new Map(o.executionContexts);return l.set(i,s),R.emit({type:"EXECUTION_STARTED",data:{threadId:o.selectedThread?.id||"unknown",assistantId:o.selectedAgent?.id||"unknown",initialState:t}}),{executionContext:s,executionContexts:l,graphState:{...o.graphState||{nodes:[],edges:[],executionPath:[]},currentNode:n||o.graphState?.nodes?.find(d=>d.type==="start")?.id,executionPath:n?[n]:[]}}})},pauseExecution:()=>r(t=>{const n={...t.executionContext,isPaused:!0},a=t.getExecutionContextKey(),o=new Map(t.executionContexts);return o.set(a,n),{executionContext:n,executionContexts:o}}),resumeExecution:async(t=null)=>{const n=e(),{selectedAgent:a,selectedThread:o}=n;if(!P||!a||!o){const d="A connected agent and interrupted thread are required to resume execution.";r({error:d}),n.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:d,data:{action:"resume"}});return}const s=o.id,i=a.id,l=d=>r(u=>{const m={...u.executionContext,isPaused:d},p=u.getExecutionContextKey(),y=new Map(u.executionContexts);return y.set(p,m),{executionContext:m,executionContexts:y}});try{l(!1);const d=ft.connect(P.getResumeStreamUrl(i,s),{value:t,action:"approve"},P.getHeaders(),{onRunStart:u=>e().addExecutionLog({nodeId:"system",nodeName:"System",type:"info",message:`Resumed run: ${u.run_id}`,data:u.data}),onNodeStart:u=>{const m=le(u.node);if(!m)return;const p=e();p.setGraphState({...p.graphState,currentNode:m,executionPath:[...p.graphState.executionPath,m]}),p.addExecutionLog({nodeId:m,nodeName:m,type:"input",message:`Resumed node: ${m}`,data:u.data})},onNodeEnd:u=>{const m=le(u.node);if(!m)return;const p=e();p.addExecutionLog({nodeId:m,nodeName:m,type:"output",message:`Completed node: ${m}`,data:u.data,duration:u.duration_ms||void 0}),p.setGraphExecutionState({...p.executionContext.currentState,[m]:u.data})},onStateUpdate:u=>{const m=e();m.setGraphExecutionState({...m.executionContext.currentState,...u.data})},onMessageChunk:u=>R.emit({type:"STREAMING_UPDATE",data:{messageId:`resume-${u.run_id}`,content:u.data?.content||"",isComplete:!1}}),onBreakpointHit:u=>{const m=e();m.pauseExecution(),m.addExecutionLog({nodeId:le(u.node)||"system",nodeName:"System",type:"info",message:`Execution paused at breakpoint${u.node?`: ${u.node}`:""}`,data:u.data})},onRunError:u=>{const m=u.data?.error||"The server could not resume this execution.",p=e();p.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:m,data:u.data}),p.stopExecution(),r({error:m})},onRunComplete:()=>e().stopExecution(),onError:u=>{const m=u.message||"Resume stream failed.",p=e();p.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:m,data:{action:"resume"}}),p.stopExecution(),r({error:m})},onDone:()=>{const u=e();u.executionContext.isExecuting&&!u.executionContext.isPaused&&u.stopExecution()}});r({activeAbortController:d})}catch(d){l(!0);const u=d instanceof Error?d.message:"Could not start the resume request.";r({error:u}),e().addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:u,data:{action:"resume"}})}},stopExecution:()=>r(t=>{const n={...t.executionContext,isExecuting:!1,isPaused:!1,endTime:new Date};t.activeAbortController&&t.activeAbortController.abort();const a=t.getExecutionContextKey(),o=new Map(t.executionContexts);o.set(a,n);const s=n.startTime?n.endTime.getTime()-n.startTime.getTime():0;return R.emit({type:"EXECUTION_COMPLETED",data:{threadId:t.selectedThread?.id||"unknown",finalState:n.currentState,duration:s}}),setTimeout(()=>{e().fitGraphToView()},500),{executionContext:n,executionContexts:o,activeAbortController:null,graphState:{...t.graphState,currentNode:void 0}}}),addExecutionLog:t=>r(n=>{const a={...t,id:`log_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:new Date},o={...n.executionContext,logs:[...n.executionContext.logs,a]},s=n.getExecutionContextKey(),i=new Map(n.executionContexts);return i.set(s,o),R.emit({type:"EXECUTION_LOG",data:a}),{executionContext:o,executionContexts:i}}),clearExecutionLogs:()=>r(t=>{const n={...t.executionContext,logs:[]},a=t.getExecutionContextKey(),o=new Map(t.executionContexts);return o.set(a,n),{executionContext:n,executionContexts:o}}),setGraphExecutionState:t=>r(n=>{const a={...n.executionContext,currentState:t},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),addBreakpoint:(t,n)=>r(a=>{if(a.executionContext.breakpoints.find(d=>d.nodeId===t))return a;const s={...a.executionContext,breakpoints:[...a.executionContext.breakpoints,{nodeId:t,enabled:!0,condition:n}]},i=a.getExecutionContextKey(),l=new Map(a.executionContexts);return l.set(i,s),{executionContext:s,executionContexts:l}}),removeBreakpoint:t=>r(n=>{const a={...n.executionContext,breakpoints:n.executionContext.breakpoints.filter(i=>i.nodeId!==t)},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),toggleBreakpoint:t=>r(n=>{const a={...n.executionContext,breakpoints:n.executionContext.breakpoints.map(i=>i.nodeId===t?{...i,enabled:!i.enabled}:i)},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),focusOnNode:t=>{console.log("Focus on node:",t)},fitGraphToView:()=>{console.log("Fit graph to view")},liveUpdateManager:R,subscribeLiveUpdates:(t,n)=>R.subscribe(t,n),subscribeAllLiveUpdates:t=>R.subscribeAll(t),emitLiveUpdate:t=>R.emit(t),addMessageToThreadLive:(t,n)=>{e().addMessageToThread(t,n)},updateThreadLive:(t,n)=>{e().updateThread(t,n)},setGraphStateLive:t=>{e().setGraphState(t)},focusOnNodeLive:t=>{e().focusOnNode(t),R.emit({type:"NODE_FOCUSED",data:{nodeId:t}})},startGlobalExecution:(t,n={},a)=>{const o=e(),s=o.selectedAgent?o.agentSchemas[o.selectedAgent.id]?.input_schema:void 0,i=s?.properties,d=!!(s&&(!i||Object.keys(i).length===0)&&s.type&&s.type!=="object")&&a!==void 0?a:void 0,u=d===void 0&&a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{},m=typeof d=="string"?d:d!==void 0?JSON.stringify(d):typeof a=="string"?a:en(u)||(typeof n?.message=="string"?n.message:"");if((o.graphState?.nodes||[]).length===0&&console.info("No graph topology loaded; executing the selected agent directly."),o.clearExecutionLogs(),o.startExecution({...n,...u,...d!==void 0?{__root__:d}:{}}),t==="graph"&&o.selectedThread){const b={id:`msg-${Date.now()}-graph-execution`,role:"assistant",content:`🔄 **Graph Execution Started** - -Execution initiated from the graph view. You can monitor the progress in real-time.`,timestamp:new Date};o.addMessageToThread(o.selectedThread.id,b)}R.emit({type:"EXECUTION_STARTED",data:{threadId:o.selectedThread?.id||"unknown",assistantId:o.selectedAgent?.id||"unknown",initialState:{...n,...u,...d!==void 0?{__root__:d}:{},source:t,userMessage:m}}}),(async()=>{try{const b=e(),{config:f,selectedThread:x,selectedAgent:g}=b;if(!g)throw new Error("No agent selected");if(!o.isConnected||!f.apiUrl){if(console.warn("Cannot execute without an active Agentomatic connection."),b.stopExecution(),b.selectedThread){const k={id:`msg-${Date.now()}-connection-error`,role:"assistant",content:`⚠️ **No active server connection** - -Connect to an Agentomatic server before executing an agent.`,timestamp:new Date};b.addMessageToThread(b.selectedThread.id,k)}return}let C=x?.id;if(!C){if(!P)throw new Error("The Studio API client is unavailable; cannot create a durable conversation.");const k=await P.createThread(g.id,"studio-user",t==="graph"?"Graph Execution":"New Chat"),j=Ve(k,g.id);C=j.id,b.addThread(j),b.setSelectedThread(j)}if(b.addExecutionLog({nodeId:"system",nodeName:"System",type:"info",message:"Starting Agentomatic execution",data:{agentId:g.id,threadId:C,input:d!==void 0?d:u,query:m}}),P){console.log("📡 Using SSE streaming via Studio API...");const k=P.getStreamUrl(g.id),j=P.getHeaders(),_=b.executionContext.breakpoints.filter(v=>v.enabled).map(v=>v.nodeId),A={};let I="";const{breakpoints:U,checkpoint_id:E,thread_id:V,user_id:O,...D}=u,J=Object.prototype.hasOwnProperty.call(D,"query"),T={...D,...d!==void 0?{agent_input:d}:{},...(J||typeof a=="string")&&(m||D.query)?{query:m||D.query}:{},thread_id:C,user_id:D.user_id||"studio-user",breakpoints:_,checkpoint_id:n.checkpoint_id},L=ft.connect(k,T,j,{onRunStart:v=>{console.log("🚀 Run started:",v.run_id);const w=e();if(v.data?.thread_id&&!w.selectedThread){const S=v.data.thread_id;if(!w.threads.find(W=>W.id===S)){const W={id:S,name:`Thread ${S.slice(-8)}`,agentId:g.id,createdAt:new Date,updatedAt:new Date,metadata:{},messages:[]};w.addThread(W),w.setSelectedThread(W)}}w.addExecutionLog({nodeId:"system",nodeName:"System",type:"info",message:`Run started: ${v.run_id}`,data:v.data})},onNodeStart:v=>{console.log("▶️ Node started:",v.node);const w=e(),S=le(v.node);S&&(w.setGraphState({...w.graphState,currentNode:S,executionPath:[...w.graphState.executionPath,S]}),w.addExecutionLog({nodeId:S,nodeName:S,type:"input",message:`Starting node: ${S}`,data:v.data}),R.emit({type:"EXECUTION_STEP",data:{nodeId:S,nodeName:S,progress:0}}))},onNodeEnd:v=>{console.log("✅ Node ended:",v.node);const w=e(),S=le(v.node);S&&(A[S]=v.data,w.addExecutionLog({nodeId:S,nodeName:S,type:"output",message:`Completed node: ${S}`,data:{...v.data,duration_ms:v.duration_ms,intermediate_results:{...A}},duration:v.duration_ms||void 0}),w.setGraphExecutionState({...w.executionContext.currentState,intermediate_results:A,[S]:v.data}))},onStateUpdate:v=>{const w=e();w.setGraphExecutionState({...w.executionContext.currentState,...v.data})},onMessageChunk:v=>{const w=v.data?.content||"";w&&(I+=w),R.emit({type:"STREAMING_UPDATE",data:{messageId:`stream-${v.run_id}`,content:I,isComplete:!1}})},onRunComplete:v=>{console.log("🏁 Run completed:",v.run_id);const w=e();if(w.stopExecution(),w.selectedThread){const S=on(w.executionContext.logs,I)||`✅ **Run completed** - -The deployment returned structured state but no chat response. Inspect the execution logs or Graph State for the exact output.`,M={id:`msg-${Date.now()}-result`,role:"assistant",content:S,timestamp:new Date};w.addMessageToThread(w.selectedThread.id,M)}R.emit({type:"EXECUTION_COMPLETED",data:{threadId:w.selectedThread?.id||"unknown",finalState:{...w.executionContext.currentState,intermediate_results:A},duration:w.executionContext.startTime?Date.now()-w.executionContext.startTime.getTime():0}})},onRunError:v=>{console.error("❌ Run error:",v.data);const w=e();if(w.stopExecution(),r({isLoading:!1,error:v.data?.error||"Unknown error"}),w.selectedThread){const S={id:`msg-${Date.now()}-error`,role:"assistant",content:`❌ **Execution Error** - -${v.data?.error||"Unknown error"}`,timestamp:new Date};w.addMessageToThread(w.selectedThread.id,S)}R.emit({type:"EXECUTION_COMPLETED",data:{threadId:w.selectedThread?.id||"unknown",finalState:w.executionContext.currentState,duration:0}})},onBreakpointHit:v=>{const w=e();w.pauseExecution(),v.node&&w.addInterrupt({id:`bp-${Date.now()}`,agentId:g.id,threadId:C||"",toolName:le(v.node)||v.node,toolArgs:v.data||{},reason:`Breakpoint hit at ${v.node}`,status:"pending",timestamp:new Date})},onError:v=>{console.error("❌ SSE error:",v);const w=e(),S=v instanceof Error?v.message:String(v);w.stopExecution(),r({isLoading:!1,error:S}),w.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:`SSE connection failed: ${S}`,data:{error:S}}),w.selectedThread&&w.addMessageToThread(w.selectedThread.id,{id:`msg-${Date.now()}-sse-error`,role:"assistant",content:`❌ **Connection Error** - -${S} - -The agent may not be reachable (check name/slug, server logs, and /studio/agents).`,timestamp:new Date}),R.emit({type:"EXECUTION_COMPLETED",data:{threadId:w.selectedThread?.id||"unknown",finalState:w.executionContext.currentState,duration:0}})},onDone:()=>{console.log("📡 SSE stream complete");const v=e();v.executionContext.isExecuting&&!v.executionContext.isPaused&&v.stopExecution(),r({isLoading:!1})}});r({activeAbortController:L});return}throw new Error("Studio API client not initialized. Cannot execute agent.")}catch(b){console.error("❌ Agentomatic execution error:",b);const f=e();if(f.stopExecution(),f.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:`Execution failed: ${b instanceof Error?b.message:"Unknown error"}`,data:{error:b instanceof Error?b.message:String(b)}}),f.selectedThread){const x={id:`msg-${Date.now()}-error`,role:"assistant",content:`❌ **Execution Error** - -Failed to execute: ${b instanceof Error?b.message:"Unknown error"}`,timestamp:new Date};f.addMessageToThread(f.selectedThread.id,x)}}})().catch(b=>{console.error("Failed to execute Agentomatic agent:",b),e().stopExecution()})},addInterrupt:t=>r(n=>(R.emit({type:"INTERRUPT_RECEIVED",data:t}),{activeInterrupts:[...n.activeInterrupts,t]})),resolveInterrupt:(t,n)=>r(a=>(R.emit({type:"INTERRUPT_RESOLVED",data:{interruptId:t,resolution:n}}),{activeInterrupts:a.activeInterrupts.map(o=>o.id===t?{...o,status:n==="approved"?"approved":"rejected",resolvedAt:new Date}:o)})),clearInterrupts:()=>r({activeInterrupts:[]}),addSubAgentResult:t=>r(n=>(R.emit({type:"SUB_AGENT_COMPLETED",data:t}),{subAgentResults:[...n.subAgentResults,t]})),clearSubAgentResults:()=>r({subAgentResults:[]}),reset:()=>r({...We,selectedThread:void 0,selectedAgent:void 0,selectedAssistant:void 0,threads:[],agents:[],assistants:[],runs:[],currentRun:void 0,executionContext:Fe,executionContexts:new Map,activeInterrupts:[],subAgentResults:[],agentSchemas:{},schemasLoading:!1,isStreaming:!1,streamingMessage:"",activeAbortController:null})}),{name:"studio-store"})),$o=(r,e,t=[])=>{const n=h.useRef(e);n.current=e,h.useEffect(()=>R.subscribe(r,o=>{n.current(o)}),[r,...t])},Oo=(r,e=[])=>{const t=h.useRef(r);t.current=r,h.useEffect(()=>R.subscribeAll(a=>{t.current(a)}),e)};function sn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"}))}const cn=h.forwardRef(sn);function dn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"}))}const ln=h.forwardRef(dn);function un({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 0 1-.825-.242m9.345-8.334a2.126 2.126 0 0 0-.476-.095 48.64 48.64 0 0 0-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0 0 11.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155"}))}const mn=h.forwardRef(un);function fn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"}))}const pt=h.forwardRef(fn);function pn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m19.5 8.25-7.5 7.5-7.5-7.5"}))}const hn=h.forwardRef(pn);function gn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 0v3.75m-16.5-3.75v3.75m16.5 0v3.75C20.25 16.153 16.556 18 12 18s-8.25-1.847-8.25-4.125v-3.75m16.5 0c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125"}))}const yn=h.forwardRef(gn);function xn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const bn=h.forwardRef(xn);function vn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4.5 12a7.5 7.5 0 0 0 15 0m-15 0a7.5 7.5 0 1 1 15 0m-15 0H3m16.5 0H21m-1.5 0H12m-8.457 3.077 1.41-.513m14.095-5.13 1.41-.513M5.106 17.785l1.15-.964m11.49-9.642 1.149-.964M7.501 19.795l.75-1.3m7.5-12.99.75-1.3m-6.063 16.658.26-1.477m2.605-14.772.26-1.477m0 17.726-.26-1.477M10.698 4.614l-.26-1.477M16.5 19.794l-.75-1.299M7.5 4.205 12 12m6.894 5.785-1.149-.964M6.256 7.178l-1.15-.964m15.352 8.864-1.41-.513M4.954 9.435l-1.41-.514M12.002 12l-3.75 6.495"}))}const pe=h.forwardRef(vn);function wn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m6.75 7.5 3 2.25-3 2.25m4.5 0h3m-9 8.25h13.5A2.25 2.25 0 0 0 21 18V6a2.25 2.25 0 0 0-2.25-2.25H5.25A2.25 2.25 0 0 0 3 6v12a2.25 2.25 0 0 0 2.25 2.25Z"}))}const Be=h.forwardRef(wn);function Cn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418"}))}const Sn=h.forwardRef(Cn);function En({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z"}))}const kn=h.forwardRef(En);function Tn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4.5v15m7.5-7.5h-15"}))}const An=h.forwardRef(Tn);function jn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 0 1 0 3.75H5.625a1.875 1.875 0 0 1 0-3.75Z"}))}const _n=h.forwardRef(jn);function Nn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"}))}const $n=h.forwardRef(Nn);function On({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"}))}const Rn=h.forwardRef(On);function Dn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"}))}const Mn=h.forwardRef(Dn);function Pn({title:r,titleId:e,...t},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},t),r?h.createElement("title",{id:e},r):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const In=h.forwardRef(Pn),Ln=()=>{const{assistants:r,selectedAssistant:e,setSelectedAssistant:t,currentView:n,setCurrentView:a,darkMode:o,setDarkMode:s,sidebarCollapsed:i,setSidebarCollapsed:l,config:d,fetchGraphData:u,refreshThreads:m,connectionStatus:p,retryAttempts:y,maxRetryAttempts:b,attemptReconnection:f}=me(),[x,g]=h.useState(!1),C=h.useRef(null),k=h.useRef(null),[j,_]=h.useState({top:0,left:0,width:0});h.useEffect(()=>{const E=V=>{C.current&&!C.current.contains(V.target)&&k.current&&!k.current.contains(V.target)&&g(!1)};if(x)return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[x]),h.useEffect(()=>{if(x&&k.current){const E=()=>{const D=k.current.getBoundingClientRect();_({top:D.bottom+8,left:D.left,width:D.width})};E();const V=()=>E(),O=()=>E();return window.addEventListener("scroll",V,!0),window.addEventListener("resize",O),()=>{window.removeEventListener("scroll",V,!0),window.removeEventListener("resize",O)}}},[x]);const A=async E=>{t(E),g(!1);try{await u(E.id),await m(E.id)}catch(V){console.error("Failed to fetch graph data:",V)}},I=E=>{switch(E){case"langgraph":return o?"bg-emerald-900 text-emerald-300":"bg-emerald-100 text-emerald-700";case"deepagent":return o?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-700";case"langchain":return o?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700";default:return o?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}},U=[{key:"graph",label:"Graph",icon:Be},{key:"chat",label:"Chat",icon:mn},{key:"debug",label:"Debug",icon:pe},{key:"pipelines",label:"Pipelines",icon:Be},{key:"builder",label:"Builder",icon:$n},{key:"plugins",label:"Plugins",icon:pe},{key:"ingestion",label:"Ingestors",icon:Be},{key:"tasks",label:"Tasks",icon:_n},{key:"control",label:"Control",icon:cn},{key:"endpoints",label:"Endpoints",icon:Sn},{key:"connections",label:"Connections",icon:yn}];return c.jsxs("header",{className:`flex min-h-16 items-center justify-between gap-2 px-3 py-2 sm:px-6 border-b backdrop-blur-sm transition-colors duration-300 ${o?"bg-gray-800/95 border-gray-700 text-white":"bg-white/95 border-gray-200 text-gray-900"}`,children:[c.jsxs("div",{className:"flex min-w-0 items-center space-x-2 sm:space-x-4",children:[c.jsx("button",{onClick:()=>l(!i),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-gray-300":"hover:bg-gray-100 text-gray-600"}`,title:i?"Show Sidebar":"Hide Sidebar",children:i?c.jsx(ln,{className:"w-5 h-5"}):c.jsx(In,{className:"w-5 h-5"})}),c.jsxs("div",{className:"flex items-center space-x-2 sm:space-x-3",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-violet-600",children:c.jsx("span",{className:"text-white font-bold text-sm",children:"AS"})}),c.jsxs("div",{className:"hidden sm:block",children:[c.jsx("h1",{className:"text-lg font-semibold",children:"Agentomatic Studio"}),c.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:p==="connected"?"Connected":"Reconnecting…"})]})]}),c.jsx("nav",{className:`hidden 2xl:flex min-w-0 items-center space-x-1 rounded-xl p-1 ml-3 xl:ml-6 overflow-x-auto ${o?"bg-gray-700":"bg-gray-100"}`,children:U.map(({key:E,label:V,icon:O})=>c.jsxs("button",{onClick:()=>a(E),className:`flex shrink-0 items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${n===E?o?"bg-blue-600 text-white shadow-lg transform scale-105":"bg-white text-blue-600 shadow-md transform scale-105":o?"text-gray-300 hover:text-white hover:bg-gray-600":"text-gray-600 hover:text-gray-900 hover:bg-white/50"}`,children:[c.jsx(O,{className:"w-4 h-4 mr-2"}),V]},E))}),c.jsx("select",{value:n,onChange:E=>a(E.target.value),"aria-label":"Select Studio view",className:`max-w-28 rounded-lg border px-2 py-2 text-sm font-medium sm:max-w-36 md:max-w-44 2xl:hidden ${o?"border-gray-600 bg-gray-700 text-white":"border-gray-300 bg-white text-gray-900"}`,children:U.map(({key:E,label:V})=>c.jsx("option",{value:E,children:V},E))})]}),c.jsx("div",{className:"flex flex-1 justify-end sm:justify-center",children:c.jsxs("div",{className:"relative",ref:C,children:[c.jsxs("button",{onClick:()=>g(!x),className:`flex max-w-[13rem] items-center space-x-2 px-2 py-2 sm:max-w-none sm:space-x-3 sm:px-4 rounded-xl border transition-all duration-200 ${o?"bg-gray-700 border-gray-600 text-white hover:bg-gray-600":"bg-white border-gray-300 text-gray-900 hover:bg-gray-50"}`,ref:k,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${o?"bg-blue-600":"bg-blue-100"}`,children:c.jsx(pe,{className:`w-4 h-4 ${o?"text-white":"text-blue-600"}`})}),c.jsxs("div",{className:"min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx("span",{className:"truncate text-sm font-medium",children:e?.name||"Select Agent"}),e?.metadata?.framework&&c.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full font-medium ${I(e.metadata.framework)}`,children:e.metadata.framework})]}),c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:e?.description||"No agent selected"})]}),c.jsx(hn,{className:`w-4 h-4 transition-transform ${x?"rotate-180":""}`})]}),x&&Mt.createPortal(c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fixed inset-0 z-[999998] bg-black/10",onClick:()=>g(!1)}),c.jsx("div",{ref:C,className:`fixed rounded-xl border shadow-2xl z-[999999] ${o?"bg-gray-800 border-gray-600":"bg-white border-gray-200"}`,style:{top:j.top,left:j.left,width:Math.max(j.width,320),maxHeight:"400px"},children:c.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:r.length===0?c.jsxs("div",{className:`p-4 text-center ${o?"text-gray-400":"text-gray-500"}`,children:[c.jsx(pe,{className:`w-8 h-8 mx-auto mb-2 ${o?"text-gray-600":"text-gray-300"}`}),c.jsx("p",{className:"text-sm",children:"No agents available"}),c.jsx("p",{className:"text-xs mt-1",children:"Check your server connection"})]}):r.map(E=>c.jsxs("button",{onClick:()=>A(E),className:`w-full flex items-center space-x-3 p-3 rounded-lg transition-colors ${e?.id===E.id?o?"bg-blue-900 border border-blue-700":"bg-blue-50 border border-blue-200":o?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${e?.id===E.id?"bg-blue-600":o?"bg-gray-600":"bg-gray-200"}`,children:c.jsx(pe,{className:`w-4 h-4 ${e?.id===E.id?"text-white":o?"text-gray-300":"text-gray-600"}`})}),c.jsxs("div",{className:"flex-1 text-left",children:[c.jsx("div",{className:`text-sm font-medium ${o?"text-white":"text-gray-900"}`,children:E.name}),E.description&&c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:E.description}),c.jsxs("div",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:["Graph: ",E.graph_id]})]}),e?.id===E.id&&c.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full"})]},E.id))})})]}),document.body)]})}),c.jsxs("div",{className:"flex items-center space-x-1.5 sm:space-x-3",children:[c.jsxs("div",{className:"hidden items-center space-x-2 xl:flex",children:[c.jsx("div",{className:`w-2 h-2 rounded-full ${p==="connected"?"bg-green-500 animate-pulse":p==="reconnecting"?"bg-yellow-500 animate-spin":p==="failed"?"bg-red-500":"bg-gray-500"}`}),c.jsx("span",{className:`text-sm ${o?"text-gray-300":"text-gray-600"}`,children:p==="connected"?c.jsx("span",{title:d.apiUrl,children:d.apiUrl.replace(/^https?:\/\//,"").slice(0,25)}):p==="reconnecting"?`Reconnecting (${y}/${b})`:p==="failed"?"Connection Failed":"Disconnected"}),(p==="disconnected"||p==="failed")&&c.jsx("button",{onClick:f,className:`px-2 py-1 text-xs rounded transition-colors ${o?"bg-blue-600 text-white hover:bg-blue-700":"bg-blue-500 text-white hover:bg-blue-600"}`,title:"Retry Connection",children:"Retry"})]}),c.jsx("button",{onClick:()=>s(!o),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-yellow-400":"hover:bg-gray-100 text-gray-600"}`,title:o?"Switch to Light Mode":"Switch to Dark Mode",children:o?c.jsx(Rn,{className:"w-5 h-5"}):c.jsx(kn,{className:"w-5 h-5"})}),c.jsx("div",{className:`hidden text-xs px-2 py-1 rounded 2xl:block ${o?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-500"}`,children:"⌘1-9 to switch views"})]})]})};function ce(r){if(r===null||r===!0||r===!1)return NaN;var e=Number(r);return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}function B(r,e){if(e.length1?"s":"")+" required, but only "+e.length+" present")}function Q(r){B(1,arguments);var e=Object.prototype.toString.call(r);return r instanceof Date||Et(r)==="object"&&e==="[object Date]"?new Date(r.getTime()):typeof r=="number"||e==="[object Number]"?new Date(r):((typeof r=="string"||e==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function Un(r,e){B(2,arguments);var t=Q(r).getTime(),n=ce(e);return new Date(t+n)}var qn={};function Oe(){return qn}function Vn(r){var e=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()));return e.setUTCFullYear(r.getFullYear()),r.getTime()-e.getTime()}function Wn(r){return B(1,arguments),r instanceof Date||Et(r)==="object"&&Object.prototype.toString.call(r)==="[object Date]"}function Fn(r){if(B(1,arguments),!Wn(r)&&typeof r!="number")return!1;var e=Q(r);return!isNaN(Number(e))}function Bn(r,e){B(2,arguments);var t=ce(e);return Un(r,-t)}var zn=864e5;function Yn(r){B(1,arguments);var e=Q(r),t=e.getTime();e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);var n=e.getTime(),a=t-n;return Math.floor(a/zn)+1}function je(r){B(1,arguments);var e=1,t=Q(r),n=t.getUTCDay(),a=(n=a.getTime()?t+1:e.getTime()>=s.getTime()?t:t-1}function Hn(r){B(1,arguments);var e=$t(r),t=new Date(0);t.setUTCFullYear(e,0,4),t.setUTCHours(0,0,0,0);var n=je(t);return n}var Gn=6048e5;function Kn(r){B(1,arguments);var e=Q(r),t=je(e).getTime()-Hn(e).getTime();return Math.round(t/Gn)+1}function _e(r,e){var t,n,a,o,s,i,l,d;B(1,arguments);var u=Oe(),m=ce((t=(n=(a=(o=e?.weekStartsOn)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.weekStartsOn)!==null&&a!==void 0?a:u.weekStartsOn)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.weekStartsOn)!==null&&t!==void 0?t:0);if(!(m>=0&&m<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var p=Q(r),y=p.getUTCDay(),b=(y=1&&y<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var b=new Date(0);b.setUTCFullYear(m+1,0,y),b.setUTCHours(0,0,0,0);var f=_e(b,e),x=new Date(0);x.setUTCFullYear(m,0,y),x.setUTCHours(0,0,0,0);var g=_e(x,e);return u.getTime()>=f.getTime()?m+1:u.getTime()>=g.getTime()?m:m-1}function Jn(r,e){var t,n,a,o,s,i,l,d;B(1,arguments);var u=Oe(),m=ce((t=(n=(a=(o=e?.firstWeekContainsDate)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.firstWeekContainsDate)!==null&&a!==void 0?a:u.firstWeekContainsDate)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&t!==void 0?t:1),p=Ot(r,e),y=new Date(0);y.setUTCFullYear(p,0,m),y.setUTCHours(0,0,0,0);var b=_e(y,e);return b}var Xn=6048e5;function Qn(r,e){B(1,arguments);var t=Q(r),n=_e(t,e).getTime()-Jn(t,e).getTime();return Math.round(n/Xn)+1}function $(r,e){for(var t=r<0?"-":"",n=Math.abs(r).toString();n.length0?n:1-n;return $(t==="yy"?a%100:a,t.length)},M:function(e,t){var n=e.getUTCMonth();return t==="M"?String(n+1):$(n+1,2)},d:function(e,t){return $(e.getUTCDate(),t.length)},a:function(e,t){var n=e.getUTCHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h:function(e,t){return $(e.getUTCHours()%12||12,t.length)},H:function(e,t){return $(e.getUTCHours(),t.length)},m:function(e,t){return $(e.getUTCMinutes(),t.length)},s:function(e,t){return $(e.getUTCSeconds(),t.length)},S:function(e,t){var n=t.length,a=e.getUTCMilliseconds(),o=Math.floor(a*Math.pow(10,n-3));return $(o,t.length)}},ue={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Zn={G:function(e,t,n){var a=e.getUTCFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});default:return n.era(a,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){var a=e.getUTCFullYear(),o=a>0?a:1-a;return n.ordinalNumber(o,{unit:"year"})}return te.y(e,t)},Y:function(e,t,n,a){var o=Ot(e,a),s=o>0?o:1-o;if(t==="YY"){var i=s%100;return $(i,2)}return t==="Yo"?n.ordinalNumber(s,{unit:"year"}):$(s,t.length)},R:function(e,t){var n=$t(e);return $(n,t.length)},u:function(e,t){var n=e.getUTCFullYear();return $(n,t.length)},Q:function(e,t,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(t){case"Q":return String(a);case"QQ":return $(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(e,t,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(t){case"q":return String(a);case"qq":return $(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(e,t,n){var a=e.getUTCMonth();switch(t){case"M":case"MM":return te.M(e,t);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(e,t,n){var a=e.getUTCMonth();switch(t){case"L":return String(a+1);case"LL":return $(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(e,t,n,a){var o=Qn(e,a);return t==="wo"?n.ordinalNumber(o,{unit:"week"}):$(o,t.length)},I:function(e,t,n){var a=Kn(e);return t==="Io"?n.ordinalNumber(a,{unit:"week"}):$(a,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getUTCDate(),{unit:"date"}):te.d(e,t)},D:function(e,t,n){var a=Yn(e);return t==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):$(a,t.length)},E:function(e,t,n){var a=e.getUTCDay();switch(t){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(e,t,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(t){case"e":return String(s);case"ee":return $(s,2);case"eo":return n.ordinalNumber(s,{unit:"day"});case"eee":return n.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(o,{width:"short",context:"formatting"});default:return n.day(o,{width:"wide",context:"formatting"})}},c:function(e,t,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(t){case"c":return String(s);case"cc":return $(s,t.length);case"co":return n.ordinalNumber(s,{unit:"day"});case"ccc":return n.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(o,{width:"narrow",context:"standalone"});case"cccccc":return n.day(o,{width:"short",context:"standalone"});default:return n.day(o,{width:"wide",context:"standalone"})}},i:function(e,t,n){var a=e.getUTCDay(),o=a===0?7:a;switch(t){case"i":return String(o);case"ii":return $(o,t.length);case"io":return n.ordinalNumber(o,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(e,t,n){var a=e.getUTCHours(),o=a/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,t,n){var a=e.getUTCHours(),o;switch(a===12?o=ue.noon:a===0?o=ue.midnight:o=a/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,t,n){var a=e.getUTCHours(),o;switch(a>=17?o=ue.evening:a>=12?o=ue.afternoon:a>=4?o=ue.morning:o=ue.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){var a=e.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return te.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getUTCHours(),{unit:"hour"}):te.H(e,t)},K:function(e,t,n){var a=e.getUTCHours()%12;return t==="Ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,t.length)},k:function(e,t,n){var a=e.getUTCHours();return a===0&&(a=24),t==="ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getUTCMinutes(),{unit:"minute"}):te.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getUTCSeconds(),{unit:"second"}):te.s(e,t)},S:function(e,t){return te.S(e,t)},X:function(e,t,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();if(s===0)return"Z";switch(t){case"X":return gt(s);case"XXXX":case"XX":return se(s);default:return se(s,":")}},x:function(e,t,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(t){case"x":return gt(s);case"xxxx":case"xx":return se(s);default:return se(s,":")}},O:function(e,t,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},z:function(e,t,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},t:function(e,t,n,a){var o=a._originalDate||e,s=Math.floor(o.getTime()/1e3);return $(s,t.length)},T:function(e,t,n,a){var o=a._originalDate||e,s=o.getTime();return $(s,t.length)}};function ht(r,e){var t=r>0?"-":"+",n=Math.abs(r),a=Math.floor(n/60),o=n%60;if(o===0)return t+String(a);var s=e;return t+String(a)+s+$(o,2)}function gt(r,e){if(r%60===0){var t=r>0?"-":"+";return t+$(Math.abs(r)/60,2)}return se(r,e)}function se(r,e){var t=e||"",n=r>0?"-":"+",a=Math.abs(r),o=$(Math.floor(a/60),2),s=$(a%60,2);return n+o+t+s}var yt=function(e,t){switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});default:return t.date({width:"full"})}},Rt=function(e,t){switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});default:return t.time({width:"full"})}},ea=function(e,t){var n=e.match(/(P+)(p+)?/)||[],a=n[1],o=n[2];if(!o)return yt(e,t);var s;switch(a){case"P":s=t.dateTime({width:"short"});break;case"PP":s=t.dateTime({width:"medium"});break;case"PPP":s=t.dateTime({width:"long"});break;default:s=t.dateTime({width:"full"});break}return s.replace("{{date}}",yt(a,t)).replace("{{time}}",Rt(o,t))},ta={p:Rt,P:ea},ra=["D","DD"],na=["YY","YYYY"];function aa(r){return ra.indexOf(r)!==-1}function oa(r){return na.indexOf(r)!==-1}function xt(r,e,t){if(r==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e,"`) for formatting years to the input `").concat(t,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(r==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(e,"`) for formatting years to the input `").concat(t,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(r==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(e,"`) for formatting days of the month to the input `").concat(t,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(r==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(e,"`) for formatting days of the month to the input `").concat(t,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var sa={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},ia=function(e,t,n){var a,o=sa[e];return typeof o=="string"?a=o:t===1?a=o.one:a=o.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a};function ze(r){return function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.width?String(e.width):r.defaultWidth,n=r.formats[t]||r.formats[r.defaultWidth];return n}}var ca={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},da={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},la={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ua={date:ze({formats:ca,defaultWidth:"full"}),time:ze({formats:da,defaultWidth:"full"}),dateTime:ze({formats:la,defaultWidth:"full"})},ma={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},fa=function(e,t,n,a){return ma[e]};function he(r){return function(e,t){var n=t!=null&&t.context?String(t.context):"standalone",a;if(n==="formatting"&&r.formattingValues){var o=r.defaultFormattingWidth||r.defaultWidth,s=t!=null&&t.width?String(t.width):o;a=r.formattingValues[s]||r.formattingValues[o]}else{var i=r.defaultWidth,l=t!=null&&t.width?String(t.width):r.defaultWidth;a=r.values[l]||r.values[i]}var d=r.argumentCallback?r.argumentCallback(e):e;return a[d]}}var pa={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ha={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},ga={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},ya={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},xa={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},ba={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},va=function(e,t){var n=Number(e),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},wa={ordinalNumber:va,era:he({values:pa,defaultWidth:"wide"}),quarter:he({values:ha,defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:he({values:ga,defaultWidth:"wide"}),day:he({values:ya,defaultWidth:"wide"}),dayPeriod:he({values:xa,defaultWidth:"wide",formattingValues:ba,defaultFormattingWidth:"wide"})};function ge(r){return function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t.width,a=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],o=e.match(a);if(!o)return null;var s=o[0],i=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],l=Array.isArray(i)?Sa(i,function(m){return m.test(s)}):Ca(i,function(m){return m.test(s)}),d;d=r.valueCallback?r.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;var u=e.slice(s.length);return{value:d,rest:u}}}function Ca(r,e){for(var t in r)if(r.hasOwnProperty(t)&&e(r[t]))return t}function Sa(r,e){for(var t=0;t1&&arguments[1]!==void 0?arguments[1]:{},n=e.match(r.matchPattern);if(!n)return null;var a=n[0],o=e.match(r.parsePattern);if(!o)return null;var s=r.valueCallback?r.valueCallback(o[0]):o[0];s=t.valueCallback?t.valueCallback(s):s;var i=e.slice(a.length);return{value:s,rest:i}}}var ka=/^(\d+)(th|st|nd|rd)?/i,Ta=/\d+/i,Aa={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},ja={any:[/^b/i,/^(a|c)/i]},_a={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Na={any:[/1/i,/2/i,/3/i,/4/i]},$a={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Oa={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Ra={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Da={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Ma={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Pa={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Ia={ordinalNumber:Ea({matchPattern:ka,parsePattern:Ta,valueCallback:function(e){return parseInt(e,10)}}),era:ge({matchPatterns:Aa,defaultMatchWidth:"wide",parsePatterns:ja,defaultParseWidth:"any"}),quarter:ge({matchPatterns:_a,defaultMatchWidth:"wide",parsePatterns:Na,defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:ge({matchPatterns:$a,defaultMatchWidth:"wide",parsePatterns:Oa,defaultParseWidth:"any"}),day:ge({matchPatterns:Ra,defaultMatchWidth:"wide",parsePatterns:Da,defaultParseWidth:"any"}),dayPeriod:ge({matchPatterns:Ma,defaultMatchWidth:"any",parsePatterns:Pa,defaultParseWidth:"any"})},La={code:"en-US",formatDistance:ia,formatLong:ua,formatRelative:fa,localize:wa,match:Ia,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ua=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,qa=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Va=/^'([^]*?)'?$/,Wa=/''/g,Fa=/[a-zA-Z]/;function Ba(r,e,t){var n,a,o,s,i,l,d,u,m,p,y,b,f,x;B(2,arguments);var g=String(e),C=Oe(),k=(n=(a=void 0)!==null&&a!==void 0?a:C.locale)!==null&&n!==void 0?n:La,j=ce((o=(s=(i=(l=void 0)!==null&&l!==void 0?l:void 0)!==null&&i!==void 0?i:C.firstWeekContainsDate)!==null&&s!==void 0?s:(d=C.locale)===null||d===void 0||(u=d.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&o!==void 0?o:1);if(!(j>=1&&j<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var _=ce((m=(p=(y=(b=void 0)!==null&&b!==void 0?b:void 0)!==null&&y!==void 0?y:C.weekStartsOn)!==null&&p!==void 0?p:(f=C.locale)===null||f===void 0||(x=f.options)===null||x===void 0?void 0:x.weekStartsOn)!==null&&m!==void 0?m:0);if(!(_>=0&&_<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!k.localize)throw new RangeError("locale must contain localize property");if(!k.formatLong)throw new RangeError("locale must contain formatLong property");var A=Q(r);if(!Fn(A))throw new RangeError("Invalid time value");var I=Vn(A),U=Bn(A,I),E={firstWeekContainsDate:j,weekStartsOn:_,locale:k,_originalDate:A},V=g.match(qa).map(function(O){var D=O[0];if(D==="p"||D==="P"){var J=ta[D];return J(O,k.formatLong)}return O}).join("").match(Ua).map(function(O){if(O==="''")return"'";var D=O[0];if(D==="'")return za(O);var J=Zn[D];if(J)return oa(O)&&xt(O,e,String(r)),aa(O)&&xt(O,e,String(r)),J(U,O,k.localize,E);if(D.match(Fa))throw new RangeError("Format string contains an unescaped latin alphabet character `"+D+"`");return O}).join("");return V}function za(r){var e=r.match(Va);return e?e[1].replace(Wa,"'"):r}const Ya=()=>{const{threads:r,selectedThread:e,setSelectedThread:t,createPersistentThread:n,deletePersistentThread:a,hydrateThreadMessages:o,selectedAssistant:s,darkMode:i}=me(),[l,d]=h.useState(null),[u,m]=h.useState(null),p=async()=>{if(!s?.id){m("Select a live agent before creating a thread.");return}d("new"),m(null);try{await n(s.id,`Thread ${r.length+1}`)}catch(f){m(f?.message||"Could not create a durable thread.")}finally{d(null)}},y=async f=>{const x=f.agentId||s?.id;d(`load:${f.id}`),m(null);try{const g=x?await o(f.id,x):void 0;t(g||f)}catch(g){m(g?.message||"Could not load this thread’s durable history."),t(f)}finally{d(null)}},b=async(f,x)=>{x.stopPropagation(),d(`delete:${f.id}`),m(null);try{await a(f)}catch(g){m(g?.message||"Could not delete the durable thread.")}finally{d(null)}};return c.jsxs("div",{className:`h-full flex flex-col ${i?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} border-r transition-colors duration-300`,children:[c.jsxs("div",{className:`p-4 border-b ${i?"border-gray-700":"border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(pt,{className:`w-5 h-5 ${i?"text-blue-400":"text-blue-600"}`}),c.jsx("h2",{className:`text-lg font-semibold ${i?"text-white":"text-gray-900"}`,children:"Threads"})]}),c.jsx("div",{className:`px-2 py-1 rounded-full text-xs font-medium ${i?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:r.length})]}),c.jsxs("button",{onClick:()=>{p()},disabled:l!==null,className:`w-full flex items-center justify-center px-4 py-3 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md ${i?"bg-blue-600 hover:bg-blue-700 text-white hover:scale-105":"bg-blue-600 text-white hover:bg-blue-700 hover:scale-105"}`,children:[c.jsx(An,{className:"w-4 h-4 mr-2"}),l==="new"?"Creating…":"New Thread"]})]}),u&&c.jsx("p",{role:"alert",className:`mx-4 mb-3 rounded-md border p-2 text-xs ${i?"border-red-800 bg-red-950/40 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:u}),c.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:r.length===0?c.jsxs("div",{className:`p-6 text-center ${i?"text-gray-400":"text-gray-500"}`,children:[c.jsx("div",{className:`w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center ${i?"bg-gray-700":"bg-gray-100"}`,children:c.jsx(pt,{className:`w-8 h-8 ${i?"text-gray-500":"text-gray-400"}`})}),c.jsx("h3",{className:`text-sm font-medium mb-2 ${i?"text-gray-300":"text-gray-700"}`,children:"No threads yet"}),c.jsx("p",{className:"text-xs leading-relaxed",children:"Create your first thread to start a conversation with your agent"})]}):c.jsx("div",{className:"p-3 space-y-2",children:r.map(f=>c.jsxs("div",{onClick:()=>{y(f)},className:`group relative p-4 rounded-xl cursor-pointer transition-all duration-200 ${e?.id===f.id?i?"bg-blue-900/50 border-2 border-blue-600 shadow-lg":"bg-blue-50 border-2 border-blue-200 shadow-md":i?"hover:bg-gray-700 border-2 border-transparent hover:border-gray-600":"hover:bg-gray-50 border-2 border-transparent hover:border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-start justify-between",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center space-x-2 mb-2",children:[c.jsx("h3",{className:`text-sm font-semibold truncate ${e?.id===f.id?i?"text-blue-300":"text-blue-700":i?"text-white":"text-gray-900"}`,children:f.name}),f.messages.length>0&&c.jsx("span",{className:`px-2 py-0.5 text-xs rounded-full font-medium ${e?.id===f.id?i?"bg-blue-800 text-blue-200":"bg-blue-100 text-blue-700":i?"bg-gray-600 text-gray-300":"bg-gray-200 text-gray-600"}`,children:f.messages.length})]}),f.messages.length>0?c.jsx("p",{className:`text-xs line-clamp-2 mb-2 ${e?.id===f.id?i?"text-blue-400":"text-blue-600":i?"text-gray-400":"text-gray-500"}`,children:f.messages[f.messages.length-1].content}):c.jsx("p",{className:`text-xs italic mb-2 ${e?.id===f.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:"No messages yet"}),c.jsxs("div",{className:`flex items-center space-x-1 text-xs ${e?.id===f.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:[c.jsx(bn,{className:"w-3 h-3"}),c.jsx("span",{children:Ba(f.updatedAt,"MMM d, HH:mm")})]})]}),c.jsx("button",{onClick:x=>{b(f,x)},disabled:l!==null,className:`opacity-0 group-hover:opacity-100 p-1.5 rounded-lg transition-all duration-200 ${i?"hover:bg-red-900 text-gray-400 hover:text-red-300":"hover:bg-red-50 text-gray-400 hover:text-red-600"}`,title:"Delete thread",children:l===`delete:${f.id}`?"…":c.jsx(Mn,{className:"w-4 h-4"})})]}),e?.id===f.id&&c.jsx("div",{className:`absolute left-0 top-1/2 transform -translate-y-1/2 w-1 h-8 rounded-r-full ${i?"bg-blue-400":"bg-blue-600"}`})]},f.id))})}),r.length>0&&c.jsx("div",{className:`p-4 border-t ${i?"border-gray-700":"border-gray-200"}`,children:c.jsxs("div",{className:`text-xs text-center ${i?"text-gray-500":"text-gray-400"}`,children:[r.length," thread",r.length!==1?"s":""," •",r.reduce((f,x)=>f+x.messages.length,0)," total messages"]})})]})},Ha=({children:r})=>{const{darkMode:e}=me();return c.jsx("div",{className:`flex-1 flex flex-col min-h-0 overflow-hidden ${e?"bg-gray-900":"bg-gray-50"}`,style:{height:"100%"},children:r})},Ga=z.lazy(()=>K(async()=>{const{GraphView:r}=await import("./GraphView-bgnAIRJp.js");return{GraphView:r}},__vite__mapDeps([0,1,2,3,4])).then(({GraphView:r})=>({default:r}))),bt=z.lazy(()=>K(async()=>{const{ChatView:r}=await import("./ChatView-SPDbgpwb.js");return{ChatView:r}},__vite__mapDeps([5,1,2,3,4,6])).then(({ChatView:r})=>({default:r}))),Ka=z.lazy(()=>K(async()=>{const{DebugView:r}=await import("./DebugView-v__T__mW.js");return{DebugView:r}},__vite__mapDeps([7,1,6,4])).then(({DebugView:r})=>({default:r}))),Ja=z.lazy(()=>K(async()=>{const{PipelinesView:r}=await import("./PipelinesView-8o6MHHuZ.js");return{PipelinesView:r}},__vite__mapDeps([8,1,2,3,4])).then(({PipelinesView:r})=>({default:r}))),Xa=z.lazy(()=>K(async()=>{const{BuilderView:r}=await import("./BuilderView-Aw10hiXI.js");return{BuilderView:r}},__vite__mapDeps([9,1,10,2,4])).then(({BuilderView:r})=>({default:r}))),Qa=z.lazy(()=>K(async()=>{const{PluginsView:r}=await import("./PluginsView-T_czY3dU.js");return{PluginsView:r}},__vite__mapDeps([11,1,2,3,4])).then(({PluginsView:r})=>({default:r}))),Za=z.lazy(()=>K(async()=>{const{IngestorsView:r}=await import("./IngestorsView-q0ceZCW0.js");return{IngestorsView:r}},__vite__mapDeps([12,1,2,3,4])).then(({IngestorsView:r})=>({default:r}))),eo=z.lazy(()=>K(async()=>{const{TasksView:r}=await import("./TasksView-HJeIPOTt.js");return{TasksView:r}},__vite__mapDeps([13,1,2,3,4])).then(({TasksView:r})=>({default:r}))),to=z.lazy(()=>K(async()=>{const{ControlPlaneView:r}=await import("./ControlPlaneView-ba4D_JM4.js");return{ControlPlaneView:r}},__vite__mapDeps([14,1,4])).then(({ControlPlaneView:r})=>({default:r}))),ro=z.lazy(()=>K(async()=>{const{EndpointsView:r}=await import("./EndpointsView-uQLIFHRE.js");return{EndpointsView:r}},__vite__mapDeps([15,1,2,3,4])).then(({EndpointsView:r})=>({default:r}))),no=z.lazy(()=>K(async()=>{const{ConnectionsView:r}=await import("./ConnectionsView-wfIgs5wX.js");return{ConnectionsView:r}},__vite__mapDeps([16,1,3,4])).then(({ConnectionsView:r})=>({default:r})));class ao extends z.Component{constructor(){super(...arguments),this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidUpdate(e){e.view!==this.props.view&&this.state.failed&&this.setState({failed:!1})}render(){return this.state.failed?c.jsxs("div",{role:"alert",className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center ${this.props.darkMode?"text-gray-200":"text-gray-800"}`,children:[c.jsxs("div",{children:[c.jsx("h2",{className:"text-lg font-semibold",children:"Workspace could not load"}),c.jsx("p",{className:`mt-1 max-w-md text-sm ${this.props.darkMode?"text-gray-400":"text-gray-600"}`,children:"A Studio module could not be loaded. Reload to fetch the current deployment assets."})]}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-lg bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700",children:"Reload Studio"})]}):this.props.children}}const oo=()=>{const{currentView:r,setCurrentView:e,sidebarCollapsed:t,setSidebarCollapsed:n,darkMode:a}=me();h.useEffect(()=>{r||e("chat")},[r,e]),h.useEffect(()=>{const i=window.matchMedia("(max-width: 767px)"),l=()=>{i.matches&&n(!0)};return l(),i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[n]),h.useEffect(()=>{const i=l=>{if(l.ctrlKey||l.metaKey)switch(l.key){case"1":l.preventDefault(),e("chat");break;case"2":l.preventDefault(),e("graph");break;case"3":l.preventDefault(),e("debug");break;case"4":l.preventDefault(),e("pipelines");break;case"9":l.preventDefault(),e("builder");break;case"5":l.preventDefault(),e("plugins");break;case"0":l.preventDefault(),e("ingestion");break;case"-":l.preventDefault(),e("tasks");break;case"6":l.preventDefault(),e("control");break;case"7":l.preventDefault(),e("endpoints");break;case"8":l.preventDefault(),e("connections");break}};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[e]);const o=()=>{switch(r){case"graph":return c.jsx(Ga,{});case"chat":return c.jsx(bt,{});case"debug":return c.jsx(Ka,{});case"pipelines":return c.jsx(Ja,{});case"builder":return c.jsx(Xa,{});case"plugins":return c.jsx(Qa,{});case"ingestion":return c.jsx(Za,{});case"tasks":return c.jsx(eo,{});case"control":return c.jsx(to,{});case"endpoints":return c.jsx(ro,{});case"connections":return c.jsx(no,{});default:return c.jsx(bt,{})}},s=c.jsx("div",{className:`flex h-full items-center justify-center p-6 text-sm ${a?"text-gray-400":"text-gray-600"}`,role:"status",children:"Loading workspace…"});return c.jsxs("div",{className:`h-screen w-screen flex flex-col overflow-hidden ${a?"bg-gray-900":"bg-gray-50"}`,children:[c.jsx("div",{className:"flex-shrink-0",children:c.jsx(Ln,{})}),c.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden",children:[!t&&c.jsx("button",{type:"button","aria-label":"Close thread sidebar",className:"absolute inset-0 z-30 bg-black/35 md:hidden",onClick:()=>n(!0)}),c.jsx("div",{className:`flex-shrink-0 transition-all duration-300 ease-in-out overflow-hidden ${t?"w-0":"absolute inset-y-0 left-0 z-40 w-80 shadow-2xl md:static md:w-72 md:shadow-none xl:w-80"}`,style:{height:"100%"},children:c.jsx(Ya,{})}),c.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:c.jsx(Ha,{children:c.jsx(ao,{darkMode:a,view:r,children:c.jsx(h.Suspense,{fallback:s,children:o()})})})})]})]})},so=8e3,X=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),q=(r,e)=>{const t=r?.[e];return X(t)?t:void 0},io=r=>r!==null&&typeof r.name=="string"&&(r.in==="query"||r.in==="header"||r.in==="path"),Ye=(r,e="")=>typeof r=="string"?r:e,co=r=>Array.isArray(r)?r.filter(e=>typeof e=="string"):[];class Xe{constructor(e,t,n=so){this.openApiDocument=null,this.baseUrl=e.replace(/\/$/,""),this.apiKey=t||null,this.timeoutMs=n,this.headers={"Content-Type":"application/json",...this.apiKey?{"X-Api-Key":this.apiKey,Authorization:`Bearer ${this.apiKey}`}:{}}}async request(e,t){const n=`${this.baseUrl}${e}`,a=new AbortController,o=setTimeout(()=>a.abort(),this.timeoutMs),s=t?.signal;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));try{const i=await fetch(n,{...t,signal:a.signal,headers:{...this.headers,...t?.headers}});if(!i.ok){const d=await i.text().catch(()=>"");throw new ye(i.status,i.statusText,d)}if(i.status===204||t?.method?.toUpperCase()==="HEAD")return null;const l=await i.text();return l?JSON.parse(l):null}catch(i){throw X(i)&&i.name==="AbortError"?new ye(408,"Request Timeout",`Timed out after ${this.timeoutMs}ms: ${e}`):i}finally{clearTimeout(o)}}async getServerInfo(){return this.request("/studio/info")}async getOperationContract(e,t="post"){if(!this.openApiDocument){const T=this.request("/openapi.json");this.openApiDocument=T,T.catch(()=>{this.openApiDocument===T&&(this.openApiDocument=null)})}const n=await this.openApiDocument,a=q(n,"components"),o=q(q(n,"paths"),e)||(()=>{const P=q(n,"paths")||{};for(const K of Object.keys(P)){if(!K.includes("{"))continue;const Z=new RegExp("^"+K.replace(/[.*+?^$()|[\]\\]/g,"\\$&").replace(/\{[^}]+\}/g,"[^/]+")+"$");if(Z.test(e))return P[K]}})(),s=q(o,t.toLowerCase());if(!s)throw new ye(404,"Operation not found",`${t.toUpperCase()} ${e}`);const i=T=>{if(!X(T))return null;const L=typeof T.$ref=="string"?T.$ref:"";if(!L.startsWith("#/components/schemas/"))return{...T,...a?{components:a}:{}};const v=L.slice(21),w=q(q(a,"schemas"),v);return X(w)?{...w,...a?{components:a}:{}}:null},l=T=>{if(!X(T))return null;const L=typeof T.$ref=="string"?T.$ref:"";if(!L.startsWith("#/components/parameters/"))return T;const v=L.slice(24),w=q(q(a,"parameters"),v);return X(w)?w:null},d=T=>{if(!X(T))return null;const L=typeof T.$ref=="string"?T.$ref:"";if(!L.startsWith("#/components/requestBodies/"))return T;const v=L.slice(27),w=q(q(a,"requestBodies"),v);return X(w)?w:null},u=T=>{if(!X(T))return null;const L=typeof T.$ref=="string"?T.$ref:"";if(!L.startsWith("#/components/responses/"))return T;const v=L.slice(23),w=q(q(a,"responses"),v);return X(w)?w:null},m=d(s.requestBody),p=q(q(m??void 0,"content"),"application/json")?.schema,y=new Map;[...Array.isArray(o?.parameters)?o.parameters:[],...Array.isArray(s.parameters)?s.parameters:[]].map(l).filter(io).forEach(T=>y.set(`${T.in}:${T.name}`,T));const b=Array.from(y.values()),f=i(p),x=!!(f&&(f.type==="object"||f.properties)),g="__body",C=m?.required===!0,k=q(f??void 0,"properties")?q(f??void 0,"properties"):{},j=co(f?.required),_=new Set(Object.keys(k)),A={},I={},U=[];for(const T of b){const L=T.name;let v=L;if(_.has(v)){v=`${T.in}_${L}`;let S=2;for(;_.has(v);)v=`${T.in}_${L}_${S++}`}_.add(v);const w=i(T.schema)||{};I[v]={...w,title:Ye(w.title,L),description:[Ye(w.description),`${T.in} parameter`].filter(Boolean).join(" · ")},A[v]={name:L,in:T.in},(T.required===!0||T.in==="path")&&U.push(v)}const E=b.length?{type:"object",properties:I,...U.length?{required:U}:{},components:a}:null,V=f&&x?{...f,properties:{...k,...I},...j.length||U.length?{required:Array.from(new Set([...j,...U]))}:{}}:f&&E?{type:"object",properties:{[g]:{...f,title:Ye(f.title,"Request body")},...I},...C||U.length?{required:[...C?[g]:[],...U]}:{}}:f||E,O=q(s,"responses")||{},D=u(O[200]||O[201]||O[202]||Object.values(O)[0]),J=q(q(D??void 0,"content"),"application/json")?.schema;return{input_schema:V,output_schema:i(J),method:t.toUpperCase(),path:e,...Object.keys(A).length?{parameters:A}:{},...f&&!x&&E?{body_field:g}:{}}}async getEndpointContract(e){const t=Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.toUpperCase()):[],n=Array.from(new Set(["POST",...t])),a=`/api/v1/endpoints/${encodeURIComponent(e.name)}${e.path}`;let o;for(const s of n)try{return await this.getOperationContract(a,s)}catch(i){if(!(i instanceof ye&&i.status===404))throw i;o=i}throw o instanceof Error?o:new ye(404,"Operation not found",`${e.name} has no documented callable method`)}async listAgents(){const e=await this.request("/studio/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:e?.agents&&typeof e.agents=="object"?Object.entries(e.agents).map(([t,n])=>({name:n?.name||t,slug:n?.slug||t,description:n?.description||"",version:n?.version||"1.0.0",framework:n?.framework||"unknown",capabilities:n?.capabilities||[],has_graph:!!n?.has_graph,has_config:!!n?.has_config,has_prompts:!!n?.has_prompts})):[]}async getGraph(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/graph`)}async getSchemas(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/schemas`)}async getAgentConfig(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/config`)}normalizeThread(e,t){return{id:e?.id||e?.thread_id||"",user_id:e?.user_id||"default-user",agent_name:e?.agent_name||t||"",title:e?.title??null,metadata:e?.metadata||{},created_at:e?.created_at||e?.created||new Date().toISOString(),updated_at:e?.updated_at||e?.updated||e?.created_at||new Date().toISOString()}}normalizeMessage(e,t){return{id:String(e?.id||e?.message_id||`${t}-${e?.timestamp||Date.now()}`),thread_id:e?.thread_id||t,role:e?.role||"assistant",content:typeof e?.content=="string"?e.content:JSON.stringify(e?.content??e?.message??""),metadata:e?.metadata||{},timestamp:e?.timestamp||e?.created_at||new Date().toISOString()}}async createThread(e,t,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`,{method:"POST",body:JSON.stringify({user_id:t||"default-user",title:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async listThreads(e){const t=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`);return(Array.isArray(t)?t:Array.isArray(t?.threads)?t.threads:[]).map(a=>this.normalizeThread(a,e))}async getThread(e,t){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}`);return this.normalizeThread(n,e)}async deleteThread(e,t){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}`,{method:"DELETE"})}async getMessages(e,t){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/messages`);return(Array.isArray(n)?n:Array.isArray(n?.messages)?n.messages:[]).map(o=>this.normalizeMessage(o,t))}async forkThread(e,t,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/fork`,{method:"POST",body:JSON.stringify({message_index:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async createRun(e,t){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs`,{method:"POST",body:JSON.stringify(t)})}async listRuns(e,t=50){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs?limit=${t}`)}async getRun(e,t){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}`)}async getState(e,t){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/state`)}async updateState(e,t,n){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/state`,{method:"POST",body:JSON.stringify({updates:n})})}async getHistory(e,t){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/history`)}async getPendingApprovals(e,t){return this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/pending`)}async approve(e,t,n){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({approval_id:n})})}async reject(e,t,n,a){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({approval_id:n,reason:a})})}async healthCheck(){try{return await this.request("/studio/info"),!0}catch{return!1}}async listPipelines(){const e=await this.request("/api/v1/pipelines");return(Array.isArray(e)?e:Array.isArray(e?.pipelines)?e.pipelines:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",steps:Array.isArray(n?.steps)?n.steps:[],agents_used:Array.isArray(n?.agents_used)?n.agents_used:[]}))}async runPipeline(e,t){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t)})}async validatePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/validate`)}async validatePipelineDraft(e){return this.request("/api/v1/pipelines/validate-draft",{method:"POST",body:JSON.stringify(e)})}async savePipeline(e,t){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})}async deletePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"DELETE"})}async listEndpoints(){const e=await this.request("/api/v1/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listIngestors(){const e=await this.request("/api/v1/ingestors");return(Array.isArray(e)?e:Array.isArray(e?.ingestors)?e.ingestors:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",ready:!!n?.ready,input_schema:n?.input_schema||""}))}async runIngestor(e,t){return this.request(`/api/v1/ingestion/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t)})}async listTasks(e={}){const t=new URLSearchParams;return Object.entries(e).forEach(([n,a])=>{a!==void 0&&a!==""&&t.set(n,String(a))}),this.request(`/api/v1/tasks${t.size?`?${t}`:""}`)}async submitTask(e){return this.request("/api/v1/tasks",{method:"POST",body:JSON.stringify(e)})}async getTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`)}async getTaskResult(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/result`)}async cancelTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/cancel`,{method:"POST"})}async deleteTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`,{method:"DELETE"})}async getPipelineConfig(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/config`)}async visualizePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/visualize`)}async listPlugins(){const e=await this.request("/api/v1/plugins");return(Array.isArray(e)?e:Array.isArray(e?.plugins)?e.plugins:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",is_loaded:!!n?.is_loaded}))}async getPluginModelCard(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/model_card`)}async reloadPlugin(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/reload`,{method:"POST"})}async runPluginPredict(e,t){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/predict`,{method:"POST",body:JSON.stringify(t)})}async callEndpoint(e,t,n,a="POST",o){const s=a.toUpperCase();let i=`/api/v1/endpoints/${encodeURIComponent(e)}${t}`;const l=new URLSearchParams,d={},u={},m=o?.parameters||{},p=o?.body_field,y=n&&typeof n=="object"&&!Array.isArray(n)?n:null,b=p&&y?y[p]:n;for(const[x,g]of Object.entries(y||{})){if(x===p)continue;const C=m[x],j=C?C.in:s==="GET"||s==="HEAD"?"query":"body",_=C?.name||x;if(j==="body"){d[x]=g;continue}if(!(g==null||g==="")){if(j==="path"){i=i.replace(`{${_}}`,encodeURIComponent(String(g)));continue}if(j==="header"){u[_]=Array.isArray(g)?g.map(A=>typeof A=="string"?A:JSON.stringify(A)).join(", "):typeof g=="object"?JSON.stringify(g):String(g);continue}Array.isArray(g)?g.forEach(A=>l.append(_,typeof A=="string"?A:JSON.stringify(A))):l.set(_,typeof g=="object"?JSON.stringify(g):String(g))}}const f=l.size?`?${l.toString()}`:"";return s==="GET"||s==="HEAD"?this.request(`${i}${f}`,{method:s,headers:u}):this.request(`${i}${f}`,{method:s,headers:u,body:JSON.stringify(p||!y?b:d)})}async getControlInfo(){return this.request("/api/v1/control")}async listControlAgents(){const e=await this.request("/api/v1/control/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]}async getControlAgent(e){return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}`)}async listControlEndpoints(){const e=await this.request("/api/v1/control/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listControlConnections(){const e=await this.request("/api/v1/control/connections");return(Array.isArray(e)?e:Array.isArray(e?.connections)?e.connections:[]).map(n=>({scope:n?.scope||"",connections:n?.connections||{}}))}async probeControlConnection(e,t){return this.request(`/api/v1/control/connections/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async getControlMetricsSummary(){return this.request("/api/v1/control/metrics/summary")}async getControlHealth(){return this.request("/api/v1/control/health")}async getControlConfig(){return this.request("/api/v1/control/config")}async setAgentEnabled(e,t,n){const a=t?"enable":"disable";return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}/${a}`,{method:"POST",headers:n?{"X-Control-Token":n}:{}})}async setMaintenance(e,t){return this.request("/api/v1/control/maintenance",{method:"POST",headers:t?{"X-Control-Token":t}:{},body:JSON.stringify({enabled:e})})}getStreamUrl(e){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/runs/stream`}getResumeStreamUrl(e,t){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/resume`}getHeaders(){return{...this.headers}}}class ye extends Error{constructor(e,t,n){super(`API Error ${e}: ${t}`),this.status=e,this.statusText=t,this.body=n,this.name="ApiError"}}const lo="agentomatic-studio:lastUrl",Ne="agentomatic-studio:lastApiKey",vt="agentomatic-studio:lastApiKey",uo=()=>{try{const r=sessionStorage.getItem(Ne);if(r)return r;const e=localStorage.getItem(vt);return e?(sessionStorage.setItem(Ne,e),localStorage.removeItem(vt),e):""}catch{return""}},mo={graph:{light:"bg-blue-100 text-blue-700 border-blue-200",dark:"bg-blue-900/40 text-blue-300 border-blue-700"},streaming:{light:"bg-green-100 text-green-700 border-green-200",dark:"bg-green-900/40 text-green-300 border-green-700"},hitl:{light:"bg-amber-100 text-amber-700 border-amber-200",dark:"bg-amber-900/40 text-amber-300 border-amber-700"},checkpoints:{light:"bg-purple-100 text-purple-700 border-purple-200",dark:"bg-purple-900/40 text-purple-300 border-purple-700"}},fo={light:"bg-gray-100 text-gray-700 border-gray-200",dark:"bg-gray-700 text-gray-300 border-gray-600"},po=()=>{const r=Pt(),{setConfig:e,setIsConnected:t,setIsLoading:n,addAssistant:a,clearAssistants:o,fetchGraphData:s,refreshThreads:i,setSelectedAgent:l,darkMode:d}=me(),[u,m]=h.useState(()=>{const S=uo();return{apiUrl:Ae(),agentId:"",apiKey:S||""}}),[p,y]=h.useState({status:"idle",message:"Enter server URL to check connectivity"}),[b,f]=h.useState([]),[x,g]=h.useState(!1),[C,k]=h.useState(!1),[j,_]=h.useState(!1),[,A]=h.useState(null),[I,U]=h.useState({}),E=h.useRef(0),V=h.useCallback((S,M)=>{try{localStorage.setItem(lo,S),M?sessionStorage.setItem(Ne,M):sessionStorage.removeItem(Ne)}catch{}},[]),O=h.useCallback(S=>{const M=mo[S]||fo,W=d?M.dark:M.light;return c.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border leading-tight ${W}`,children:S},S)},[d]),D=h.useCallback(async S=>{const M=++E.current,W=mt(S);if(!W||!W.startsWith("http")){y({status:"idle",message:"Enter a valid server URL"}),f([]),U({}),_(!1),g(!1);return}y({status:"checking",message:"Checking server connectivity..."}),f([]),U({}),_(!1),g(!0),m(Y=>Y.agentId?{...Y,agentId:""}:Y);try{const Y=new Xe(W,u.apiKey||void 0),G=await Y.getServerInfo();if(M!==E.current)return;A(G);const ae=await Y.listAgents();if(M!==E.current)return;if(ae.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ve=ae.map(N=>({id:N.slug||N.name,name:N.name,description:N.description||`${N.framework} agent`,config:{capabilities:N.capabilities,has_graph:N.has_graph,version:N.version}})),oe={};ae.forEach(N=>{oe[N.slug||N.name]=N.capabilities||[]}),U(oe),f(ve),m(N=>({...N,agentId:ve[0].id})),y({status:"success",message:`Connected to ${G.platform_title||"Agentomatic"} v${G.version} — ${G.agent_count} agent(s)`,lastChecked:new Date}),setTimeout(()=>_(!0),300)}catch(Y){if(M!==E.current)return;const G=Y?.status===401||Y?.status===403?"Studio authorization failed. Provide a valid API key and retry.":`Studio API is unavailable: ${Y?.message||"start the platform with Studio enabled."}`;y({status:"error",message:G,lastChecked:new Date}),_(!1)}finally{M===E.current&&g(!1)}},[u.apiKey]);h.useEffect(()=>{const S=setTimeout(()=>{u.apiUrl&&D(u.apiUrl)},1e3);return()=>clearTimeout(S)},[u.apiUrl,D]);const J=async S=>{if(S.preventDefault(),p.status!=="success"){Se.error("Please ensure the server connection is healthy before connecting");return}if(!u.agentId){Se.error("Please select a live agent to use");return}k(!0),n(!0);try{const M=mt(u.apiUrl),W=new Xe(M,u.apiKey||void 0),[Y,G]=await Promise.all([W.getServerInfo(),W.listAgents()]);if(G.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ae=G.map(N=>({id:N.slug||N.name,name:N.name,description:N.description||"",type:"chat",model:N.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:N.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:N.capabilities,apiName:N.name,slug:N.slug},graph_id:N.slug||N.name}));Je(W),o(),e({...u,apiUrl:M}),ae.forEach(N=>a(N)),t(!0);const ve=u.agentId||G[0]?.slug||G[0]?.name,oe=ae.find(N=>N.id===ve)||ae[0];oe&&(l(oe),s(oe.id).catch(N=>{console.warn("Background graph load failed:",N)}),i(oe.id).catch(()=>{})),V(M,u.apiKey||""),Se.success(`Connected to ${Y.platform_title||"Agentomatic"} v${Y.version}!`),setTimeout(()=>r("/studio"),500)}catch(M){console.error("Connection error:",M),Se.error("Failed to connect. Please check your configuration.")}finally{k(!1),n(!1)}},T=(S,M)=>{m(W=>({...W,[S]:M}))},L=()=>{switch(p.status){case"checking":return c.jsxs("svg",{className:"w-5 h-5 animate-spin text-blue-500",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]});case"success":return c.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})});case"error":return c.jsx("svg",{className:"w-5 h-5 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})});default:return c.jsx("svg",{className:"w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}},v=()=>{switch(p.status){case"checking":return"text-blue-600 bg-blue-50 border-blue-200";case"success":return"text-green-600 bg-green-50 border-green-200";case"error":return"text-red-600 bg-red-50 border-red-200";default:return"text-gray-600 bg-gray-50 border-gray-200"}},w=()=>{switch(p.status){case"checking":return"text-blue-400 bg-blue-900/30 border-blue-700";case"success":return"text-green-400 bg-green-900/30 border-green-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return c.jsxs("div",{className:`min-h-screen w-full flex ${d?"bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900":"bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50"} relative overflow-hidden`,children:[c.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[c.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),c.jsx("div",{className:`absolute top-1/4 left-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse ${d?"bg-blue-600":"bg-blue-400"}`}),c.jsx("div",{className:`absolute bottom-1/4 right-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse delay-1000 ${d?"bg-purple-600":"bg-purple-400"}`}),c.jsx("div",{className:`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 rounded-full blur-3xl opacity-10 animate-pulse delay-500 ${d?"bg-indigo-600":"bg-indigo-400"}`})]}),c.jsxs("div",{className:"relative z-10 w-full flex",children:[c.jsx("div",{className:"hidden lg:flex lg:w-1/2 xl:w-2/5 flex-col justify-center items-center p-12 relative",children:c.jsxs("div",{className:"max-w-md text-center animate-slide-in-left",children:[c.jsx("div",{className:`w-32 h-32 rounded-3xl flex items-center justify-center mx-auto mb-8 ${d?"bg-gradient-to-br from-blue-600 via-purple-600 to-indigo-600":"bg-gradient-to-br from-blue-500 via-indigo-500 to-purple-600"} shadow-2xl animate-pulse-glow`,children:c.jsx("svg",{className:"w-16 h-16 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),c.jsxs("h1",{className:`text-5xl font-bold mb-6 ${d?"text-white":"text-gray-900"}`,children:["Agentomatic",c.jsx("span",{className:`block text-4xl ${d?"text-violet-400":"text-violet-600"}`,children:"Studio"})]}),c.jsx("p",{className:`text-xl leading-relaxed mb-8 ${d?"text-gray-300":"text-gray-600"}`,children:"Build, debug, and deploy intelligent agent workflows with visual graph execution"}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-green-400":"bg-green-500"} animate-pulse`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Real-time graph execution"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-blue-400":"bg-blue-500"} animate-pulse delay-300`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Interactive debugging tools"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-purple-400":"bg-purple-500"} animate-pulse delay-700`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Multi-agent orchestration"})]})]})]})}),c.jsx("div",{className:"w-full lg:w-1/2 xl:w-3/5 flex items-center justify-center p-6 lg:p-12",children:c.jsxs("div",{className:`w-full max-w-md rounded-3xl shadow-2xl backdrop-blur-md border ${d?"bg-gray-800/80 border-gray-700":"bg-white/80 border-gray-200"} animate-slide-in-right`,children:[c.jsxs("div",{className:"p-8 text-center",children:[c.jsx("div",{className:"lg:hidden mb-6",children:c.jsx("div",{className:`w-16 h-16 rounded-2xl flex items-center justify-center mx-auto ${d?"bg-gradient-to-br from-blue-600 to-purple-600":"bg-gradient-to-br from-blue-500 to-indigo-600"} shadow-lg`,children:c.jsx("svg",{className:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})})}),c.jsx("h2",{className:`text-2xl lg:text-3xl font-bold mb-3 ${d?"text-white":"text-gray-900"}`,children:"Get Started"}),c.jsx("p",{className:`text-lg ${d?"text-gray-300":"text-gray-600"}`,children:"Connect to your authenticated Agentomatic server"})]}),c.jsxs("div",{className:"px-8 pb-8",children:[c.jsxs("form",{onSubmit:J,className:"space-y-6",children:[c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsx("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:"Server URL"}),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:"url",value:u.apiUrl,onChange:S=>T("apiUrl",S.target.value),placeholder:Ae(),className:`w-full px-4 py-4 pr-14 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`,required:!0}),c.jsx("div",{className:"absolute right-4 top-1/2 transform -translate-y-1/2",children:L()})]}),c.jsxs("div",{className:`mt-3 p-4 rounded-xl border text-sm flex items-center space-x-3 transition-all duration-300 ${d?w():v()}`,children:[L(),c.jsxs("div",{className:"flex-1",children:[c.jsx("span",{className:"font-medium",children:p.message}),p.lastChecked&&c.jsxs("div",{className:"text-xs opacity-75 mt-1",children:["Last checked: ",p.lastChecked.toLocaleTimeString()]})]})]})]}),c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsxs("label",{htmlFor:"agentomatic-api-key",className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["API key ",c.jsx("span",{className:"font-normal opacity-70",children:"(optional)"})]}),c.jsx("input",{id:"agentomatic-api-key",type:"password",value:u.apiKey||"",onChange:S=>T("apiKey",S.target.value),placeholder:"Required when server authentication is enabled",autoComplete:"off",spellCheck:!1,className:`w-full px-4 py-4 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`}),c.jsx("p",{className:`mt-2 text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Kept only for this tab session after a successful connection; closing the tab removes it."})]}),j&&c.jsxs("div",{className:"animate-fade-in-up stagger-2",children:[c.jsxs("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["Available agents",x&&c.jsxs("span",{className:"ml-2 text-xs text-blue-500",children:[c.jsxs("svg",{className:"inline w-3 h-3 animate-spin mr-1",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Loading..."]})]}),b.length>0?c.jsx("div",{className:"space-y-3 max-h-48 overflow-y-auto custom-scrollbar",children:b.map((S,M)=>c.jsxs("label",{className:`flex items-center p-4 rounded-xl border cursor-pointer transition-all duration-300 transform hover:scale-105 ${u.agentId===S.id?d?"bg-blue-900/40 border-blue-500 text-blue-400 shadow-lg":"bg-blue-50 border-blue-500 text-blue-700 shadow-lg":d?"bg-gray-700/50 border-gray-600 hover:bg-gray-600/50 text-gray-200":"bg-white/50 border-gray-200 hover:bg-gray-50 text-gray-700"} animate-slide-in-right`,style:{animationDelay:`${M*100}ms`},children:[c.jsx("input",{type:"radio",name:"agentId",value:S.id,checked:u.agentId===S.id,onChange:W=>T("agentId",W.target.value),className:"sr-only"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"font-semibold",children:S.name}),I[S.id]?.length>0&&c.jsx("span",{className:"flex flex-wrap gap-1",children:I[S.id].map(O)})]}),S.description&&c.jsx("div",{className:`text-sm mt-1 ${u.agentId===S.id?"opacity-90":d?"text-gray-400":"text-gray-500"}`,children:S.description})]}),c.jsx("div",{className:`w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all duration-200 ${u.agentId===S.id?"border-current scale-110":d?"border-gray-500":"border-gray-300"}`,children:u.agentId===S.id&&c.jsx("div",{className:"w-3 h-3 rounded-full bg-current animate-pulse"})})]},S.id))}):c.jsx("div",{className:`p-6 rounded-xl border text-center ${d?"bg-gray-700/50 border-gray-600 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:x?c.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Loading live agents..."})]}):"No live agents available. Check the Studio API and server connection."})]}),c.jsx("div",{className:"space-y-4 animate-fade-in-up stagger-3",children:c.jsx("button",{type:"submit",disabled:p.status!=="success"||!u.agentId||C,className:`w-full py-4 px-6 rounded-2xl font-semibold text-white transition-all duration-300 transform ${p.status==="success"&&u.agentId&&!C?"bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 hover:scale-105 shadow-lg hover:shadow-2xl":"bg-gray-400 cursor-not-allowed opacity-50"}`,children:C?c.jsxs("div",{className:"flex items-center justify-center space-x-3",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Connecting..."})]}):"Connect to Server"})})]}),c.jsx("div",{className:`mt-8 pt-6 border-t ${d?"border-gray-600":"border-gray-200"} animate-fade-in-up stagger-4`,children:c.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-green-400":"text-green-600"}`,children:"🚀"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Authenticated server"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Verify before entering Studio"})]}),c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-blue-400":"text-blue-600"}`,children:"🔗"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Live execution"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Uses deployed resource contracts"})]})]})})]})]})})]})]})},wt="agentomatic-studio:lastApiKey",Ct="agentomatic-studio:lastApiKey",ho=()=>{try{const r=sessionStorage.getItem(wt);if(r)return r;const e=localStorage.getItem(Ct);return e?(sessionStorage.setItem(wt,e),localStorage.removeItem(Ct),e):""}catch{return""}},go=r=>({id:r.slug||r.name,name:r.name,description:r.description||"",type:"chat",model:r.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:r.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:r.capabilities,apiName:r.name,slug:r.slug},graph_id:r.slug||r.name,metadata:{version:r.version,framework:r.framework,capabilities:r.capabilities,has_graph:r.has_graph,has_config:r.has_config}});function yo(){const{isConnected:r,darkMode:e,setConfig:t,setIsConnected:n,setConnectionStatus:a,clearAssistants:o,addAssistant:s,setSelectedAssistant:i,fetchGraphData:l,refreshThreads:d}=me(),[u,m]=h.useState(!1),p="/studio/ui/".replace(/\/$/,"");h.useEffect(()=>{e?(document.documentElement.setAttribute("data-theme","dark"),document.documentElement.classList.add("dark")):(document.documentElement.removeAttribute("data-theme"),document.documentElement.classList.remove("dark"))},[e]),h.useEffect(()=>{let b=!1;return(async()=>{const x=Ae();let g="";try{g=ho()}catch{}try{const C=new Xe(x,g||void 0);await C.getServerInfo();const k=await C.listAgents();if(b)return;const j=k.map(go);Je(C);const _=j[0];t({apiUrl:x,apiKey:g||void 0,agentId:_?.id}),o(),j.forEach(s),_&&(i(_),l(_.id),d(_.id).catch(()=>{})),a("connected"),n(!0)}catch{b||(Je(null),a("disconnected"),n(!1))}finally{b||m(!0)}})(),()=>{b=!0}},[s,o,t,a,n,i,l,d]);const y=u?r?c.jsx(oo,{}):c.jsx(et,{to:"/setup",replace:!0}):c.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-gray-500",children:"Restoring Studio session…"});return c.jsxs(It,{basename:p,children:[c.jsx("div",{className:`App ${e?"dark":""}`,children:c.jsxs(Lt,{children:[c.jsx(Re,{path:"/setup",element:c.jsx(po,{})}),c.jsx(Re,{path:"/studio",element:y}),c.jsx(Re,{path:"/",element:c.jsx(et,{to:r&&u?"/studio":"/setup",replace:!0})})]})}),c.jsx(Rr,{position:"top-right",toastOptions:{duration:4e3,style:{background:e?"#374151":"#ffffff",color:e?"#f9fafb":"#111827",border:e?"1px solid #4b5563":"1px solid #e5e7eb"},success:{duration:3e3,iconTheme:{primary:"#10b981",secondary:e?"#374151":"#ffffff"}},error:{duration:5e3,iconTheme:{primary:"#ef4444",secondary:e?"#374151":"#ffffff"}}}})]})}const xo=Ft.createRoot(document.getElementById("root"));xo.render(c.jsx(z.StrictMode,{children:c.jsx(yo,{})}));export{Xe as A,An as F,Se as V,Nt as a,$o as b,Oo as c,jo as d,en as e,Ba as f,Mn as g,So as h,Ao as i,c as j,ko as k,Eo as l,_o as m,H as n,To as o,wo as p,No as q,Co as s,me as u}; diff --git a/src/agentomatic/studio/static/assets/index-Czmh8XoR.css b/src/agentomatic/studio/static/assets/index-Czmh8XoR.css new file mode 100644 index 00000000..15ea15e9 --- /dev/null +++ b/src/agentomatic/studio/static/assets/index-Czmh8XoR.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:Inter,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Monaco,Consolas,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.inset-3{inset:.75rem}.inset-y-0{top:0;bottom:0}.bottom-1\/4{bottom:25%}.bottom-2{bottom:.5rem}.bottom-4{bottom:1rem}.bottom-full{bottom:100%}.left-0{left:0}.left-1\/2{left:50%}.left-1\/4{left:25%}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-1\/4{right:25%}.right-2{right:.5rem}.right-4{right:1rem}.top-0{top:0}.top-1\/2{top:50%}.top-1\/4{top:25%}.top-2{top:.5rem}.top-4{top:1rem}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[999998\]{z-index:999998}.z-\[999999\]{z-index:999999}.order-1{order:1}.order-2{order:2}.m-2{margin:.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-1{margin-left:.25rem}.ml-1\.5{margin-left:.375rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-1\.5{margin-right:.375rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-20{height:5rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.h-96{height:24rem}.h-full{height:100%}.h-screen{height:100vh}.max-h-32{max-height:8rem}.max-h-36{max-height:9rem}.max-h-40{max-height:10rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-80{max-height:20rem}.max-h-96{max-height:24rem}.max-h-\[85vh\]{max-height:85vh}.min-h-0{min-height:0px}.min-h-14{min-height:3.5rem}.min-h-16{min-height:4rem}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-80{width:20rem}.w-96{width:24rem}.w-\[480px\]{width:480px}.w-auto{width:auto}.w-full{width:100%}.w-px{width:1px}.w-screen{width:100vw}.min-w-0{min-width:0px}.min-w-\[16px\]{min-width:16px}.min-w-\[32rem\]{min-width:32rem}.min-w-\[44rem\]{min-width:44rem}.min-w-\[4rem\]{min-width:4rem}.min-w-max{min-width:-webkit-max-content;min-width:max-content}.max-w-28{max-width:7rem}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-\[13rem\]{max-width:13rem}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-\[1\.5\]{flex:1.5}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.animate-fade-in{animation:fadeIn .5s ease-in-out}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-grab{cursor:grab}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;user-select:none}.resize-none{resize:none}.resize-y{resize:vertical}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-1\.5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.375rem * var(--tw-space-x-reverse));margin-left:calc(.375rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1.25rem * var(--tw-space-x-reverse));margin-left:calc(1.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 231 235 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-center{align-self:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-3xl{border-radius:1.5rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-t-xl{border-top-left-radius:.75rem;border-top-right-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-amber-400{--tw-border-opacity: 1;border-color:rgb(251 191 36 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-700{--tw-border-opacity: 1;border-color:rgb(180 83 9 / var(--tw-border-opacity, 1))}.border-amber-800{--tw-border-opacity: 1;border-color:rgb(146 64 14 / var(--tw-border-opacity, 1))}.border-amber-900{--tw-border-opacity: 1;border-color:rgb(120 53 15 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-300{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.border-blue-400{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-blue-700{--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.border-blue-900\/70{border-color:#1e3a8ab3}.border-blue-900\/80{border-color:#1e3a8acc}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-700{--tw-border-opacity: 1;border-color:rgb(4 120 87 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-500{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.border-gray-600{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-600{--tw-border-opacity: 1;border-color:rgb(22 163 74 / var(--tw-border-opacity, 1))}.border-green-700{--tw-border-opacity: 1;border-color:rgb(21 128 61 / var(--tw-border-opacity, 1))}.border-indigo-500{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.border-orange-500{--tw-border-opacity: 1;border-color:rgb(249 115 22 / var(--tw-border-opacity, 1))}.border-pink-500{--tw-border-opacity: 1;border-color:rgb(236 72 153 / var(--tw-border-opacity, 1))}.border-purple-200{--tw-border-opacity: 1;border-color:rgb(233 213 255 / var(--tw-border-opacity, 1))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-700{--tw-border-opacity: 1;border-color:rgb(126 34 206 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-700{--tw-border-opacity: 1;border-color:rgb(185 28 28 / var(--tw-border-opacity, 1))}.border-red-800{--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.border-teal-500{--tw-border-opacity: 1;border-color:rgb(20 184 166 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-violet-200{--tw-border-opacity: 1;border-color:rgb(221 214 254 / var(--tw-border-opacity, 1))}.border-violet-700{--tw-border-opacity: 1;border-color:rgb(109 40 217 / var(--tw-border-opacity, 1))}.border-violet-800\/70{border-color:#5b21b6b3}.border-l-gray-200{--tw-border-opacity: 1;border-left-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-l-gray-600{--tw-border-opacity: 1;border-left-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/95{background-color:#fffbebf2}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-900{--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.bg-amber-900\/40{background-color:#78350f66}.bg-amber-900\/60{background-color:#78350f99}.bg-amber-950\/30{background-color:#451a034d}.bg-amber-950\/40{background-color:#451a0366}.bg-amber-950\/95{background-color:#451a03f2}.bg-black\/10{background-color:#0000001a}.bg-black\/30{background-color:#0000004d}.bg-black\/35{background-color:#00000059}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.bg-blue-300{--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity, 1))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-50\/70{background-color:#eff6ffb3}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-600\/20{background-color:#2563eb33}.bg-blue-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.bg-blue-800{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.bg-blue-900{--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.bg-blue-900\/20{background-color:#1e3a8a33}.bg-blue-900\/30{background-color:#1e3a8a4d}.bg-blue-900\/40{background-color:#1e3a8a66}.bg-blue-900\/50{background-color:#1e3a8a80}.bg-blue-900\/60{background-color:#1e3a8a99}.bg-blue-950\/20{background-color:#17255433}.bg-blue-950\/30{background-color:#1725544d}.bg-blue-950\/60{background-color:#17255499}.bg-current{background-color:currentColor}.bg-cyan-100{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-900{--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.bg-emerald-900\/60{background-color:#064e3b99}.bg-emerald-900\/80{background-color:#064e3bcc}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-50\/50{background-color:#f9fafb80}.bg-gray-50\/70{background-color:#f9fafbb3}.bg-gray-50\/80{background-color:#f9fafbcc}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-700\/50{background-color:#37415180}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/30{background-color:#1f29374d}.bg-gray-800\/40{background-color:#1f293766}.bg-gray-800\/50{background-color:#1f293780}.bg-gray-800\/80{background-color:#1f2937cc}.bg-gray-800\/90{background-color:#1f2937e6}.bg-gray-800\/95{background-color:#1f2937f2}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-900\/40{background-color:#11182766}.bg-gray-900\/50{background-color:#11182780}.bg-gray-950{--tw-bg-opacity: 1;background-color:rgb(3 7 18 / var(--tw-bg-opacity, 1))}.bg-gray-950\/35{background-color:#03071259}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-50\/90{background-color:#f0fdf4e6}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-green-900{--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.bg-green-900\/30{background-color:#14532d4d}.bg-green-900\/40{background-color:#14532d66}.bg-green-900\/60{background-color:#14532d99}.bg-green-900\/90{background-color:#14532de6}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-indigo-400{--tw-bg-opacity: 1;background-color:rgb(129 140 248 / var(--tw-bg-opacity, 1))}.bg-indigo-600{--tw-bg-opacity: 1;background-color:rgb(79 70 229 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-pink-100{--tw-bg-opacity: 1;background-color:rgb(252 231 243 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-900{--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.bg-purple-900\/40{background-color:#581c8766}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-red-700{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.bg-red-900{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.bg-red-900\/30{background-color:#7f1d1d4d}.bg-red-900\/40{background-color:#7f1d1d66}.bg-red-900\/50{background-color:#7f1d1d80}.bg-red-900\/60{background-color:#7f1d1d99}.bg-red-950\/40{background-color:#450a0a66}.bg-red-950\/50{background-color:#450a0a80}.bg-teal-100{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.bg-teal-50{--tw-bg-opacity: 1;background-color:rgb(240 253 250 / var(--tw-bg-opacity, 1))}.bg-teal-950{--tw-bg-opacity: 1;background-color:rgb(4 47 46 / var(--tw-bg-opacity, 1))}.bg-violet-100{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.bg-violet-50{--tw-bg-opacity: 1;background-color:rgb(245 243 255 / var(--tw-bg-opacity, 1))}.bg-violet-50\/50{background-color:#f5f3ff80}.bg-violet-50\/60{background-color:#f5f3ff99}.bg-violet-500{--tw-bg-opacity: 1;background-color:rgb(139 92 246 / var(--tw-bg-opacity, 1))}.bg-violet-600{--tw-bg-opacity: 1;background-color:rgb(124 58 237 / var(--tw-bg-opacity, 1))}.bg-violet-800{--tw-bg-opacity: 1;background-color:rgb(91 33 182 / var(--tw-bg-opacity, 1))}.bg-violet-900{--tw-bg-opacity: 1;background-color:rgb(76 29 149 / var(--tw-bg-opacity, 1))}.bg-violet-950\/20{background-color:#2e106533}.bg-violet-950\/25{background-color:#2e106540}.bg-violet-950\/50{background-color:#2e106580}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/20{background-color:#fff3}.bg-white\/50{background-color:#ffffff80}.bg-white\/60{background-color:#fff9}.bg-white\/75{background-color:#ffffffbf}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-600{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity, 1))}.bg-yellow-900{--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.bg-yellow-900\/30{background-color:#713f124d}.bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.20\)_1px\,transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.2) 1px,transparent 0)}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-100{--tw-gradient-from: #dbeafe var(--tw-gradient-from-position);--tw-gradient-to: rgb(219 234 254 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-800{--tw-gradient-from: #1f2937 var(--tw-gradient-from-position);--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-900{--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-100{--tw-gradient-from: #dcfce7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 252 231 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500{--tw-gradient-from: #22c55e var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-600{--tw-gradient-from: #16a34a var(--tw-gradient-from-position);--tw-gradient-to: rgb(22 163 74 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-600{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-gray-700{--tw-gradient-to: rgb(55 65 81 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #374151 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-gray-800{--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #1f2937 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-50{--tw-gradient-to: rgb(238 242 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #eef2ff var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-500{--tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #6366f1 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-purple-600{--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #9333ea var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-white{--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #fff var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-blue-100{--tw-gradient-to: #dbeafe var(--tw-gradient-to-position)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-blue-600{--tw-gradient-to: #2563eb var(--tw-gradient-to-position)}.to-gray-800{--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.to-gray-900{--tw-gradient-to: #111827 var(--tw-gradient-to-position)}.to-indigo-600{--tw-gradient-to: #4f46e5 var(--tw-gradient-to-position)}.to-purple-100{--tw-gradient-to: #f3e8ff var(--tw-gradient-to-position)}.to-purple-50{--tw-gradient-to: #faf5ff var(--tw-gradient-to-position)}.to-purple-500{--tw-gradient-to: #a855f7 var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.to-red-700{--tw-gradient-to: #b91c1c var(--tw-gradient-to-position)}.bg-\[size\:18px_18px\]{background-size:18px 18px}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pb-6{padding-bottom:1.5rem}.pb-8{padding-bottom:2rem}.pl-0{padding-left:0}.pl-10{padding-left:2.5rem}.pr-1{padding-right:.25rem}.pr-14{padding-right:3.5rem}.pr-4{padding-right:1rem}.pt-2{padding-top:.5rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:JetBrains Mono,Monaco,Consolas,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity, 1))}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-500{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-950{--tw-text-opacity: 1;color:rgb(69 26 3 / var(--tw-text-opacity, 1))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-300\/70{color:#93c5fdb3}.text-blue-300\/80{color:#93c5fdcc}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-700\/70{color:#1d4ed8b3}.text-blue-700\/80{color:#1d4ed8cc}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-cyan-500{--tw-text-opacity: 1;color:rgb(6 182 212 / var(--tw-text-opacity, 1))}.text-cyan-600{--tw-text-opacity: 1;color:rgb(8 145 178 / var(--tw-text-opacity, 1))}.text-cyan-700{--tw-text-opacity: 1;color:rgb(14 116 144 / var(--tw-text-opacity, 1))}.text-emerald-200{--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-500{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-200{--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.text-green-300{--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-indigo-500{--tw-text-opacity: 1;color:rgb(99 102 241 / var(--tw-text-opacity, 1))}.text-indigo-700{--tw-text-opacity: 1;color:rgb(67 56 202 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-500{--tw-text-opacity: 1;color:rgb(236 72 153 / var(--tw-text-opacity, 1))}.text-pink-700{--tw-text-opacity: 1;color:rgb(190 24 93 / var(--tw-text-opacity, 1))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-200{--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-teal-200{--tw-text-opacity: 1;color:rgb(153 246 228 / var(--tw-text-opacity, 1))}.text-teal-500{--tw-text-opacity: 1;color:rgb(20 184 166 / var(--tw-text-opacity, 1))}.text-teal-700{--tw-text-opacity: 1;color:rgb(15 118 110 / var(--tw-text-opacity, 1))}.text-teal-800{--tw-text-opacity: 1;color:rgb(17 94 89 / var(--tw-text-opacity, 1))}.text-violet-200{--tw-text-opacity: 1;color:rgb(221 214 254 / var(--tw-text-opacity, 1))}.text-violet-400{--tw-text-opacity: 1;color:rgb(167 139 250 / var(--tw-text-opacity, 1))}.text-violet-500{--tw-text-opacity: 1;color:rgb(139 92 246 / var(--tw-text-opacity, 1))}.text-violet-600{--tw-text-opacity: 1;color:rgb(124 58 237 / var(--tw-text-opacity, 1))}.text-violet-800{--tw-text-opacity: 1;color:rgb(91 33 182 / var(--tw-text-opacity, 1))}.text-violet-900{--tw-text-opacity: 1;color:rgb(76 29 149 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.no-underline{-webkit-text-decoration-line:none;text-decoration-line:none}.underline-offset-2{text-underline-offset:2px}.placeholder-gray-400::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.accent-blue-500{accent-color:#3b82f6}.accent-blue-600{accent-color:#2563eb}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-25{opacity:.25}.opacity-5{opacity:.05}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-gray-200\/50{--tw-shadow-color: rgb(229 231 235 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-900\/20{--tw-shadow-color: rgb(17 24 39 / .2);--tw-shadow: var(--tw-shadow-colored)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-blue-400{--tw-ring-opacity: 1;--tw-ring-color: rgb(96 165 250 / var(--tw-ring-opacity, 1))}.ring-blue-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-blue-600{--tw-ring-opacity: 1;--tw-ring-color: rgb(37 99 235 / var(--tw-ring-opacity, 1))}.ring-green-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.ring-red-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.blur-3xl{--tw-blur: blur(64px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,fill,stroke,-webkit-text-decoration-color;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,-webkit-text-decoration-color;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.delay-1000{transition-delay:1s}.delay-300{transition-delay:.3s}.delay-500{transition-delay:.5s}.delay-700{transition-delay:.7s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}:root{--bg-primary: #ffffff;--bg-secondary: #f9fafb;--text-primary: #111827;--text-secondary: #6b7280;--border-color: #e5e7eb}[data-theme=dark]{--bg-primary: #1f2937;--bg-secondary: #111827;--text-primary: #f9fafb;--text-secondary: #9ca3af;--border-color: #374151}*{box-sizing:border-box}body{margin:0;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:var(--bg-secondary);color:var(--text-primary);transition:background-color .3s ease,color .3s ease}code{font-family:JetBrains Mono,source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:var(--bg-secondary)}::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.dark ::-webkit-scrollbar-track{background:#374151}.dark ::-webkit-scrollbar-thumb{background:#6b7280}.dark ::-webkit-scrollbar-thumb:hover{background:#9ca3af}.graph-svg{background:transparent;border-radius:8px;transition:background-color .3s ease}.graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.1));transition:all .2s ease}.dark .graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.3))}.graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-canvas{background:var(--bg-secondary);position:relative;transition:background-color .3s ease}.dark .graph-canvas{background:#1f2937}.graph-canvas:before{display:none}.minimap{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border-bottom:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.control-panel{transition:all .3s cubic-bezier(.4,0,.2,1)}.control-panel.collapsed{transform:translate(100%)}@keyframes nodeSelect{0%{transform:scale(1)}50%{transform:scale(1.05)}to{transform:scale(1)}}.node-selected{animation:nodeSelect .3s ease-out}@keyframes pathFlow{0%{stroke-dashoffset:20}to{stroke-dashoffset:0}}.execution-path{stroke-dasharray:5,5;animation:pathFlow 1s linear infinite}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);box-shadow:0 2px 4px #3b82f633;transition:all .2s ease}.btn-primary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #3b82f64d}.btn-secondary{background:linear-gradient(135deg,#6b7280,#4b5563);box-shadow:0 2px 4px #6b728033;transition:all .2s ease}.btn-secondary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #6b72804d}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);box-shadow:0 2px 4px #ef444433;transition:all .2s ease}.btn-danger:hover{transform:translateY(-1px);box-shadow:0 4px 8px #ef44444d}.status-indicator{position:relative;overflow:hidden;transition:all .3s ease}.status-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);transition:left .5s}.dark .status-indicator:before{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator.active:before{left:100%}.line-clamp-2{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.monaco-editor{border-radius:8px}@keyframes typing{0%{width:0}to{width:100%}}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .3s ease-out}.typing-animation{overflow:hidden;border-right:2px solid #0ea5e9;white-space:nowrap;animation:typing 2s steps(40,end),blink-caret .75s step-end infinite}@keyframes blink-caret{0%,to{border-color:transparent}50%{border-color:#0ea5e9}}.spinner{border:2px solid var(--bg-secondary);border-top:2px solid #0ea5e9;border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.message-bubble{max-width:80%;word-wrap:break-word;animation:slideUp .3s ease-out;transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#0ea5e9,#0284c7);color:#fff;margin-left:auto}.message-bubble.assistant{background:var(--bg-primary);border:1px solid var(--border-color);color:var(--text-primary);transition:background-color .3s ease,border-color .3s ease,color .3s ease}.graph-node{background:var(--bg-primary);border:2px solid var(--border-color);border-radius:8px;padding:12px;min-width:120px;text-align:center;font-weight:500;transition:all .2s ease}.graph-node:hover{border-color:#0ea5e9;box-shadow:0 4px 12px #0ea5e926}.dark .graph-node:hover{box-shadow:0 4px 12px #0ea5e94d}.graph-node.active{border-color:#0ea5e9;background:#f0f9ff;box-shadow:0 4px 12px #0ea5e940}.dark .graph-node.active{background:#1e3a8a;box-shadow:0 4px 12px #0ea5e966}.graph-node.error{border-color:#ef4444;background:#fef2f2}.dark .graph-node.error{background:#7f1d1d}.Resizer{background:var(--border-color);opacity:.5;z-index:1;box-sizing:border-box;background-clip:padding-box;transition:all .2s ease}.Resizer:hover{opacity:1;background:#0ea5e9}.Resizer.horizontal{height:4px;margin:-2px 0;cursor:row-resize;width:100%}.Resizer.vertical{width:4px;margin:0 -2px;cursor:col-resize;height:100%}.react-json-view{background-color:var(--bg-secondary)!important;border-radius:8px;padding:16px;transition:background-color .3s ease}.mermaid{text-align:center}.mermaid svg{max-width:100%;height:auto}.sidebar-container{transition:width .3s cubic-bezier(.4,0,.2,1)}.sidebar-collapsed{width:0;overflow:hidden}.sidebar-expanded{width:320px}@keyframes slideIn{0%{transform:translate(-100%);opacity:0}to{transform:translate(0);opacity:1}}.graph-canvas{background-image:none;transition:background-color .3s ease}.graph-node-group{transition:opacity .2s ease}.graph-node-group:hover{opacity:.95}.graph-node-group:hover .graph-node-rect{filter:brightness(1.08) drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.2) drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-node-rect{transition:stroke-width .2s ease,filter .2s ease}.selection-ring{animation:selection-dash 3s linear infinite}@keyframes selection-dash{0%{stroke-dashoffset:0}to{stroke-dashoffset:16}}.graph-edge-path{transition:stroke .3s ease-in-out,stroke-width .3s ease-in-out;filter:drop-shadow(0 1px 2px rgba(0,0,0,.1))}.dark .graph-edge-path{filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}.graph-edge-arrow{transition:fill .3s ease-in-out}.status-indicator{transition:all .3s ease-in-out}.status-indicator.active{background:linear-gradient(90deg,#3b82f6,#1d4ed8,#3b82f6);background-size:200px 100%;animation:shimmer 2s infinite linear;color:#fff}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);transition:all .2s ease-in-out}.btn-primary:hover{background:linear-gradient(135deg,#1d4ed8,#1e40af);transform:translateY(-1px);box-shadow:0 4px 12px #3b82f666}.btn-secondary{background:linear-gradient(135deg,#8b5cf6,#7c3aed);transition:all .2s ease-in-out}.btn-secondary:hover{background:linear-gradient(135deg,#7c3aed,#6d28d9);transform:translateY(-1px);box-shadow:0 4px 12px #8b5cf666}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);transition:all .2s ease-in-out}.btn-danger:hover{background:linear-gradient(135deg,#dc2626,#b91c1c);transform:translateY(-1px);box-shadow:0 4px 12px #ef444466}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffffff2}.dark .toolbar{background:#1f2937f2}.message-bubble{transition:all .2s ease-in-out;animation:fadeIn .3s ease-out}.animate-fade-in{animation:fadeIn .5s ease-out}.animate-slide-in{animation:slideIn .3s ease-out}.transition-width{transition:width .3s ease-in-out}.transition-height{transition:height .3s ease-in-out}.message-bubble{transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:#fff}.message-bubble.assistant{background:var(--bg-secondary);color:var(--text-primary);border:1px solid var(--border-color);transition:background-color .3s ease,color .3s ease,border-color .3s ease}@keyframes fade-in{0%{opacity:0}to{opacity:1}}@keyframes slide-in-right{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-left{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}.animate-fade-in{animation:fade-in .3s ease-out}.animate-shimmer{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,transparent,rgba(255,255,255,.2),transparent);background-size:200px 100%}.dark .animate-shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator{transition:all .2s ease}.status-indicator.active{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,#3b82f6,#60a5fa,#3b82f6);background-size:200% 100%;color:#fff}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffc}.dark .toolbar{background:#1f2937cc}.graph-node-group{transition:all .2s ease}.graph-node-group:hover .graph-node-rect{filter:brightness(1.1)}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.3)}.graph-edge-path,.graph-edge-arrow{transition:all .2s ease}.selection-ring{animation:dash 1.5s linear infinite}@keyframes dash{to{stroke-dashoffset:-16}}.graph-canvas{background-image:none}.graph-svg{transition:all .2s ease}.backdrop-blur-sm{-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}.backdrop-blur-md{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.card-hover{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-hover:hover{transform:translateY(-2px);box-shadow:0 10px 25px #0000001a}.dark .card-hover:hover{box-shadow:0 10px 25px #0000004d}.status-badge{position:relative;overflow:hidden}.status-badge:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.3),transparent);transition:left .6s}.status-badge:hover:before{left:100%}.focus-ring:focus{outline:none;ring:2px;ring-color:#3b82f6;ring-offset:2px}.debug-scrollbar::-webkit-scrollbar{width:8px;height:8px}.debug-scrollbar::-webkit-scrollbar-track{background:transparent;border-radius:4px}.debug-scrollbar::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:4px;-webkit-transition:background-color .3s ease;transition:background-color .3s ease}.debug-scrollbar::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.gradient-border{position:relative;background:linear-gradient(45deg,#3b82f6,#8b5cf6,#06b6d4);border-radius:12px;padding:1px}.gradient-border-content{background:var(--bg-primary);border-radius:11px;padding:1rem}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromBottom{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromLeft{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}@keyframes slideInFromRight{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes fadeInScale{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}@keyframes pulseGlow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-slide-in-top{animation:slideInFromTop .4s ease-out}.animate-slide-in-bottom{animation:slideInFromBottom .4s ease-out}.animate-slide-in-left{animation:slideInFromLeft .3s ease-out}.animate-slide-in-right{animation:slideInFromRight .3s ease-out}.animate-fade-in-scale{animation:fadeInScale .3s ease-out}.animate-pulse-glow{animation:pulseGlow 2s ease-in-out infinite}.auto-focus-indicator{animation:fadeInScale .5s ease-out,pulseGlow 2s ease-in-out infinite .5s}.context-switch-notification{animation:slideInFromTop .5s ease-out,fadeInScale .3s ease-out}.graph-node-focused{animation:pulseGlow 1s ease-in-out;filter:drop-shadow(0 0 20px rgba(59,130,246,.6))}.graph-view-transition{transition:all .8s cubic-bezier(.4,0,.2,1)}@keyframes executionFlow{0%{stroke-dashoffset:20;opacity:.5}50%{opacity:1}to{stroke-dashoffset:0;opacity:.8}}.execution-path-animated{stroke-dasharray:10,5;animation:executionFlow 2s ease-in-out infinite}.skeleton{background:linear-gradient(90deg,var(--bg-secondary) 25%,var(--border-color) 50%,var(--bg-secondary) 75%);background-size:200% 100%;animation:skeleton-loading 1.5s infinite}@keyframes skeleton-loading{0%{background-position:200% 0}to{background-position:-200% 0}}.graph-overlay{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);background:#ffffffe6;border:1px solid rgba(255,255,255,.2);box-shadow:0 8px 32px #0000001a}.dark .graph-overlay{background:#1f2937e6;border:1px solid rgba(75,85,99,.3);box-shadow:0 8px 32px #0000004d}.metric-card{background:linear-gradient(135deg,var(--bg-primary) 0%,var(--bg-secondary) 100%);border:1px solid var(--border-color);transition:all .3s ease}.metric-card:hover{transform:translateY(-2px);box-shadow:0 8px 25px #0000001a;border-color:#3b82f6}.dark .metric-card:hover{box-shadow:0 8px 25px #0000004d}.log-level-error{background:linear-gradient(135deg,#fef2f2,#fee2e2);border-color:#fecaca;color:#991b1b}.dark .log-level-error{background:linear-gradient(135deg,#7f1d1d4d,#991b1b33);border-color:#7f1d1d;color:#fca5a5}.log-level-warn{background:linear-gradient(135deg,#fffbeb,#fef3c7);border-color:#fde68a;color:#92400e}.dark .log-level-warn{background:linear-gradient(135deg,#92400e4d,#b4530933);border-color:#92400e;color:#fcd34d}.log-level-info{background:linear-gradient(135deg,#eff6ff,#dbeafe);border-color:#bfdbfe;color:#1e40af}.dark .log-level-info{background:linear-gradient(135deg,#1e40af4d,#2563eb33);border-color:#1e40af;color:#93c5fd}.log-level-debug{background:linear-gradient(135deg,#f9fafb,#f3f4f6);border-color:#e5e7eb;color:#374151}.dark .log-level-debug{background:linear-gradient(135deg,#3741514d,#4b556333);border-color:#374151;color:#d1d5db}@keyframes pulse-glow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-pulse-glow{animation:pulse-glow 3s ease-in-out infinite}@keyframes slide-in-left{0%{opacity:0;transform:translate(-50px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-right{0%{opacity:0;transform:translate(50px)}to{opacity:1;transform:translate(0)}}@keyframes fade-in-up{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.animate-slide-in-left{animation:slide-in-left .8s ease-out}.animate-slide-in-right{animation:slide-in-right .8s ease-out}.animate-fade-in-up{animation:fade-in-up .6s ease-out;animation-fill-mode:both}.stagger-1{animation-delay:.1s}.stagger-2{animation-delay:.3s}.stagger-3{animation-delay:.5s}.stagger-4{animation-delay:.7s}.custom-scrollbar::-webkit-scrollbar{width:6px}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:3px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afcc}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#6b728080}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#6b7280cc}.bg-grid-pattern{background-image:linear-gradient(rgba(0,0,0,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(0,0,0,.1) 1px,transparent 1px);background-size:20px 20px}.dark .bg-grid-pattern{background-image:linear-gradient(rgba(255,255,255,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.1) 1px,transparent 1px)}.btn-hover-lift{transition:all .3s cubic-bezier(.4,0,.2,1)}.btn-hover-lift:hover{transform:translateY(-2px);box-shadow:0 10px 25px #00000026}.dark .btn-hover-lift:hover{box-shadow:0 10px 25px #0000004d}.glass-morphism{-webkit-backdrop-filter:blur(16px) saturate(180%);backdrop-filter:blur(16px) saturate(180%);background-color:#ffffffbf;border:1px solid rgba(255,255,255,.125)}.dark .glass-morphism{background-color:#1f2937bf;border:1px solid rgba(255,255,255,.125)}.status-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes status-glow{0%,to{box-shadow:0 0 5px currentColor}50%{box-shadow:0 0 20px currentColor,0 0 30px currentColor}}.status-glow{animation:status-glow 2s ease-in-out infinite}.input-focus-ring:focus{outline:none;box-shadow:0 0 0 3px #3b82f61a;border-color:#3b82f6}.dark .input-focus-ring:focus{box-shadow:0 0 0 3px #3b82f633}.card-interactive{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-interactive:hover{transform:translateY(-4px);box-shadow:0 20px 25px -5px #0000001a,0 10px 10px -5px #0000000a}.dark .card-interactive:hover{box-shadow:0 20px 25px -5px #00000040,0 10px 10px -5px #0000001a}@keyframes shimmer{0%{background-position:-200px 0}to{background-position:calc(200px + 100%) 0}}.shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);background-size:200px 100%;animation:shimmer 1.5s infinite}.dark .shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}@keyframes float{0%,to{transform:translateY(0)}50%{transform:translateY(-20px)}}.animate-float{animation:float 6s ease-in-out infinite}.animate-float-delayed{animation:float 6s ease-in-out infinite;animation-delay:2s}.radio-custom{-webkit-appearance:none;appearance:none;width:1.5rem;height:1.5rem;border:2px solid currentColor;border-radius:50%;position:relative;transition:all .2s ease}.radio-custom:checked:before{content:"";position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:.75rem;height:.75rem;background:currentColor;border-radius:50%;animation:radio-check .2s ease-out}@keyframes radio-check{0%{transform:translate(-50%,-50%) scale(0)}to{transform:translate(-50%,-50%) scale(1)}}.gradient-text{background:linear-gradient(135deg,#667eea,#764ba2);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.dark .gradient-text{background:linear-gradient(135deg,#60a5fa,#a78bfa);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.log-entry-selected{transform:scale(1.02);box-shadow:0 8px 25px #3b82f626}.log-entry-hover{transform:translateY(-1px);box-shadow:0 4px 12px #0000001a}.node-highlighted{filter:drop-shadow(0 0 12px rgba(245,158,11,.6));animation:pulse-highlight 2s infinite}@keyframes pulse-highlight{0%,to{filter:drop-shadow(0 0 12px rgba(245,158,11,.6))}50%{filter:drop-shadow(0 0 20px rgba(245,158,11,.8))}}.custom-scrollbar::-webkit-scrollbar{width:8px}.custom-scrollbar::-webkit-scrollbar-track{background:transparent}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afb3}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#4b556380}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#4b5563b3}.log-data-json{background:linear-gradient(135deg,#3b82f60d,#10b9810d)}.dark .log-data-json{background:linear-gradient(135deg,#3b82f61a,#10b9811a)}.performance-card{background:linear-gradient(135deg,#6366f11a,#a855f71a);border:1px solid rgba(99,102,241,.2)}.dark .performance-card{background:linear-gradient(135deg,#6366f126,#a855f726);border:1px solid rgba(99,102,241,.3)}.state-update-indicator{position:relative;overflow:hidden}.state-update-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(59,130,246,.2),transparent);animation:shimmer 2s infinite}@keyframes shimmer{0%{left:-100%}to{left:100%}}.typing-indicator{display:flex;align-items:center;gap:4px;padding:8px 16px}.typing-indicator .dot{width:8px;height:8px;border-radius:50%;background-color:#6b7280;animation:typingBounce 1.4s infinite ease-in-out both}.dark .typing-indicator .dot{background-color:#9ca3af}.typing-indicator .dot:nth-child(1){animation-delay:-.32s}.typing-indicator .dot:nth-child(2){animation-delay:-.16s}.typing-indicator .dot:nth-child(3){animation-delay:0s}@keyframes typingBounce{0%,80%,to{transform:scale(.6);opacity:.4}40%{transform:scale(1);opacity:1}}.copy-btn{opacity:0;transition:all .2s ease;cursor:pointer}.message-bubble:hover .copy-btn,.copy-btn:focus{opacity:1}.copy-btn:active{transform:scale(.9)}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6,#e5e7eb 75%);background-size:200% 100%;animation:skeletonShimmer 1.5s ease-in-out infinite;border-radius:8px}.dark .skeleton{background:linear-gradient(90deg,#374151 25%,#4b5563,#374151 75%);background-size:200% 100%}@keyframes skeletonShimmer{0%{background-position:200% 0}to{background-position:-200% 0}}.zoom-controls{display:flex;align-items:center;gap:4px;padding:4px;border-radius:12px;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);box-shadow:0 2px 8px #00000026}.zoom-controls button{width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:8px;font-size:14px;font-weight:600;transition:all .15s ease;border:none;cursor:pointer}.zoom-controls button:hover{transform:scale(1.1)}.zoom-controls button:active{transform:scale(.95)}@keyframes livePulse{0%{box-shadow:0 0 #10b98166}70%{box-shadow:0 0 0 6px #10b98100}to{box-shadow:0 0 #10b98100}}.live-pulse{animation:livePulse 2s infinite}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-blue-400:hover{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.hover\:border-blue-500:hover{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.hover\:border-gray-200:hover{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.hover\:border-gray-600:hover{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-50:hover{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-900\/60:hover{background-color:#78350f99}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-800:hover{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-900\/60:hover{background-color:#1e3a8a99}.hover\:bg-blue-950\/40:hover{background-color:#17255466}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-500:hover{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600\/50:hover{background-color:#4b556380}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700\/50:hover{background-color:#37415180}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\:bg-red-200:hover{--tw-bg-opacity: 1;background-color:rgb(254 202 202 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-red-800:hover{--tw-bg-opacity: 1;background-color:rgb(153 27 27 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900:hover{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900\/40:hover{background-color:#7f1d1d66}.hover\:bg-violet-100:hover{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-200:hover{--tw-bg-opacity: 1;background-color:rgb(221 214 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-700:hover{--tw-bg-opacity: 1;background-color:rgb(109 40 217 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-900\/70:hover{background-color:#4c1d95b3}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/50:hover{background-color:#ffffff80}.hover\:bg-yellow-700:hover{--tw-bg-opacity: 1;background-color:rgb(161 98 7 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-50:hover{--tw-bg-opacity: .5}.hover\:from-blue-700:hover{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-indigo-700:hover{--tw-gradient-to: #4338ca var(--tw-gradient-to-position)}.hover\:text-blue-300:hover{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-700:hover{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.hover\:text-gray-200:hover{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-red-600:hover{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{-webkit-text-decoration-line:underline;text-decoration-line:underline}.hover\:shadow-2xl:hover{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-xl:hover{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:bg-gray-600:focus{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.focus\:bg-white:focus{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-red-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:transform-none:disabled{transform:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-gray-300:disabled{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-400:disabled{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-600:disabled{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group:hover .group-hover\:opacity-100{opacity:1}.group:hover .group-hover\:shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.dark\:divide-gray-700:is(.dark *)>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(55 65 81 / var(--tw-divide-opacity, 1))}.dark\:border-blue-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(30 64 175 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:bg-amber-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900\/30:is(.dark *){background-color:#1e3a8a4d}.dark\:bg-cyan-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity, 1))}.dark\:bg-emerald-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700\/50:is(.dark *){background-color:#37415180}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800\/75:is(.dark *){background-color:#1f2937bf}.dark\:bg-gray-900\/40:is(.dark *){background-color:#11182766}.dark\:bg-indigo-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(49 46 129 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(124 45 18 / var(--tw-bg-opacity, 1))}.dark\:bg-pink-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(131 24 67 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.dark\:bg-red-950\/40:is(.dark *){background-color:#450a0a66}.dark\:bg-teal-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(19 78 74 / var(--tw-bg-opacity, 1))}.dark\:bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.12\)_1px\,transparent_0\)\]:is(.dark *){background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.12) 1px,transparent 0)}.dark\:text-amber-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-cyan-300:is(.dark *){--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.dark\:text-emerald-300:is(.dark *){--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-indigo-300:is(.dark *){--tw-text-opacity: 1;color:rgb(165 180 252 / var(--tw-text-opacity, 1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.dark\:text-orange-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.dark\:text-pink-300:is(.dark *){--tw-text-opacity: 1;color:rgb(249 168 212 / var(--tw-text-opacity, 1))}.dark\:text-purple-300:is(.dark *){--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-teal-300:is(.dark *){--tw-text-opacity: 1;color:rgb(94 234 212 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-amber-950:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(69 26 3 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:m-4{margin:1rem}.sm\:block{display:block}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:w-52{width:13rem}.sm\:w-56{width:14rem}.sm\:w-auto{width:auto}.sm\:max-w-36{max-width:9rem}.sm\:max-w-none{max-width:none}.sm\:flex-none{flex:none}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-start{align-items:flex-start}.sm\:items-end{align-items:flex-end}.sm\:items-center{align-items:center}.sm\:justify-end{justify-content:flex-end}.sm\:justify-center{justify-content:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:.5rem}.sm\:space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.sm\:p-3{padding:.75rem}.sm\:p-4{padding:1rem}.sm\:p-5{padding:1.25rem}.sm\:p-6{padding:1.5rem}.sm\:px-4{padding-left:1rem;padding-right:1rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}}@media(min-width:768px){.md\:static{position:static}.md\:flex{display:flex}.md\:hidden{display:none}.md\:w-72{width:18rem}.md\:max-w-44{max-width:11rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}@media(min-width:1024px){.lg\:block{display:block}.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:w-1\/2{width:50%}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.lg\:p-12{padding:3rem}.lg\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media(min-width:1280px){.xl\:static{position:static}.xl\:ml-6{margin-left:1.5rem}.xl\:flex{display:flex}.xl\:hidden{display:none}.xl\:w-2\/5{width:40%}.xl\:w-3\/5{width:60%}.xl\:w-80{width:20rem}.xl\:w-96{width:24rem}.xl\:flex-shrink-0{flex-shrink:0}.xl\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.xl\:rounded-none{border-radius:0}.xl\:border-y-0{border-top-width:0px;border-bottom-width:0px}.xl\:border-l{border-left-width:1px}.xl\:border-r-0{border-right-width:0px}}@media(min-width:1536px){.\32xl\:block{display:block}.\32xl\:flex{display:flex}.\32xl\:hidden{display:none}.\32xl\:grid-cols-\[minmax\(26rem\,0\.85fr\)_minmax\(32rem\,1\.15fr\)\]{grid-template-columns:minmax(26rem,.85fr) minmax(32rem,1.15fr)}} diff --git a/src/agentomatic/studio/static/assets/index-DHb1ckAg.css b/src/agentomatic/studio/static/assets/index-DHb1ckAg.css deleted file mode 100644 index d02099d5..00000000 --- a/src/agentomatic/studio/static/assets/index-DHb1ckAg.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:Inter,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Monaco,Consolas,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.inset-3{inset:.75rem}.inset-y-0{top:0;bottom:0}.bottom-1\/4{bottom:25%}.bottom-2{bottom:.5rem}.bottom-4{bottom:1rem}.bottom-full{bottom:100%}.left-0{left:0}.left-1\/2{left:50%}.left-1\/4{left:25%}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-1\/4{right:25%}.right-2{right:.5rem}.right-4{right:1rem}.top-0{top:0}.top-1\/2{top:50%}.top-1\/4{top:25%}.top-2{top:.5rem}.top-4{top:1rem}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[999998\]{z-index:999998}.z-\[999999\]{z-index:999999}.order-1{order:1}.order-2{order:2}.m-2{margin:.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-1{margin-left:.25rem}.ml-1\.5{margin-left:.375rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-1\.5{margin-right:.375rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-20{height:5rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.h-96{height:24rem}.h-full{height:100%}.h-screen{height:100vh}.max-h-32{max-height:8rem}.max-h-36{max-height:9rem}.max-h-40{max-height:10rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-80{max-height:20rem}.max-h-96{max-height:24rem}.max-h-\[85vh\]{max-height:85vh}.min-h-0{min-height:0px}.min-h-14{min-height:3.5rem}.min-h-16{min-height:4rem}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-80{width:20rem}.w-96{width:24rem}.w-\[480px\]{width:480px}.w-auto{width:auto}.w-full{width:100%}.w-px{width:1px}.w-screen{width:100vw}.min-w-0{min-width:0px}.min-w-\[16px\]{min-width:16px}.min-w-\[32rem\]{min-width:32rem}.min-w-\[44rem\]{min-width:44rem}.min-w-\[4rem\]{min-width:4rem}.min-w-max{min-width:-webkit-max-content;min-width:max-content}.max-w-28{max-width:7rem}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-\[13rem\]{max-width:13rem}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-\[1\.5\]{flex:1.5}.flex-shrink-0,.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.animate-fade-in{animation:fadeIn .5s ease-in-out}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-grab{cursor:grab}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;user-select:none}.resize-none{resize:none}.resize-y{resize:vertical}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-1\.5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.375rem * var(--tw-space-x-reverse));margin-left:calc(.375rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1.25rem * var(--tw-space-x-reverse));margin-left:calc(1.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 231 235 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-center{align-self:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-3xl{border-radius:1.5rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-t-xl{border-top-left-radius:.75rem;border-top-right-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-amber-400{--tw-border-opacity: 1;border-color:rgb(251 191 36 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-700{--tw-border-opacity: 1;border-color:rgb(180 83 9 / var(--tw-border-opacity, 1))}.border-amber-800{--tw-border-opacity: 1;border-color:rgb(146 64 14 / var(--tw-border-opacity, 1))}.border-amber-900{--tw-border-opacity: 1;border-color:rgb(120 53 15 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-300{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.border-blue-400{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-blue-700{--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.border-blue-900\/70{border-color:#1e3a8ab3}.border-blue-900\/80{border-color:#1e3a8acc}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-700{--tw-border-opacity: 1;border-color:rgb(4 120 87 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-500{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.border-gray-600{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-600{--tw-border-opacity: 1;border-color:rgb(22 163 74 / var(--tw-border-opacity, 1))}.border-green-700{--tw-border-opacity: 1;border-color:rgb(21 128 61 / var(--tw-border-opacity, 1))}.border-indigo-500{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.border-orange-500{--tw-border-opacity: 1;border-color:rgb(249 115 22 / var(--tw-border-opacity, 1))}.border-pink-500{--tw-border-opacity: 1;border-color:rgb(236 72 153 / var(--tw-border-opacity, 1))}.border-purple-200{--tw-border-opacity: 1;border-color:rgb(233 213 255 / var(--tw-border-opacity, 1))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-700{--tw-border-opacity: 1;border-color:rgb(126 34 206 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-700{--tw-border-opacity: 1;border-color:rgb(185 28 28 / var(--tw-border-opacity, 1))}.border-red-800{--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.border-teal-500{--tw-border-opacity: 1;border-color:rgb(20 184 166 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-violet-200{--tw-border-opacity: 1;border-color:rgb(221 214 254 / var(--tw-border-opacity, 1))}.border-violet-700{--tw-border-opacity: 1;border-color:rgb(109 40 217 / var(--tw-border-opacity, 1))}.border-violet-800\/70{border-color:#5b21b6b3}.border-l-gray-200{--tw-border-opacity: 1;border-left-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-l-gray-600{--tw-border-opacity: 1;border-left-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/95{background-color:#fffbebf2}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-900{--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.bg-amber-900\/40{background-color:#78350f66}.bg-amber-900\/60{background-color:#78350f99}.bg-amber-950\/30{background-color:#451a034d}.bg-amber-950\/40{background-color:#451a0366}.bg-amber-950\/95{background-color:#451a03f2}.bg-black\/10{background-color:#0000001a}.bg-black\/30{background-color:#0000004d}.bg-black\/35{background-color:#00000059}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.bg-blue-300{--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity, 1))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-50\/70{background-color:#eff6ffb3}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-600\/20{background-color:#2563eb33}.bg-blue-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.bg-blue-800{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.bg-blue-900{--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.bg-blue-900\/20{background-color:#1e3a8a33}.bg-blue-900\/30{background-color:#1e3a8a4d}.bg-blue-900\/40{background-color:#1e3a8a66}.bg-blue-900\/50{background-color:#1e3a8a80}.bg-blue-900\/60{background-color:#1e3a8a99}.bg-blue-950\/20{background-color:#17255433}.bg-blue-950\/30{background-color:#1725544d}.bg-blue-950\/60{background-color:#17255499}.bg-current{background-color:currentColor}.bg-cyan-100{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-900{--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.bg-emerald-900\/60{background-color:#064e3b99}.bg-emerald-900\/80{background-color:#064e3bcc}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-50\/50{background-color:#f9fafb80}.bg-gray-50\/70{background-color:#f9fafbb3}.bg-gray-50\/80{background-color:#f9fafbcc}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-700\/50{background-color:#37415180}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/30{background-color:#1f29374d}.bg-gray-800\/40{background-color:#1f293766}.bg-gray-800\/50{background-color:#1f293780}.bg-gray-800\/80{background-color:#1f2937cc}.bg-gray-800\/90{background-color:#1f2937e6}.bg-gray-800\/95{background-color:#1f2937f2}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-900\/40{background-color:#11182766}.bg-gray-900\/50{background-color:#11182780}.bg-gray-950{--tw-bg-opacity: 1;background-color:rgb(3 7 18 / var(--tw-bg-opacity, 1))}.bg-gray-950\/35{background-color:#03071259}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-50\/90{background-color:#f0fdf4e6}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-green-900{--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.bg-green-900\/30{background-color:#14532d4d}.bg-green-900\/40{background-color:#14532d66}.bg-green-900\/60{background-color:#14532d99}.bg-green-900\/90{background-color:#14532de6}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-indigo-400{--tw-bg-opacity: 1;background-color:rgb(129 140 248 / var(--tw-bg-opacity, 1))}.bg-indigo-600{--tw-bg-opacity: 1;background-color:rgb(79 70 229 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-pink-100{--tw-bg-opacity: 1;background-color:rgb(252 231 243 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-900{--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.bg-purple-900\/40{background-color:#581c8766}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-red-700{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.bg-red-900{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.bg-red-900\/30{background-color:#7f1d1d4d}.bg-red-900\/40{background-color:#7f1d1d66}.bg-red-900\/50{background-color:#7f1d1d80}.bg-red-900\/60{background-color:#7f1d1d99}.bg-red-950\/40{background-color:#450a0a66}.bg-red-950\/50{background-color:#450a0a80}.bg-teal-100{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.bg-teal-50{--tw-bg-opacity: 1;background-color:rgb(240 253 250 / var(--tw-bg-opacity, 1))}.bg-teal-950{--tw-bg-opacity: 1;background-color:rgb(4 47 46 / var(--tw-bg-opacity, 1))}.bg-violet-100{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.bg-violet-50{--tw-bg-opacity: 1;background-color:rgb(245 243 255 / var(--tw-bg-opacity, 1))}.bg-violet-50\/50{background-color:#f5f3ff80}.bg-violet-50\/60{background-color:#f5f3ff99}.bg-violet-500{--tw-bg-opacity: 1;background-color:rgb(139 92 246 / var(--tw-bg-opacity, 1))}.bg-violet-600{--tw-bg-opacity: 1;background-color:rgb(124 58 237 / var(--tw-bg-opacity, 1))}.bg-violet-800{--tw-bg-opacity: 1;background-color:rgb(91 33 182 / var(--tw-bg-opacity, 1))}.bg-violet-900{--tw-bg-opacity: 1;background-color:rgb(76 29 149 / var(--tw-bg-opacity, 1))}.bg-violet-950\/20{background-color:#2e106533}.bg-violet-950\/25{background-color:#2e106540}.bg-violet-950\/50{background-color:#2e106580}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/20{background-color:#fff3}.bg-white\/50{background-color:#ffffff80}.bg-white\/60{background-color:#fff9}.bg-white\/75{background-color:#ffffffbf}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-600{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity, 1))}.bg-yellow-900{--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.bg-yellow-900\/30{background-color:#713f124d}.bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.20\)_1px\,transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.2) 1px,transparent 0)}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-100{--tw-gradient-from: #dbeafe var(--tw-gradient-from-position);--tw-gradient-to: rgb(219 234 254 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-800{--tw-gradient-from: #1f2937 var(--tw-gradient-from-position);--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-900{--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-100{--tw-gradient-from: #dcfce7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 252 231 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500{--tw-gradient-from: #22c55e var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-600{--tw-gradient-from: #16a34a var(--tw-gradient-from-position);--tw-gradient-to: rgb(22 163 74 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-600{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-gray-700{--tw-gradient-to: rgb(55 65 81 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #374151 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-gray-800{--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #1f2937 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-50{--tw-gradient-to: rgb(238 242 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #eef2ff var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-500{--tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #6366f1 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-purple-600{--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #9333ea var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-white{--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #fff var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-blue-100{--tw-gradient-to: #dbeafe var(--tw-gradient-to-position)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-blue-600{--tw-gradient-to: #2563eb var(--tw-gradient-to-position)}.to-gray-800{--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.to-gray-900{--tw-gradient-to: #111827 var(--tw-gradient-to-position)}.to-indigo-600{--tw-gradient-to: #4f46e5 var(--tw-gradient-to-position)}.to-purple-100{--tw-gradient-to: #f3e8ff var(--tw-gradient-to-position)}.to-purple-50{--tw-gradient-to: #faf5ff var(--tw-gradient-to-position)}.to-purple-500{--tw-gradient-to: #a855f7 var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.to-red-700{--tw-gradient-to: #b91c1c var(--tw-gradient-to-position)}.bg-\[size\:18px_18px\]{background-size:18px 18px}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pb-6{padding-bottom:1.5rem}.pb-8{padding-bottom:2rem}.pl-0{padding-left:0}.pl-10{padding-left:2.5rem}.pr-1{padding-right:.25rem}.pr-14{padding-right:3.5rem}.pr-4{padding-right:1rem}.pt-2{padding-top:.5rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:JetBrains Mono,Monaco,Consolas,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity, 1))}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-500{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-950{--tw-text-opacity: 1;color:rgb(69 26 3 / var(--tw-text-opacity, 1))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-300\/70{color:#93c5fdb3}.text-blue-300\/80{color:#93c5fdcc}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-700\/70{color:#1d4ed8b3}.text-blue-700\/80{color:#1d4ed8cc}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-cyan-500{--tw-text-opacity: 1;color:rgb(6 182 212 / var(--tw-text-opacity, 1))}.text-cyan-600{--tw-text-opacity: 1;color:rgb(8 145 178 / var(--tw-text-opacity, 1))}.text-cyan-700{--tw-text-opacity: 1;color:rgb(14 116 144 / var(--tw-text-opacity, 1))}.text-emerald-200{--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-500{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-200{--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.text-green-300{--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-indigo-500{--tw-text-opacity: 1;color:rgb(99 102 241 / var(--tw-text-opacity, 1))}.text-indigo-700{--tw-text-opacity: 1;color:rgb(67 56 202 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-500{--tw-text-opacity: 1;color:rgb(236 72 153 / var(--tw-text-opacity, 1))}.text-pink-700{--tw-text-opacity: 1;color:rgb(190 24 93 / var(--tw-text-opacity, 1))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-200{--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-teal-200{--tw-text-opacity: 1;color:rgb(153 246 228 / var(--tw-text-opacity, 1))}.text-teal-500{--tw-text-opacity: 1;color:rgb(20 184 166 / var(--tw-text-opacity, 1))}.text-teal-700{--tw-text-opacity: 1;color:rgb(15 118 110 / var(--tw-text-opacity, 1))}.text-teal-800{--tw-text-opacity: 1;color:rgb(17 94 89 / var(--tw-text-opacity, 1))}.text-violet-200{--tw-text-opacity: 1;color:rgb(221 214 254 / var(--tw-text-opacity, 1))}.text-violet-400{--tw-text-opacity: 1;color:rgb(167 139 250 / var(--tw-text-opacity, 1))}.text-violet-500{--tw-text-opacity: 1;color:rgb(139 92 246 / var(--tw-text-opacity, 1))}.text-violet-600{--tw-text-opacity: 1;color:rgb(124 58 237 / var(--tw-text-opacity, 1))}.text-violet-800{--tw-text-opacity: 1;color:rgb(91 33 182 / var(--tw-text-opacity, 1))}.text-violet-900{--tw-text-opacity: 1;color:rgb(76 29 149 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.no-underline{-webkit-text-decoration-line:none;text-decoration-line:none}.underline-offset-2{text-underline-offset:2px}.placeholder-gray-400::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.accent-blue-500{accent-color:#3b82f6}.accent-blue-600{accent-color:#2563eb}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-25{opacity:.25}.opacity-5{opacity:.05}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-gray-200\/50{--tw-shadow-color: rgb(229 231 235 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-900\/20{--tw-shadow-color: rgb(17 24 39 / .2);--tw-shadow: var(--tw-shadow-colored)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-blue-400{--tw-ring-opacity: 1;--tw-ring-color: rgb(96 165 250 / var(--tw-ring-opacity, 1))}.ring-blue-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-blue-600{--tw-ring-opacity: 1;--tw-ring-color: rgb(37 99 235 / var(--tw-ring-opacity, 1))}.ring-green-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.ring-red-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.blur-3xl{--tw-blur: blur(64px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,fill,stroke,-webkit-text-decoration-color;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,-webkit-text-decoration-color;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.delay-1000{transition-delay:1s}.delay-300{transition-delay:.3s}.delay-500{transition-delay:.5s}.delay-700{transition-delay:.7s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}:root{--bg-primary: #ffffff;--bg-secondary: #f9fafb;--text-primary: #111827;--text-secondary: #6b7280;--border-color: #e5e7eb}[data-theme=dark]{--bg-primary: #1f2937;--bg-secondary: #111827;--text-primary: #f9fafb;--text-secondary: #9ca3af;--border-color: #374151}*{box-sizing:border-box}body{margin:0;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:var(--bg-secondary);color:var(--text-primary);transition:background-color .3s ease,color .3s ease}code{font-family:JetBrains Mono,source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:var(--bg-secondary)}::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.dark ::-webkit-scrollbar-track{background:#374151}.dark ::-webkit-scrollbar-thumb{background:#6b7280}.dark ::-webkit-scrollbar-thumb:hover{background:#9ca3af}.graph-svg{background:transparent;border-radius:8px;transition:background-color .3s ease}.graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.1));transition:all .2s ease}.dark .graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.3))}.graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-canvas{background:var(--bg-secondary);position:relative;transition:background-color .3s ease}.dark .graph-canvas{background:#1f2937}.graph-canvas:before{display:none}.minimap{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border-bottom:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.control-panel{transition:all .3s cubic-bezier(.4,0,.2,1)}.control-panel.collapsed{transform:translate(100%)}@keyframes nodeSelect{0%{transform:scale(1)}50%{transform:scale(1.05)}to{transform:scale(1)}}.node-selected{animation:nodeSelect .3s ease-out}@keyframes pathFlow{0%{stroke-dashoffset:20}to{stroke-dashoffset:0}}.execution-path{stroke-dasharray:5,5;animation:pathFlow 1s linear infinite}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);box-shadow:0 2px 4px #3b82f633;transition:all .2s ease}.btn-primary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #3b82f64d}.btn-secondary{background:linear-gradient(135deg,#6b7280,#4b5563);box-shadow:0 2px 4px #6b728033;transition:all .2s ease}.btn-secondary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #6b72804d}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);box-shadow:0 2px 4px #ef444433;transition:all .2s ease}.btn-danger:hover{transform:translateY(-1px);box-shadow:0 4px 8px #ef44444d}.status-indicator{position:relative;overflow:hidden;transition:all .3s ease}.status-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);transition:left .5s}.dark .status-indicator:before{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator.active:before{left:100%}.line-clamp-2{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.monaco-editor{border-radius:8px}@keyframes typing{0%{width:0}to{width:100%}}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .3s ease-out}.typing-animation{overflow:hidden;border-right:2px solid #0ea5e9;white-space:nowrap;animation:typing 2s steps(40,end),blink-caret .75s step-end infinite}@keyframes blink-caret{0%,to{border-color:transparent}50%{border-color:#0ea5e9}}.spinner{border:2px solid var(--bg-secondary);border-top:2px solid #0ea5e9;border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.message-bubble{max-width:80%;word-wrap:break-word;animation:slideUp .3s ease-out;transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#0ea5e9,#0284c7);color:#fff;margin-left:auto}.message-bubble.assistant{background:var(--bg-primary);border:1px solid var(--border-color);color:var(--text-primary);transition:background-color .3s ease,border-color .3s ease,color .3s ease}.graph-node{background:var(--bg-primary);border:2px solid var(--border-color);border-radius:8px;padding:12px;min-width:120px;text-align:center;font-weight:500;transition:all .2s ease}.graph-node:hover{border-color:#0ea5e9;box-shadow:0 4px 12px #0ea5e926}.dark .graph-node:hover{box-shadow:0 4px 12px #0ea5e94d}.graph-node.active{border-color:#0ea5e9;background:#f0f9ff;box-shadow:0 4px 12px #0ea5e940}.dark .graph-node.active{background:#1e3a8a;box-shadow:0 4px 12px #0ea5e966}.graph-node.error{border-color:#ef4444;background:#fef2f2}.dark .graph-node.error{background:#7f1d1d}.Resizer{background:var(--border-color);opacity:.5;z-index:1;box-sizing:border-box;background-clip:padding-box;transition:all .2s ease}.Resizer:hover{opacity:1;background:#0ea5e9}.Resizer.horizontal{height:4px;margin:-2px 0;cursor:row-resize;width:100%}.Resizer.vertical{width:4px;margin:0 -2px;cursor:col-resize;height:100%}.react-json-view{background-color:var(--bg-secondary)!important;border-radius:8px;padding:16px;transition:background-color .3s ease}.mermaid{text-align:center}.mermaid svg{max-width:100%;height:auto}.sidebar-container{transition:width .3s cubic-bezier(.4,0,.2,1)}.sidebar-collapsed{width:0;overflow:hidden}.sidebar-expanded{width:320px}@keyframes slideIn{0%{transform:translate(-100%);opacity:0}to{transform:translate(0);opacity:1}}.graph-canvas{background-image:none;transition:background-color .3s ease}.graph-node-group{transition:opacity .2s ease}.graph-node-group:hover{opacity:.95}.graph-node-group:hover .graph-node-rect{filter:brightness(1.08) drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.2) drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-node-rect{transition:stroke-width .2s ease,filter .2s ease}.selection-ring{animation:selection-dash 3s linear infinite}@keyframes selection-dash{0%{stroke-dashoffset:0}to{stroke-dashoffset:16}}.graph-edge-path{transition:stroke .3s ease-in-out,stroke-width .3s ease-in-out;filter:drop-shadow(0 1px 2px rgba(0,0,0,.1))}.dark .graph-edge-path{filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}.graph-edge-arrow{transition:fill .3s ease-in-out}.status-indicator{transition:all .3s ease-in-out}.status-indicator.active{background:linear-gradient(90deg,#3b82f6,#1d4ed8,#3b82f6);background-size:200px 100%;animation:shimmer 2s infinite linear;color:#fff}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);transition:all .2s ease-in-out}.btn-primary:hover{background:linear-gradient(135deg,#1d4ed8,#1e40af);transform:translateY(-1px);box-shadow:0 4px 12px #3b82f666}.btn-secondary{background:linear-gradient(135deg,#8b5cf6,#7c3aed);transition:all .2s ease-in-out}.btn-secondary:hover{background:linear-gradient(135deg,#7c3aed,#6d28d9);transform:translateY(-1px);box-shadow:0 4px 12px #8b5cf666}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);transition:all .2s ease-in-out}.btn-danger:hover{background:linear-gradient(135deg,#dc2626,#b91c1c);transform:translateY(-1px);box-shadow:0 4px 12px #ef444466}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffffff2}.dark .toolbar{background:#1f2937f2}.message-bubble{transition:all .2s ease-in-out;animation:fadeIn .3s ease-out}.animate-fade-in{animation:fadeIn .5s ease-out}.animate-slide-in{animation:slideIn .3s ease-out}.transition-width{transition:width .3s ease-in-out}.transition-height{transition:height .3s ease-in-out}.message-bubble{transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:#fff}.message-bubble.assistant{background:var(--bg-secondary);color:var(--text-primary);border:1px solid var(--border-color);transition:background-color .3s ease,color .3s ease,border-color .3s ease}@keyframes fade-in{0%{opacity:0}to{opacity:1}}@keyframes slide-in-right{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-left{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}.animate-fade-in{animation:fade-in .3s ease-out}.animate-shimmer{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,transparent,rgba(255,255,255,.2),transparent);background-size:200px 100%}.dark .animate-shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator{transition:all .2s ease}.status-indicator.active{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,#3b82f6,#60a5fa,#3b82f6);background-size:200% 100%;color:#fff}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffc}.dark .toolbar{background:#1f2937cc}.graph-node-group{transition:all .2s ease}.graph-node-group:hover .graph-node-rect{filter:brightness(1.1)}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.3)}.graph-edge-path,.graph-edge-arrow{transition:all .2s ease}.selection-ring{animation:dash 1.5s linear infinite}@keyframes dash{to{stroke-dashoffset:-16}}.graph-canvas{background-image:none}.graph-svg{transition:all .2s ease}.backdrop-blur-sm{-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}.backdrop-blur-md{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.card-hover{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-hover:hover{transform:translateY(-2px);box-shadow:0 10px 25px #0000001a}.dark .card-hover:hover{box-shadow:0 10px 25px #0000004d}.status-badge{position:relative;overflow:hidden}.status-badge:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.3),transparent);transition:left .6s}.status-badge:hover:before{left:100%}.focus-ring:focus{outline:none;ring:2px;ring-color:#3b82f6;ring-offset:2px}.debug-scrollbar::-webkit-scrollbar{width:8px;height:8px}.debug-scrollbar::-webkit-scrollbar-track{background:transparent;border-radius:4px}.debug-scrollbar::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:4px;-webkit-transition:background-color .3s ease;transition:background-color .3s ease}.debug-scrollbar::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.gradient-border{position:relative;background:linear-gradient(45deg,#3b82f6,#8b5cf6,#06b6d4);border-radius:12px;padding:1px}.gradient-border-content{background:var(--bg-primary);border-radius:11px;padding:1rem}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromBottom{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromLeft{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}@keyframes slideInFromRight{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes fadeInScale{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}@keyframes pulseGlow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-slide-in-top{animation:slideInFromTop .4s ease-out}.animate-slide-in-bottom{animation:slideInFromBottom .4s ease-out}.animate-slide-in-left{animation:slideInFromLeft .3s ease-out}.animate-slide-in-right{animation:slideInFromRight .3s ease-out}.animate-fade-in-scale{animation:fadeInScale .3s ease-out}.animate-pulse-glow{animation:pulseGlow 2s ease-in-out infinite}.auto-focus-indicator{animation:fadeInScale .5s ease-out,pulseGlow 2s ease-in-out infinite .5s}.context-switch-notification{animation:slideInFromTop .5s ease-out,fadeInScale .3s ease-out}.graph-node-focused{animation:pulseGlow 1s ease-in-out;filter:drop-shadow(0 0 20px rgba(59,130,246,.6))}.graph-view-transition{transition:all .8s cubic-bezier(.4,0,.2,1)}@keyframes executionFlow{0%{stroke-dashoffset:20;opacity:.5}50%{opacity:1}to{stroke-dashoffset:0;opacity:.8}}.execution-path-animated{stroke-dasharray:10,5;animation:executionFlow 2s ease-in-out infinite}.skeleton{background:linear-gradient(90deg,var(--bg-secondary) 25%,var(--border-color) 50%,var(--bg-secondary) 75%);background-size:200% 100%;animation:skeleton-loading 1.5s infinite}@keyframes skeleton-loading{0%{background-position:200% 0}to{background-position:-200% 0}}.graph-overlay{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);background:#ffffffe6;border:1px solid rgba(255,255,255,.2);box-shadow:0 8px 32px #0000001a}.dark .graph-overlay{background:#1f2937e6;border:1px solid rgba(75,85,99,.3);box-shadow:0 8px 32px #0000004d}.metric-card{background:linear-gradient(135deg,var(--bg-primary) 0%,var(--bg-secondary) 100%);border:1px solid var(--border-color);transition:all .3s ease}.metric-card:hover{transform:translateY(-2px);box-shadow:0 8px 25px #0000001a;border-color:#3b82f6}.dark .metric-card:hover{box-shadow:0 8px 25px #0000004d}.log-level-error{background:linear-gradient(135deg,#fef2f2,#fee2e2);border-color:#fecaca;color:#991b1b}.dark .log-level-error{background:linear-gradient(135deg,#7f1d1d4d,#991b1b33);border-color:#7f1d1d;color:#fca5a5}.log-level-warn{background:linear-gradient(135deg,#fffbeb,#fef3c7);border-color:#fde68a;color:#92400e}.dark .log-level-warn{background:linear-gradient(135deg,#92400e4d,#b4530933);border-color:#92400e;color:#fcd34d}.log-level-info{background:linear-gradient(135deg,#eff6ff,#dbeafe);border-color:#bfdbfe;color:#1e40af}.dark .log-level-info{background:linear-gradient(135deg,#1e40af4d,#2563eb33);border-color:#1e40af;color:#93c5fd}.log-level-debug{background:linear-gradient(135deg,#f9fafb,#f3f4f6);border-color:#e5e7eb;color:#374151}.dark .log-level-debug{background:linear-gradient(135deg,#3741514d,#4b556333);border-color:#374151;color:#d1d5db}@keyframes pulse-glow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-pulse-glow{animation:pulse-glow 3s ease-in-out infinite}@keyframes slide-in-left{0%{opacity:0;transform:translate(-50px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-right{0%{opacity:0;transform:translate(50px)}to{opacity:1;transform:translate(0)}}@keyframes fade-in-up{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.animate-slide-in-left{animation:slide-in-left .8s ease-out}.animate-slide-in-right{animation:slide-in-right .8s ease-out}.animate-fade-in-up{animation:fade-in-up .6s ease-out;animation-fill-mode:both}.stagger-1{animation-delay:.1s}.stagger-2{animation-delay:.3s}.stagger-3{animation-delay:.5s}.stagger-4{animation-delay:.7s}.custom-scrollbar::-webkit-scrollbar{width:6px}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:3px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afcc}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#6b728080}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#6b7280cc}.bg-grid-pattern{background-image:linear-gradient(rgba(0,0,0,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(0,0,0,.1) 1px,transparent 1px);background-size:20px 20px}.dark .bg-grid-pattern{background-image:linear-gradient(rgba(255,255,255,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.1) 1px,transparent 1px)}.btn-hover-lift{transition:all .3s cubic-bezier(.4,0,.2,1)}.btn-hover-lift:hover{transform:translateY(-2px);box-shadow:0 10px 25px #00000026}.dark .btn-hover-lift:hover{box-shadow:0 10px 25px #0000004d}.glass-morphism{-webkit-backdrop-filter:blur(16px) saturate(180%);backdrop-filter:blur(16px) saturate(180%);background-color:#ffffffbf;border:1px solid rgba(255,255,255,.125)}.dark .glass-morphism{background-color:#1f2937bf;border:1px solid rgba(255,255,255,.125)}.status-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes status-glow{0%,to{box-shadow:0 0 5px currentColor}50%{box-shadow:0 0 20px currentColor,0 0 30px currentColor}}.status-glow{animation:status-glow 2s ease-in-out infinite}.input-focus-ring:focus{outline:none;box-shadow:0 0 0 3px #3b82f61a;border-color:#3b82f6}.dark .input-focus-ring:focus{box-shadow:0 0 0 3px #3b82f633}.card-interactive{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-interactive:hover{transform:translateY(-4px);box-shadow:0 20px 25px -5px #0000001a,0 10px 10px -5px #0000000a}.dark .card-interactive:hover{box-shadow:0 20px 25px -5px #00000040,0 10px 10px -5px #0000001a}@keyframes shimmer{0%{background-position:-200px 0}to{background-position:calc(200px + 100%) 0}}.shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);background-size:200px 100%;animation:shimmer 1.5s infinite}.dark .shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}@keyframes float{0%,to{transform:translateY(0)}50%{transform:translateY(-20px)}}.animate-float{animation:float 6s ease-in-out infinite}.animate-float-delayed{animation:float 6s ease-in-out infinite;animation-delay:2s}.radio-custom{-webkit-appearance:none;appearance:none;width:1.5rem;height:1.5rem;border:2px solid currentColor;border-radius:50%;position:relative;transition:all .2s ease}.radio-custom:checked:before{content:"";position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:.75rem;height:.75rem;background:currentColor;border-radius:50%;animation:radio-check .2s ease-out}@keyframes radio-check{0%{transform:translate(-50%,-50%) scale(0)}to{transform:translate(-50%,-50%) scale(1)}}.gradient-text{background:linear-gradient(135deg,#667eea,#764ba2);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.dark .gradient-text{background:linear-gradient(135deg,#60a5fa,#a78bfa);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.log-entry-selected{transform:scale(1.02);box-shadow:0 8px 25px #3b82f626}.log-entry-hover{transform:translateY(-1px);box-shadow:0 4px 12px #0000001a}.node-highlighted{filter:drop-shadow(0 0 12px rgba(245,158,11,.6));animation:pulse-highlight 2s infinite}@keyframes pulse-highlight{0%,to{filter:drop-shadow(0 0 12px rgba(245,158,11,.6))}50%{filter:drop-shadow(0 0 20px rgba(245,158,11,.8))}}.custom-scrollbar::-webkit-scrollbar{width:8px}.custom-scrollbar::-webkit-scrollbar-track{background:transparent}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afb3}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#4b556380}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#4b5563b3}.log-data-json{background:linear-gradient(135deg,#3b82f60d,#10b9810d)}.dark .log-data-json{background:linear-gradient(135deg,#3b82f61a,#10b9811a)}.performance-card{background:linear-gradient(135deg,#6366f11a,#a855f71a);border:1px solid rgba(99,102,241,.2)}.dark .performance-card{background:linear-gradient(135deg,#6366f126,#a855f726);border:1px solid rgba(99,102,241,.3)}.state-update-indicator{position:relative;overflow:hidden}.state-update-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(59,130,246,.2),transparent);animation:shimmer 2s infinite}@keyframes shimmer{0%{left:-100%}to{left:100%}}.typing-indicator{display:flex;align-items:center;gap:4px;padding:8px 16px}.typing-indicator .dot{width:8px;height:8px;border-radius:50%;background-color:#6b7280;animation:typingBounce 1.4s infinite ease-in-out both}.dark .typing-indicator .dot{background-color:#9ca3af}.typing-indicator .dot:nth-child(1){animation-delay:-.32s}.typing-indicator .dot:nth-child(2){animation-delay:-.16s}.typing-indicator .dot:nth-child(3){animation-delay:0s}@keyframes typingBounce{0%,80%,to{transform:scale(.6);opacity:.4}40%{transform:scale(1);opacity:1}}.copy-btn{opacity:0;transition:all .2s ease;cursor:pointer}.message-bubble:hover .copy-btn,.copy-btn:focus{opacity:1}.copy-btn:active{transform:scale(.9)}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6,#e5e7eb 75%);background-size:200% 100%;animation:skeletonShimmer 1.5s ease-in-out infinite;border-radius:8px}.dark .skeleton{background:linear-gradient(90deg,#374151 25%,#4b5563,#374151 75%);background-size:200% 100%}@keyframes skeletonShimmer{0%{background-position:200% 0}to{background-position:-200% 0}}.zoom-controls{display:flex;align-items:center;gap:4px;padding:4px;border-radius:12px;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);box-shadow:0 2px 8px #00000026}.zoom-controls button{width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:8px;font-size:14px;font-weight:600;transition:all .15s ease;border:none;cursor:pointer}.zoom-controls button:hover{transform:scale(1.1)}.zoom-controls button:active{transform:scale(.95)}@keyframes livePulse{0%{box-shadow:0 0 #10b98166}70%{box-shadow:0 0 0 6px #10b98100}to{box-shadow:0 0 #10b98100}}.live-pulse{animation:livePulse 2s infinite}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-blue-400:hover{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.hover\:border-blue-500:hover{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.hover\:border-gray-200:hover{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.hover\:border-gray-600:hover{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-50:hover{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-900\/60:hover{background-color:#78350f99}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-800:hover{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-900\/60:hover{background-color:#1e3a8a99}.hover\:bg-blue-950\/40:hover{background-color:#17255466}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-500:hover{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600\/50:hover{background-color:#4b556380}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700\/50:hover{background-color:#37415180}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\:bg-red-200:hover{--tw-bg-opacity: 1;background-color:rgb(254 202 202 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-red-800:hover{--tw-bg-opacity: 1;background-color:rgb(153 27 27 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900:hover{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900\/40:hover{background-color:#7f1d1d66}.hover\:bg-violet-100:hover{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-200:hover{--tw-bg-opacity: 1;background-color:rgb(221 214 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-700:hover{--tw-bg-opacity: 1;background-color:rgb(109 40 217 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-900\/70:hover{background-color:#4c1d95b3}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/50:hover{background-color:#ffffff80}.hover\:bg-yellow-700:hover{--tw-bg-opacity: 1;background-color:rgb(161 98 7 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-50:hover{--tw-bg-opacity: .5}.hover\:from-blue-700:hover{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-indigo-700:hover{--tw-gradient-to: #4338ca var(--tw-gradient-to-position)}.hover\:text-blue-300:hover{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-700:hover{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.hover\:text-gray-200:hover{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-red-600:hover{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{-webkit-text-decoration-line:underline;text-decoration-line:underline}.hover\:shadow-2xl:hover{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-xl:hover{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:bg-gray-600:focus{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.focus\:bg-white:focus{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-red-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:transform-none:disabled{transform:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-gray-300:disabled{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-400:disabled{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-600:disabled{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group:hover .group-hover\:opacity-100{opacity:1}.group:hover .group-hover\:shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.dark\:divide-gray-700:is(.dark *)>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(55 65 81 / var(--tw-divide-opacity, 1))}.dark\:border-blue-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(30 64 175 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:bg-amber-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900\/30:is(.dark *){background-color:#1e3a8a4d}.dark\:bg-cyan-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity, 1))}.dark\:bg-emerald-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700\/50:is(.dark *){background-color:#37415180}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800\/75:is(.dark *){background-color:#1f2937bf}.dark\:bg-gray-900\/40:is(.dark *){background-color:#11182766}.dark\:bg-indigo-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(49 46 129 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(124 45 18 / var(--tw-bg-opacity, 1))}.dark\:bg-pink-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(131 24 67 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.dark\:bg-red-950\/40:is(.dark *){background-color:#450a0a66}.dark\:bg-teal-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(19 78 74 / var(--tw-bg-opacity, 1))}.dark\:bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.12\)_1px\,transparent_0\)\]:is(.dark *){background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.12) 1px,transparent 0)}.dark\:text-amber-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-cyan-300:is(.dark *){--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.dark\:text-emerald-300:is(.dark *){--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-indigo-300:is(.dark *){--tw-text-opacity: 1;color:rgb(165 180 252 / var(--tw-text-opacity, 1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.dark\:text-orange-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.dark\:text-pink-300:is(.dark *){--tw-text-opacity: 1;color:rgb(249 168 212 / var(--tw-text-opacity, 1))}.dark\:text-purple-300:is(.dark *){--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-teal-300:is(.dark *){--tw-text-opacity: 1;color:rgb(94 234 212 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-amber-950:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(69 26 3 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:m-4{margin:1rem}.sm\:block{display:block}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:w-52{width:13rem}.sm\:w-56{width:14rem}.sm\:w-auto{width:auto}.sm\:max-w-36{max-width:9rem}.sm\:max-w-none{max-width:none}.sm\:flex-none{flex:none}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-start{align-items:flex-start}.sm\:items-end{align-items:flex-end}.sm\:items-center{align-items:center}.sm\:justify-end{justify-content:flex-end}.sm\:justify-center{justify-content:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:.5rem}.sm\:space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.sm\:p-3{padding:.75rem}.sm\:p-4{padding:1rem}.sm\:p-5{padding:1.25rem}.sm\:p-6{padding:1.5rem}.sm\:px-4{padding-left:1rem;padding-right:1rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}}@media(min-width:768px){.md\:static{position:static}.md\:flex{display:flex}.md\:hidden{display:none}.md\:w-72{width:18rem}.md\:max-w-44{max-width:11rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}@media(min-width:1024px){.lg\:block{display:block}.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:w-1\/2{width:50%}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.lg\:p-12{padding:3rem}.lg\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media(min-width:1280px){.xl\:static{position:static}.xl\:ml-6{margin-left:1.5rem}.xl\:flex{display:flex}.xl\:hidden{display:none}.xl\:w-2\/5{width:40%}.xl\:w-3\/5{width:60%}.xl\:w-80{width:20rem}.xl\:w-96{width:24rem}.xl\:flex-shrink-0{flex-shrink:0}.xl\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.xl\:rounded-none{border-radius:0}.xl\:border-y-0{border-top-width:0px;border-bottom-width:0px}.xl\:border-l{border-left-width:1px}.xl\:border-r-0{border-right-width:0px}}@media(min-width:1536px){.\32xl\:block{display:block}.\32xl\:flex{display:flex}.\32xl\:hidden{display:none}.\32xl\:grid-cols-\[minmax\(26rem\,0\.85fr\)_minmax\(32rem\,1\.15fr\)\]{grid-template-columns:minmax(26rem,.85fr) minmax(32rem,1.15fr)}} diff --git a/src/agentomatic/studio/static/assets/index-FSSL6O5F.js b/src/agentomatic/studio/static/assets/index-FSSL6O5F.js new file mode 100644 index 00000000..f76b1e7a --- /dev/null +++ b/src/agentomatic/studio/static/assets/index-FSSL6O5F.js @@ -0,0 +1,197 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GraphView-CMqOwCTc.js","assets/react-vendor-BHJ3EV8m.js","assets/SchemaForm-DyHc2s7z.js","assets/OutputSchemaSummary-C65WaRqI.js","assets/syntax-vendor-ru7AzRyY.js","assets/ChatView-C7_FNxo9.js","assets/ClipboardDocumentIcon-Cnz7XqGa.js","assets/DebugView-Bwa7sy_c.js","assets/PipelinesView-DacXbEMw.js","assets/BuilderView-C296ULRo.js","assets/ui-vendor-DIaV1y77.js","assets/PluginsView-COAn7Q5V.js","assets/IngestorsView-Cd56f61k.js","assets/TasksView-DAoR0f0z.js","assets/ControlPlaneView-CC__Od52.js","assets/EndpointsView-fCUdmgxr.js","assets/ConnectionsView-Dvq88oBW.js"])))=>i.map(i=>d[i]); +import{a as Qe,b as Dt,g as St,r as h,R as B,c as Pt,u as Mt,B as It,d as Lt,e as Re,N as et}from"./react-vendor-BHJ3EV8m.js";import{_ as Et,a as G}from"./syntax-vendor-ru7AzRyY.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();var De={exports:{}},fe={};var tt;function Ut(){if(tt)return fe;tt=1;var t=Qe(),e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,a=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function s(i,l,d){var u,m={},f=null,x=null;d!==void 0&&(f=""+d),l.key!==void 0&&(f=""+l.key),l.ref!==void 0&&(x=l.ref);for(u in l)n.call(l,u)&&!o.hasOwnProperty(u)&&(m[u]=l[u]);if(i&&i.defaultProps)for(u in l=i.defaultProps,l)m[u]===void 0&&(m[u]=l[u]);return{$$typeof:e,type:i,key:f,ref:x,props:m,_owner:a.current}}return fe.Fragment=r,fe.jsx=s,fe.jsxs=s,fe}var rt;function qt(){return rt||(rt=1,De.exports=Ut()),De.exports}var c=qt(),we={},nt;function Vt(){if(nt)return we;nt=1;var t=Dt();return we.createRoot=t.createRoot,we.hydrateRoot=t.hydrateRoot,we}var Wt=Vt();const Bt=St(Wt);let Ft={data:""},zt=t=>typeof window=="object"?((t?t.querySelector("#_goober"):window._goober)||Object.assign((t||document.head).appendChild(document.createElement("style")),{innerHTML:" ",id:"_goober"})).firstChild:t||Ft,Yt=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,Ht=/\/\*[^]*?\*\/| +/g,at=/\n+/g,te=(t,e)=>{let r="",n="",a="";for(let o in t){let s=t[o];o[0]=="@"?o[1]=="i"?r=o+" "+s+";":n+=o[1]=="f"?te(s,o):o+"{"+te(s,o[1]=="k"?"":e)+"}":typeof s=="object"?n+=te(s,e?e.replace(/([^,])+/g,i=>o.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,l=>/&/.test(l)?l.replace(/&/g,i):i?i+" "+l:l)):o):s!=null&&(o=/^--/.test(o)?o:o.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=te.p?te.p(o,s):o+":"+s+";")}return r+(e&&a?e+"{"+a+"}":a)+n},Q={},kt=t=>{if(typeof t=="object"){let e="";for(let r in t)e+=r+kt(t[r]);return e}return t},Gt=(t,e,r,n,a)=>{let o=kt(t),s=Q[o]||(Q[o]=(l=>{let d=0,u=11;for(;d>>0;return"go"+u})(o));if(!Q[s]){let l=o!==t?t:(d=>{let u,m,f=[{}];for(;u=Yt.exec(d.replace(Ht,""));)u[4]?f.shift():u[3]?(m=u[3].replace(at," ").trim(),f.unshift(f[0][m]=f[0][m]||{})):f[0][u[1]]=u[2].replace(at," ").trim();return f[0]})(t);Q[s]=te(a?{["@keyframes "+s]:l}:l,r?"":"."+s)}let i=r&&Q.g?Q.g:null;return r&&(Q.g=Q[s]),((l,d,u,m)=>{m?d.data=d.data.replace(m,l):d.data.indexOf(l)===-1&&(d.data=u?l+d.data:d.data+l)})(Q[s],e,n,i),s},Kt=(t,e,r)=>t.reduce((n,a,o)=>{let s=e[o];if(s&&s.call){let i=s(r),l=i&&i.props&&i.props.className||/^go/.test(i)&&i;s=l?"."+l:i&&typeof i=="object"?i.props?"":te(i,""):i===!1?"":i}return n+a+(s??"")},"");function $e(t){let e=this||{},r=t.call?t(e.p):t;return Gt(r.unshift?r.raw?Kt(r,[].slice.call(arguments,1),e.p):r.reduce((n,a)=>Object.assign(n,a&&a.call?a(e.p):a),{}):r,zt(e.target),e.g,e.o,e.k)}let Tt,He,Ge;$e.bind({g:1});let Z=$e.bind({k:1});function Jt(t,e,r,n){te.p=e,Tt=t,He=r,Ge=n}function re(t,e){let r=this||{};return function(){let n=arguments;function a(o,s){let i=Object.assign({},o),l=i.className||a.className;r.p=Object.assign({theme:He&&He()},i),r.o=/ *go\d+/.test(l),i.className=$e.apply(r,n)+(l?" "+l:"");let d=t;return t[0]&&(d=i.as||t,delete i.as),Ge&&d[0]&&Ge(i),Tt(d,i)}return a}}var Xt=t=>typeof t=="function",Te=(t,e)=>Xt(t)?t(e):t,Qt=(()=>{let t=0;return()=>(++t).toString()})(),At=(()=>{let t;return()=>{if(t===void 0&&typeof window<"u"){let e=matchMedia("(prefers-reduced-motion: reduce)");t=!e||e.matches}return t}})(),Zt=20,jt=(t,e)=>{switch(e.type){case 0:return{...t,toasts:[e.toast,...t.toasts].slice(0,Zt)};case 1:return{...t,toasts:t.toasts.map(o=>o.id===e.toast.id?{...o,...e.toast}:o)};case 2:let{toast:r}=e;return jt(t,{type:t.toasts.find(o=>o.id===r.id)?1:0,toast:r});case 3:let{toastId:n}=e;return{...t,toasts:t.toasts.map(o=>o.id===n||n===void 0?{...o,dismissed:!0,visible:!1}:o)};case 4:return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(o=>o.id!==e.toastId)};case 5:return{...t,pausedAt:e.time};case 6:let a=e.time-(t.pausedAt||0);return{...t,pausedAt:void 0,toasts:t.toasts.map(o=>({...o,pauseDuration:o.pauseDuration+a}))}}},ke=[],ie={toasts:[],pausedAt:void 0},de=t=>{ie=jt(ie,t),ke.forEach(e=>{e(ie)})},er={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},tr=(t={})=>{let[e,r]=h.useState(ie),n=h.useRef(ie);h.useEffect(()=>(n.current!==ie&&r(ie),ke.push(r),()=>{let o=ke.indexOf(r);o>-1&&ke.splice(o,1)}),[]);let a=e.toasts.map(o=>{var s,i,l;return{...t,...t[o.type],...o,removeDelay:o.removeDelay||((s=t[o.type])==null?void 0:s.removeDelay)||t?.removeDelay,duration:o.duration||((i=t[o.type])==null?void 0:i.duration)||t?.duration||er[o.type],style:{...t.style,...(l=t[o.type])==null?void 0:l.style,...o.style}}});return{...e,toasts:a}},rr=(t,e="blank",r)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:e,ariaProps:{role:"status","aria-live":"polite"},message:t,pauseDuration:0,...r,id:r?.id||Qt()}),be=t=>(e,r)=>{let n=rr(e,t,r);return de({type:2,toast:n}),n.id},V=(t,e)=>be("blank")(t,e);V.error=be("error");V.success=be("success");V.loading=be("loading");V.custom=be("custom");V.dismiss=t=>{de({type:3,toastId:t})};V.remove=t=>de({type:4,toastId:t});V.promise=(t,e,r)=>{let n=V.loading(e.loading,{...r,...r?.loading});return typeof t=="function"&&(t=t()),t.then(a=>{let o=e.success?Te(e.success,a):void 0;return o?V.success(o,{id:n,...r,...r?.success}):V.dismiss(n),a}).catch(a=>{let o=e.error?Te(e.error,a):void 0;o?V.error(o,{id:n,...r,...r?.error}):V.dismiss(n)}),t};var nr=(t,e)=>{de({type:1,toast:{id:t,height:e}})},ar=()=>{de({type:5,time:Date.now()})},xe=new Map,or=1e3,sr=(t,e=or)=>{if(xe.has(t))return;let r=setTimeout(()=>{xe.delete(t),de({type:4,toastId:t})},e);xe.set(t,r)},ir=t=>{let{toasts:e,pausedAt:r}=tr(t);h.useEffect(()=>{if(r)return;let o=Date.now(),s=e.map(i=>{if(i.duration===1/0)return;let l=(i.duration||0)+i.pauseDuration-(o-i.createdAt);if(l<0){i.visible&&V.dismiss(i.id);return}return setTimeout(()=>V.dismiss(i.id),l)});return()=>{s.forEach(i=>i&&clearTimeout(i))}},[e,r]);let n=h.useCallback(()=>{r&&de({type:6,time:Date.now()})},[r]),a=h.useCallback((o,s)=>{let{reverseOrder:i=!1,gutter:l=8,defaultPosition:d}=s||{},u=e.filter(x=>(x.position||d)===(o.position||d)&&x.height),m=u.findIndex(x=>x.id===o.id),f=u.filter((x,v)=>vx.visible).slice(...i?[f+1]:[0,f]).reduce((x,v)=>x+(v.height||0)+l,0)},[e]);return h.useEffect(()=>{e.forEach(o=>{if(o.dismissed)sr(o.id,o.removeDelay);else{let s=xe.get(o.id);s&&(clearTimeout(s),xe.delete(o.id))}})},[e]),{toasts:e,handlers:{updateHeight:nr,startPause:ar,endPause:n,calculateOffset:a}}},cr=Z` +from { + transform: scale(0) rotate(45deg); + opacity: 0; +} +to { + transform: scale(1) rotate(45deg); + opacity: 1; +}`,dr=Z` +from { + transform: scale(0); + opacity: 0; +} +to { + transform: scale(1); + opacity: 1; +}`,lr=Z` +from { + transform: scale(0) rotate(90deg); + opacity: 0; +} +to { + transform: scale(1) rotate(90deg); + opacity: 1; +}`,ur=re("div")` + width: 20px; + opacity: 0; + height: 20px; + border-radius: 10px; + background: ${t=>t.primary||"#ff4b4b"}; + position: relative; + transform: rotate(45deg); + + animation: ${cr} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; + animation-delay: 100ms; + + &:after, + &:before { + content: ''; + animation: ${dr} 0.15s ease-out forwards; + animation-delay: 150ms; + position: absolute; + border-radius: 3px; + opacity: 0; + background: ${t=>t.secondary||"#fff"}; + bottom: 9px; + left: 4px; + height: 2px; + width: 12px; + } + + &:before { + animation: ${lr} 0.15s ease-out forwards; + animation-delay: 180ms; + transform: rotate(90deg); + } +`,mr=Z` + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +`,fr=re("div")` + width: 12px; + height: 12px; + box-sizing: border-box; + border: 2px solid; + border-radius: 100%; + border-color: ${t=>t.secondary||"#e0e0e0"}; + border-right-color: ${t=>t.primary||"#616161"}; + animation: ${mr} 1s linear infinite; +`,pr=Z` +from { + transform: scale(0) rotate(45deg); + opacity: 0; +} +to { + transform: scale(1) rotate(45deg); + opacity: 1; +}`,hr=Z` +0% { + height: 0; + width: 0; + opacity: 0; +} +40% { + height: 0; + width: 6px; + opacity: 1; +} +100% { + opacity: 1; + height: 10px; +}`,gr=re("div")` + width: 20px; + opacity: 0; + height: 20px; + border-radius: 10px; + background: ${t=>t.primary||"#61d345"}; + position: relative; + transform: rotate(45deg); + + animation: ${pr} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; + animation-delay: 100ms; + &:after { + content: ''; + box-sizing: border-box; + animation: ${hr} 0.2s ease-out forwards; + opacity: 0; + animation-delay: 200ms; + position: absolute; + border-right: 2px solid; + border-bottom: 2px solid; + border-color: ${t=>t.secondary||"#fff"}; + bottom: 6px; + left: 6px; + height: 10px; + width: 6px; + } +`,yr=re("div")` + position: absolute; +`,xr=re("div")` + position: relative; + display: flex; + justify-content: center; + align-items: center; + min-width: 20px; + min-height: 20px; +`,br=Z` +from { + transform: scale(0.6); + opacity: 0.4; +} +to { + transform: scale(1); + opacity: 1; +}`,vr=re("div")` + position: relative; + transform: scale(0.6); + opacity: 0.4; + min-width: 20px; + animation: ${br} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; +`,wr=({toast:t})=>{let{icon:e,type:r,iconTheme:n}=t;return e!==void 0?typeof e=="string"?h.createElement(vr,null,e):e:r==="blank"?null:h.createElement(xr,null,h.createElement(fr,{...n}),r!=="loading"&&h.createElement(yr,null,r==="error"?h.createElement(ur,{...n}):h.createElement(gr,{...n})))},Cr=t=>` +0% {transform: translate3d(0,${t*-200}%,0) scale(.6); opacity:.5;} +100% {transform: translate3d(0,0,0) scale(1); opacity:1;} +`,Sr=t=>` +0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} +100% {transform: translate3d(0,${t*-150}%,-1px) scale(.6); opacity:0;} +`,Er="0%{opacity:0;} 100%{opacity:1;}",kr="0%{opacity:1;} 100%{opacity:0;}",Tr=re("div")` + display: flex; + align-items: center; + background: #fff; + color: #363636; + line-height: 1.3; + will-change: transform; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05); + max-width: 350px; + pointer-events: auto; + padding: 8px 10px; + border-radius: 8px; +`,Ar=re("div")` + display: flex; + justify-content: center; + margin: 4px 10px; + color: inherit; + flex: 1 1 auto; + white-space: pre-line; +`,jr=(t,e)=>{let r=t.includes("top")?1:-1,[n,a]=At()?[Er,kr]:[Cr(r),Sr(r)];return{animation:e?`${Z(n)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${Z(a)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},_r=h.memo(({toast:t,position:e,style:r,children:n})=>{let a=t.height?jr(t.position||e||"top-center",t.visible):{opacity:0},o=h.createElement(wr,{toast:t}),s=h.createElement(Ar,{...t.ariaProps},Te(t.message,t));return h.createElement(Tr,{className:t.className,style:{...a,...r,...t.style}},typeof n=="function"?n({icon:o,message:s}):h.createElement(h.Fragment,null,o,s))});Jt(h.createElement);var Nr=({id:t,className:e,style:r,onHeightUpdate:n,children:a})=>{let o=h.useCallback(s=>{if(s){let i=()=>{let l=s.getBoundingClientRect().height;n(t,l)};i(),new MutationObserver(i).observe(s,{subtree:!0,childList:!0,characterData:!0})}},[t,n]);return h.createElement("div",{ref:o,className:e,style:r},a)},$r=(t,e)=>{let r=t.includes("top"),n=r?{top:0}:{bottom:0},a=t.includes("center")?{justifyContent:"center"}:t.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:At()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${e*(r?1:-1)}px)`,...n,...a}},Or=$e` + z-index: 9999; + > * { + pointer-events: auto; + } +`,Ce=16,Rr=({reverseOrder:t,position:e="top-center",toastOptions:r,gutter:n,children:a,containerStyle:o,containerClassName:s})=>{let{toasts:i,handlers:l}=ir(r);return h.createElement("div",{id:"_rht_toaster",style:{position:"fixed",zIndex:9999,top:Ce,left:Ce,right:Ce,bottom:Ce,pointerEvents:"none",...o},className:s,onMouseEnter:l.startPause,onMouseLeave:l.endPause},i.map(d=>{let u=d.position||e,m=l.calculateOffset(d,{reverseOrder:t,gutter:n,defaultPosition:e}),f=$r(u,m);return h.createElement(Nr,{id:d.id,key:d.id,onHeightUpdate:l.updateHeight,className:d.visible?Or:"",style:f},d.type==="custom"?Te(d.message,d):a?a(d):h.createElement(_r,{toast:d,position:u}))}))},Se=V;const Dr={},ot=t=>{let e;const r=new Set,n=(u,m)=>{const f=typeof u=="function"?u(e):u;if(!Object.is(f,e)){const x=e;e=m??(typeof f!="object"||f===null)?f:Object.assign({},e,f),r.forEach(v=>v(e,x))}},a=()=>e,l={setState:n,getState:a,getInitialState:()=>d,subscribe:u=>(r.add(u),()=>r.delete(u)),destroy:()=>{(Dr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},d=e=t(n,a,l);return l},Pr=t=>t?ot(t):ot;var Pe={exports:{}},Me={},Ie={exports:{}},Le={};var st;function Mr(){if(st)return Le;st=1;var t=Qe();function e(m,f){return m===f&&(m!==0||1/m===1/f)||m!==m&&f!==f}var r=typeof Object.is=="function"?Object.is:e,n=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function i(m,f){var x=f(),v=n({inst:{value:x,getSnapshot:f}}),p=v[0].inst,y=v[1];return o(function(){p.value=x,p.getSnapshot=f,l(p)&&y({inst:p})},[m,x,f]),a(function(){return l(p)&&y({inst:p}),m(function(){l(p)&&y({inst:p})})},[m]),s(x),x}function l(m){var f=m.getSnapshot;m=m.value;try{var x=f();return!r(m,x)}catch{return!0}}function d(m,f){return f()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:i;return Le.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,Le}var it;function Ir(){return it||(it=1,Ie.exports=Mr()),Ie.exports}var ct;function Lr(){if(ct)return Me;ct=1;var t=Qe(),e=Ir();function r(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var n=typeof Object.is=="function"?Object.is:r,a=e.useSyncExternalStore,o=t.useRef,s=t.useEffect,i=t.useMemo,l=t.useDebugValue;return Me.useSyncExternalStoreWithSelector=function(d,u,m,f,x){var v=o(null);if(v.current===null){var p={hasValue:!1,value:null};v.current=p}else p=v.current;v=i(function(){function g(A){if(!C){if(C=!0,T=A,A=f(A),x!==void 0&&p.hasValue){var I=p.value;if(x(I,A))return j=I}return j=A}if(I=j,n(T,A))return I;var q=f(A);return x!==void 0&&x(I,q)?(T=A,I):(T=A,j=q)}var C=!1,T,j,N=m===void 0?null:m;return[function(){return g(u())},N===null?void 0:function(){return g(N())}]},[u,m,f,x]);var y=a(d,v[0],v[1]);return s(function(){p.hasValue=!0,p.value=y},[y]),l(y),y},Me}var dt;function Ur(){return dt||(dt=1,Pe.exports=Lr()),Pe.exports}var qr=Ur();const Vr=St(qr),_t={},{useDebugValue:Wr}=B,{useSyncExternalStoreWithSelector:Br}=Vr;let lt=!1;const Fr=t=>t;function zr(t,e=Fr,r){(_t?"production":void 0)!=="production"&&r&&!lt&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),lt=!0);const n=Br(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,r);return Wr(n),n}const Yr=t=>{(_t?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?Pr(t):t,r=(n,a)=>zr(e,n,a);return Object.assign(r,e),r},Hr=t=>Yr,Ue={BASE_URL:"/studio/ui/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_BASE_URL:"/studio/ui/"},Ke=new Map,Ee=t=>{const e=Ke.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([r,n])=>[r,n.getState()])):{}},Gr=(t,e,r)=>{if(t===void 0)return{type:"untracked",connection:e.connect(r)};const n=Ke.get(r.name);if(n)return{type:"tracked",store:t,...n};const a={connection:e.connect(r),stores:{}};return Ke.set(r.name,a),{type:"tracked",store:t,...a}},Kr=(t,e={})=>(r,n,a)=>{const{enabled:o,anonymousActionType:s,store:i,...l}=e;let d;try{d=(o??(Ue?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return(Ue?"production":void 0)!=="production"&&o&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),t(r,n,a);const{connection:u,...m}=Gr(i,d,l);let f=!0;a.setState=(p,y,g)=>{const C=r(p,y);if(!f)return C;const T=g===void 0?{type:s||"anonymous"}:typeof g=="string"?{type:g}:g;return i===void 0?(u?.send(T,n()),C):(u?.send({...T,type:`${i}/${T.type}`},{...Ee(l.name),[i]:a.getState()}),C)};const x=(...p)=>{const y=f;f=!1,r(...p),f=y},v=t(a.setState,n,a);if(m.type==="untracked"?u?.init(v):(m.stores[m.store]=a,u?.init(Object.fromEntries(Object.entries(m.stores).map(([p,y])=>[p,p===m.store?v:y.getState()])))),a.dispatchFromDevtools&&typeof a.dispatch=="function"){let p=!1;const y=a.dispatch;a.dispatch=(...g)=>{(Ue?"production":void 0)!=="production"&&g[0].type==="__setState"&&!p&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),p=!0),y(...g)}}return u.subscribe(p=>{var y;switch(p.type){case"ACTION":if(typeof p.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return qe(p.payload,g=>{if(g.type==="__setState"){if(i===void 0){x(g.state);return}Object.keys(g.state).length!==1&&console.error(` + [zustand devtools middleware] Unsupported __setState action format. + When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(), + and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } } + `);const C=g.state[i];if(C==null)return;JSON.stringify(a.getState())!==JSON.stringify(C)&&x(C);return}a.dispatchFromDevtools&&typeof a.dispatch=="function"&&a.dispatch(g)});case"DISPATCH":switch(p.payload.type){case"RESET":return x(v),i===void 0?u?.init(a.getState()):u?.init(Ee(l.name));case"COMMIT":if(i===void 0){u?.init(a.getState());return}return u?.init(Ee(l.name));case"ROLLBACK":return qe(p.state,g=>{if(i===void 0){x(g),u?.init(a.getState());return}x(g[i]),u?.init(Ee(l.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return qe(p.state,g=>{if(i===void 0){x(g);return}JSON.stringify(a.getState())!==JSON.stringify(g[i])&&x(g[i])});case"IMPORT_STATE":{const{nextLiftedState:g}=p.payload,C=(y=g.computedStates.slice(-1)[0])==null?void 0:y.state;if(!C)return;x(i===void 0?C:C[i]),u?.send(null,g);return}case"PAUSE_RECORDING":return f=!f}return}}),v},Jr=Kr,qe=(t,e)=>{let r;try{r=JSON.parse(t)}catch(n){console.error("[zustand devtools middleware] Could not parse the received json",n)}r!==void 0&&e(r)},Xr="agentomatic-studio:lastUrl",ut="http://127.0.0.1:8000";function Qr(){return typeof window>"u"?!1:(window.location.pathname||"").includes("/studio/ui")}function Zr(t){try{const e=new URL(t),r=e.hostname,n=e.port||(e.protocol==="https:"?"443":"80");return(r==="127.0.0.1"||r==="localhost")&&(n==="8000"||n==="3000")}catch{return!1}}function Ae(){if(typeof window>"u")return ut;const t=Qr();try{const e=localStorage.getItem(Xr);if(e&&/^https?:\/\//i.test(e)){const r=e.replace(/\/$/,"");if(!(t&&Zr(r)))return r}}catch{}return t?window.location.origin:ut}function mt(t){return(t||"").trim().replace(/\/$/,"")}class ft{static connect(e,r,n,a){const o=new AbortController;return(async()=>{try{const i=await fetch(e,{method:"POST",headers:{...n,Accept:"text/event-stream"},body:JSON.stringify(r),signal:o.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);const l=i.body?.getReader();if(!l)throw new Error("No response body");const d=new TextDecoder;let u="",m="";for(;;){const{done:f,value:x}=await l.read();if(f){a.onDone?.();break}u+=d.decode(x,{stream:!0});const v=u.split(` +`);u=v.pop()||"";for(const p of v){if(p.startsWith("event: ")){m=p.slice(7).trim();continue}if(p.startsWith("data: ")){const y=p.slice(6).trim();if(y==="[DONE]"){a.onDone?.(),m="";return}try{const g=JSON.parse(y);switch(m&&!g.event&&(g.event=m),m="",a.onEvent?.(g),g.event){case"run_start":a.onRunStart?.(g);break;case"node_start":a.onNodeStart?.(g);break;case"node_end":a.onNodeEnd?.(g);break;case"state_update":a.onStateUpdate?.(g);break;case"message_chunk":a.onMessageChunk?.(g);break;case"run_complete":a.onRunComplete?.(g);break;case"run_error":a.onRunError?.(g);break;case"breakpoint_hit":a.onBreakpointHit?.(g);break}}catch(g){console.warn("Failed to parse SSE event:",y,g)}}p.trim()===""&&(m="")}}}catch(i){i.name!=="AbortError"&&a.onError?.(i)}})(),o}}function en({schemaFields:t,rootInput:e,input:r,userMessage:n,threadId:a,breakpoints:o,checkpointId:s}){const i=Object.prototype.hasOwnProperty.call(t,"query"),l=typeof r=="string",d=n||t.query;return{...t,...e!==void 0?{agent_input:e}:{},...(i||l)&&d?{query:d}:{},thread_id:a,user_id:t.user_id||"studio-user",breakpoints:o,checkpoint_id:s}}function So(t){if(!t||typeof t!="object")return null;if(t.type||t.properties||t.$ref||t.anyOf||t.oneOf||t.allOf)return t;const e={str:"string",string:"string",int:"integer",integer:"integer",float:"number",number:"number",bool:"boolean",boolean:"boolean",dict:"object",object:"object",list:"array",array:"array"},r={},n=[];for(const[a,o]of Object.entries(t)){const s=o&&typeof o=="object"&&!Array.isArray(o)?o:{type:o},i=typeof s.type=="string"?s.type:void 0;r[a]={...s,type:i?e[i]||i:void 0},s.default===void 0&&n.push(a)}return{type:"object",properties:r,...n.length?{required:n}:{}}}function Ze(t,e){if(!t||typeof t!="object")return{};if(!t.$ref||typeof t.$ref!="string")return t;const r=t.$ref;if(!r.startsWith("#/"))return t;const n=r.slice(2).split("/");let a=e;for(const s of n){if(a==null||typeof a!="object")return t;a=a[s]}if(!a||typeof a!="object")return t;const o={...t};return delete o.$ref,{...a,...o}}function Y(t,e){if(!t||typeof t!="object")return{};let r=Ze(t,e);if(Array.isArray(r.allOf)){const{allOf:n,...a}=r,o=n.reduce((s,i)=>{const l=Y(i,e),d=Array.from(new Set([...Array.isArray(s.required)?s.required:[],...Array.isArray(l.required)?l.required:[]]));return{...s,...l,properties:{...s.properties||{},...l.properties||{}},...d.length?{required:d}:{}}},{});r={...o,...a,properties:{...o.properties||{},...a.properties||{}}}}if(!r.type&&Array.isArray(r.anyOf)){const n=r.anyOf.find(a=>a&&(a.type||a.$ref||a.properties));if(n){const a={...r};delete a.anyOf,r={...Y(n,e),...a}}}if(!r.type&&Array.isArray(r.oneOf)){const n=r.oneOf.find(a=>a&&(a.type||a.$ref||a.properties));if(n){const a={...r};delete a.oneOf,r={...Y(n,e),...a}}}if(Array.isArray(r.type)){const n=r.type.find(a=>a!=="null")||r.type[0];r={...r,type:n}}return r}function Eo(t,e){if(!t||typeof t!="object")return[];const r=Ze(t,e),a=(Array.isArray(r.oneOf)?r.oneOf:Array.isArray(r.anyOf)?r.anyOf:[]).map(o=>Y(o,e)).filter(o=>o.type!=="null");return a.length>1?a:[]}function ko(t,e){return e?.title&&typeof e.title=="string"?e.title:t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,r=>r.toUpperCase())}function To(t){if(typeof t=="string")return t;if(t===null)return"null";if(typeof t>"u")return"undefined";try{return JSON.stringify(t)}catch{return String(t)}}function Ao(t,e){return t.findIndex(r=>{if(Object.is(r,e))return!0;try{return JSON.stringify(r)===JSON.stringify(e)}catch{return!1}})}function jo(t,e){if(e==="")return;const r=Number(e);return Number.isInteger(r)&&r>=0&&r0||t.type&&t.type!=="object"||t.$ref||t.allOf||t.anyOf||t.oneOf)}function Nt(t,e){if(!t||typeof t!="object")return{};const r=e||t,n=Y(t,r);if(n.default!==void 0)return typeof n.default=="object"&&!Array.isArray(n.default)?{...n.default}:{};const a=n.properties||{},o={};for(const[s,i]of Object.entries(a)){const l=Y(i,r);if(l.const!==void 0){o[s]=l.const;continue}if(l.default!==void 0){o[s]=l.default;continue}switch(l.type){case"string":o[s]="";break;case"number":case"integer":o[s]=l.minimum??0;break;case"boolean":o[s]=!1;break;case"array":o[s]=[];break;case"object":o[s]=Nt(l,r);break}}return o}function No(t,e){if(!t||typeof t!="object")return{};const r=e||t,n=Y(t,r);if(n.const!==void 0)return n.const;if(n.default!==void 0)return n.default;if(n.type==="object"||n.properties)return Nt(n,r);switch(n.type){case"array":return[];case"boolean":return!1;case"number":case"integer":return n.minimum??0;case"null":return null;case"string":return"";default:return{}}}function $o(t,e,r){if(!t||typeof t!="object")return[];const n=r||t,a=s=>s==null||typeof s=="string"&&!s.trim(),o=(s,i,l,d)=>{if(d>12)return[];const u=Ze(s,n),m=(Array.isArray(u.oneOf)?u.oneOf:u.anyOf)?.filter(g=>Y(g,n).type!=="null")||[];if(m.length>1){const g=m.map(C=>o(C,i,l,d+1));return g.find(C=>C.length===0)??g.sort((C,T)=>C.length-T.length)[0]??[]}const f=[],x=Y(s,n),v=x.properties||{},p=new Set(Array.isArray(x.required)?x.required:[]),y=i&&typeof i=="object"&&!Array.isArray(i)?i:void 0;for(const g of Array.from(p)){const C=y?.[g],T=l?`${l}.${g}`:g;if(a(C)){f.push(T);continue}f.push(...o(v[g]||{},C,T,d+1))}if(y)for(const[g,C]of Object.entries(v))p.has(g)||a(y[g])||f.push(...o(C,y[g],l?`${l}.${g}`:g,d+1));return Array.isArray(i)&&x.items&&i.forEach((g,C)=>f.push(...o(x.items,g,`${l}[${C}]`,d+1))),f};return o(t,e,"",0)}function tn(t){if(!t||typeof t!="object")return"";if(typeof t.query=="string"&&t.query.trim())return t.query;if(typeof t.current_query=="string"&&t.current_query.trim())return t.current_query;for(const[e,r]of Object.entries(t))if(e.endsWith("_query")&&typeof r=="string"&&r.trim())return r;for(const e of["message","text","input","prompt","content"]){const r=t[e];if(typeof r=="string"&&r.trim())return r}for(const e of Object.values(t))if(typeof e=="string"&&e.trim())return e;try{const e=JSON.stringify(t);return e==="{}"?"":e}catch{return""}}function Oo(t){if(!t||typeof t!="object")return[];const e=Y(t,t),r=e.properties||{},n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(r).map(([a,o])=>{const s=Y(o,t);let i=s.type||"any";return i==="array"&&s.items&&(i=`array<${Y(s.items,t).type||"any"}>`),{name:a,type:String(i),required:n.has(a),description:typeof s.description=="string"?s.description:typeof s.title=="string"?s.title:void 0}})}const le=t=>{if(!t)return"";const e=["tool:","llm:","retriever:","subagent:"];for(const r of e)if(t.startsWith(r))return t.slice(r.length);return t},rn=(t,e)=>{if(t.length===0)return t;const r=new Map,n=new Map;t.forEach(p=>{r.set(p.id,[]),n.set(p.id,[])}),e.forEach(p=>{r.get(p.source)?.push(p.target),n.get(p.target)?.push(p.source)});const a=t.filter(p=>n.get(p.id)?.length===0);t.filter(p=>r.get(p.id)?.length===0);const o=[],s=new Set,i=new Map,l=[];for(a.forEach(p=>{l.push({nodeId:p.id,layer:0})}),l.length===0&&t.length>0&&l.push({nodeId:t[0].id,layer:0});l.length>0;){const{nodeId:p,layer:y}=l.shift();if(s.has(p))continue;for(s.add(p);o.length<=y;)o.push([]);o[y].push(p),i.set(p,y),(r.get(p)||[]).forEach(C=>{s.has(C)||l.push({nodeId:C,layer:y+1})})}t.forEach(p=>{if(!s.has(p.id)){const y=o.length;o.length===0?o.push([]):o.push([]),o[y].push(p.id),i.set(p.id,y)}});const d=100,u=220,m=140,f=100,x=100;return t.map(p=>{const y=i.get(p.id)||0,g=o[y]||[],C=g.indexOf(p.id),T=g.length*d+(g.length-1)*m,j=x-T/2+(g.length>1?0:T/2),N=f+y*u,A=j+C*(d+m);return{...p,position:{x:N,y:A}}})};class nn{constructor(){this.listeners=new Map,this.globalListeners=new Set}subscribe(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>{this.listeners.get(e)?.delete(r)}}subscribeAll(e){return this.globalListeners.add(e),()=>{this.globalListeners.delete(e)}}emit(e){this.listeners.get(e.type)?.forEach(r=>{try{r(e)}catch(n){console.error("Error in live update listener:",n)}}),this.globalListeners.forEach(r=>{try{r(e)}catch(n){console.error("Error in global live update listener:",n)}})}getListenerCount(){const e={};return this.listeners.forEach((r,n)=>{e[n]=r.size}),{total:this.globalListeners.size+Array.from(this.listeners.values()).reduce((r,n)=>r+n.size,0),byType:e}}}const R=new nn;let P=null;const Je=t=>{P=t},an=t=>{const e=t.nodes.map(n=>({id:n.id,type:n.type||"processing",data:{label:n.name,description:n.metadata?.description||"",status:"idle",metadata:n.metadata},position:{x:0,y:0}})),r=t.edges.map(n=>({id:n.id,source:n.source,target:n.target,type:n.condition?"conditional":"default",data:{label:n.condition||void 0}}));return{nodes:rn(e,r),edges:r}},Ve=(t,e)=>({id:t?.id||t?.thread_id||"",name:t?.title||`Thread ${(t?.id||t?.thread_id||"").slice(-8)}`,messages:[],createdAt:new Date(t?.created_at||Date.now()),updatedAt:new Date(t?.updated_at||t?.created_at||Date.now()),metadata:t?.metadata||{},agentId:e}),on=t=>({id:t?.id||t?.message_id||`message-${Date.now()}`,role:t?.role==="user"||t?.role==="system"?t.role:"assistant",content:typeof t?.content=="string"?t.content:JSON.stringify(t?.content??t?.message??""),timestamp:new Date(t?.timestamp||t?.created_at||Date.now()),metadata:t?.metadata||{}}),sn=(t,e)=>{if(e&&e.trim().length>0)return e.trim();const r=t.filter(l=>l.data?.intermediate_results);for(const l of r.reverse()){const d=l.data.intermediate_results;for(const[u,m]of Object.entries(d))if(m&&typeof m=="object"){const f=m,x=f.output&&typeof f.output=="object"?f.output:f;if(x.response&&typeof x.response=="string"&&x.response.trim().length>0)return x.response}}const n=t.filter(l=>l.type==="output"&&l.data?.output);for(const l of n.reverse()){const d=l.data.output;if(d&&typeof d=="object"){const u=d.output&&typeof d.output=="object"?d.output:d;if(u.response&&typeof u.response=="string"&&u.response.trim().length>0)return u.response;const m=["result","content","text","message","answer"];for(const f of m)if(u[f]&&typeof u[f]=="string"&&u[f].trim().length>0)return u[f]}if(typeof d=="string"&&d.trim().length>0)return d}const a=t.filter(l=>l.data?.final_response&&typeof l.data.final_response=="string"&&l.data.final_response.trim().length>0);if(a.length>0)return a[a.length-1].data.final_response;const o=t.filter(l=>l.data?.state_updates?.intermediate_results);for(const l of o.reverse()){const d=l.data.state_updates.intermediate_results;for(const[u,m]of Object.entries(d))if(u.includes("respond")&&m&&typeof m=="object"){const f=m.response;if(f&&typeof f=="string"&&f.trim().length>0)return f}}const s=t.filter(l=>(l.nodeId.includes("respond")||l.nodeId.includes("generation")||l.nodeName.toLowerCase().includes("respond")||l.nodeName.toLowerCase().includes("generation"))&&l.type==="output"&&l.data?.output);for(const l of s.reverse()){const d=l.data.output;if(d.response&&typeof d.response=="string"&&d.response.trim().length>0)return d.response;if(d.result&&typeof d.result=="string"&&d.result.trim().length>0)return d.result;if(d.content&&typeof d.content=="string"&&d.content.trim().length>0)return d.content}const i=t.filter(l=>l.type==="output"&&l.data?.output&&typeof l.data.output=="object").slice(-5);for(const l of i.reverse()){const d=l.data.output,u=[d.response,d.result,d.content,d.text,d.message,d.answer,d.clarification_request];for(const m of u)if(m&&typeof m=="string"&&m.trim().length>20)return m}return null},We={currentView:"graph",graphState:{nodes:[],edges:[],currentNode:void 0,executionPath:[]},isConnected:!1,isLoading:!1},Be={isExecuting:!1,isPaused:!1,currentState:{},logs:[],breakpoints:[]},me=Hr()(Jr((t,e)=>({...We,threads:[],agents:[],assistants:[],runs:[],config:{apiUrl:Ae(),agentId:void 0,apiKey:void 0},graphState:We.graphState,activeInterrupts:[],subAgentResults:[],agentSchemas:{},schemasLoading:!1,setCurrentView:r=>t({currentView:r}),builderPipelineToLoad:null,setBuilderPipelineToLoad:r=>t({builderPipelineToLoad:r}),setSelectedThread:r=>{t({selectedThread:r});const n=e();r&&n.selectedAgent&&n.switchToExecutionContext(r.id,n.selectedAgent.id)},setSelectedAgent:r=>{const n=r?{...r,config:{},graph_id:r.graph?.id||""}:void 0;t({selectedAgent:r,selectedAssistant:n});const a=e();r&&a.selectedThread&&a.switchToExecutionContext(a.selectedThread.id,r.id),r?.id&&a.fetchAgentSchemas(r.id)},setSelectedAssistant:r=>{t({selectedAssistant:r,selectedAgent:r});const n=e();r&&n.selectedThread&&n.switchToExecutionContext(n.selectedThread.id,r.id),r?.id&&n.fetchAgentSchemas(r.id)},setCurrentRun:r=>t({currentRun:r}),setGraphState:r=>{t({graphState:r}),R.emit({type:"GRAPH_STATE_CHANGED",data:r})},setIsConnected:r=>t({isConnected:r}),setIsLoading:r=>t({isLoading:r}),setError:r=>t({error:r}),sidebarCollapsed:!1,setSidebarCollapsed:r=>t({sidebarCollapsed:r}),darkMode:!1,setDarkMode:r=>t({darkMode:r}),isStreaming:!1,setIsStreaming:r=>t({isStreaming:r}),streamingMessage:"",setStreamingMessage:r=>t({streamingMessage:r}),activeAbortController:null,setActiveAbortController:r=>t({activeAbortController:r}),connectionStatus:"disconnected",setConnectionStatus:r=>t({connectionStatus:r}),retryAttempts:0,maxRetryAttempts:3,attemptReconnection:async()=>{const r=e();if(r.retryAttempts>=r.maxRetryAttempts){t({connectionStatus:"failed"});return}t({connectionStatus:"reconnecting",retryAttempts:r.retryAttempts+1});try{if(P)try{if(await P.healthCheck()){t({connectionStatus:"connected",isConnected:!0,retryAttempts:0,error:void 0}),R.emit({type:"GRAPH_STATE_CHANGED",data:r.graphState});return}}catch{console.log("Studio API health check failed, trying legacy endpoints...")}const n=["/studio/info","/health","/ready","/status","/"];let a=!1,o=null;for(const s of n)try{console.log(`🔍 Testing connectivity with endpoint: ${s}`);const i=await fetch(`${r.config.apiUrl}${s}`,{method:"GET",headers:{"Content-Type":"application/json",...r.config.apiKey&&{"X-Api-Key":r.config.apiKey,Authorization:`Bearer ${r.config.apiKey}`}}});if(i.status<500){console.log(`✅ Server responding on ${s} with status ${i.status}`),a=!0;break}}catch(i){console.log(`❌ Failed to connect to ${s}:`,i),o=i;continue}if(a)t({connectionStatus:"connected",isConnected:!0,retryAttempts:0,error:void 0}),R.emit({type:"GRAPH_STATE_CHANGED",data:r.graphState});else throw o||new Error("All endpoints failed to respond")}catch(n){console.error(`Reconnection attempt ${r.retryAttempts} failed:`,n),r.retryAttempts>=r.maxRetryAttempts?t({connectionStatus:"failed",isConnected:!1,error:`Failed to reconnect after ${r.maxRetryAttempts} attempts`}):setTimeout(()=>{const a=e();a.connectionStatus==="reconnecting"&&a.attemptReconnection()},2e3*r.retryAttempts)}},replaceThreads:r=>t(n=>({threads:r,selectedThread:n.selectedThread?r.find(a=>a.id===n.selectedThread?.id):void 0})),refreshThreads:async r=>{if(!P||!r)return[];const n=await P.listThreads(r),a=e().threads,o=n.map(s=>{const i=Ve(s,r),l=a.find(d=>d.id===i.id);return l?.messages.length?{...i,messages:l.messages}:i});return e().replaceThreads(o),o},hydrateThreadMessages:async(r,n)=>{if(!P||!r||!n)return;const a=(await P.getMessages(n,r)).map(i=>on(i)),o=e().threads.find(i=>i.id===r);if(!o)return;const s={...o,messages:a,updatedAt:new Date};return e().updateThread(r,{messages:s.messages,updatedAt:s.updatedAt}),s},createPersistentThread:async(r,n="New Chat")=>{if(!P||!r)throw new Error("Connect Studio to a live agent before creating a thread.");const a=await P.createThread(r,"studio-user",n),o=Ve(a,r);return e().addThread(o),e().setSelectedThread(o),o},deletePersistentThread:async r=>{const n=r.agentId||e().selectedAssistant?.id;if(!P||!n)throw new Error("Connect Studio to the thread agent before deleting this conversation.");await P.deleteThread(n,r.id),e().deleteThread(r.id)},addThread:r=>t(n=>({threads:[...n.threads,r]})),updateThread:(r,n)=>t(a=>{const o=a.threads.map(s=>s.id===r?{...s,...n}:s);return R.emit({type:"THREAD_UPDATED",data:{threadId:r,updates:n}}),{threads:o}}),deleteThread:r=>t(n=>({threads:n.threads.filter(a=>a.id!==r),selectedThread:n.selectedThread?.id===r?void 0:n.selectedThread})),addMessageToThread:(r,n)=>t(a=>{const o=a.threads.map(i=>i.id===r?{...i,messages:[...i.messages,n],updatedAt:new Date}:i),s=a.selectedThread?.id===r?{...a.selectedThread,messages:[...a.selectedThread.messages,n],updatedAt:new Date}:a.selectedThread;return R.emit({type:"MESSAGE_ADDED",data:{threadId:r,message:n}}),{threads:o,selectedThread:s}}),addAgent:r=>t(n=>({agents:[...n.agents,r],assistants:[...n.assistants,{...r,config:{},graph_id:r.graph?.id||""}]})),updateAgent:(r,n)=>t(a=>({agents:a.agents.map(o=>o.id===r?{...o,...n}:o),assistants:a.assistants.map(o=>o.id===r?{...o,...n,config:{},graph_id:o.graph_id}:o)})),deleteAgent:r=>t(n=>({agents:n.agents.filter(a=>a.id!==r),assistants:n.assistants.filter(a=>a.id!==r),selectedAgent:n.selectedAgent?.id===r?void 0:n.selectedAgent,selectedAssistant:n.selectedAssistant?.id===r?void 0:n.selectedAssistant})),clearAgents:()=>t({agents:[],assistants:[],selectedAgent:void 0,selectedAssistant:void 0}),addAssistant:r=>t(n=>({assistants:[...n.assistants,r],agents:[...n.agents,{...r,type:"chat",model:"",provider:"",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:!1,timeout:3e4}]})),updateAssistant:(r,n)=>t(a=>({assistants:a.assistants.map(o=>o.id===r?{...o,...n}:o),agents:a.agents.map(o=>o.id===r?{...o,...n}:o)})),deleteAssistant:r=>t(n=>({assistants:n.assistants.filter(a=>a.id!==r),agents:n.agents.filter(a=>a.id!==r),selectedAssistant:n.selectedAssistant?.id===r?void 0:n.selectedAssistant,selectedAgent:n.selectedAgent?.id===r?void 0:n.selectedAgent})),clearAssistants:()=>t({assistants:[],agents:[],selectedAssistant:void 0,selectedAgent:void 0}),addRun:r=>t(n=>({runs:[...n.runs,r]})),updateRun:(r,n)=>t(a=>({runs:a.runs.map(o=>o.id===r?{...o,...n}:o)})),setConfig:r=>t({config:r}),fetchAgentSchemas:async(r,n=!1)=>{if(!r)return null;const a=e();if(!n&&a.agentSchemas[r])return a.agentSchemas[r];if(!P)return console.warn("fetchAgentSchemas: Studio API client not initialized"),null;try{t({schemasLoading:!0});const o=await P.getSchemas(r);return t(s=>({agentSchemas:{...s.agentSchemas,[r]:o},schemasLoading:!1})),o}catch(o){return console.warn(`Failed to fetch schemas for ${r}:`,o),t({schemasLoading:!1}),null}},fetchGraphData:async r=>{try{t({isLoading:!0,error:void 0}),console.log(`🔍 Fetching graph data for agent: ${r}`);let n=new Error("The Studio API client is not initialized");if(P)try{const o=await P.getGraph(r);console.log("📊 Received graph topology from API:",o);const{nodes:s,edges:i}=an(o);t({graphState:{nodes:s,edges:i,currentNode:void 0,executionPath:[]},isLoading:!1}),console.log(`✅ Loaded graph for ${r}: ${s.length} nodes, ${i.length} edges`);return}catch(o){n=o,console.warn("⚠️ Could not fetch graph from Studio API:",o)}const a=n instanceof Error?n.message:String(n);t({graphState:{nodes:[],edges:[],currentNode:void 0,executionPath:[]},isLoading:!1,error:"Unable to load live graph topology for "+r+": "+a});return}catch(n){console.error("❌ Error fetching graph data:",n);const a=e();a.connectionStatus!=="reconnecting"&&a.retryAttempts{const a=e(),o=r||a.selectedThread?.id||"default",s=n||a.selectedAgent?.id||"default";return`${o}-${s}`},switchToExecutionContext:(r,n)=>{const a=e(),o=a.getExecutionContextKey(r,n),s=a.executionContexts.get(o);if(s)t({executionContext:s});else{const i={...Be,threadId:r||a.selectedThread?.id,agentId:n||a.selectedAgent?.id,assistantId:n||a.selectedAgent?.id},l=new Map(a.executionContexts);l.set(o,i),t({executionContext:i,executionContexts:l})}},setExecutionContext:r=>t(n=>{const a={...n.executionContext,...r},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),startExecution:(r={},n)=>{const a=`exec_${Date.now()}`;e(),t(o=>{const s={...o.executionContext,isExecuting:!0,isPaused:!1,currentState:r,executionId:a,startTime:new Date,endTime:void 0,threadId:o.selectedThread?.id,agentId:o.selectedAgent?.id,assistantId:o.selectedAgent?.id},i=o.getExecutionContextKey(),l=new Map(o.executionContexts);return l.set(i,s),R.emit({type:"EXECUTION_STARTED",data:{threadId:o.selectedThread?.id||"unknown",assistantId:o.selectedAgent?.id||"unknown",initialState:r}}),{executionContext:s,executionContexts:l,graphState:{...o.graphState||{nodes:[],edges:[],executionPath:[]},currentNode:n||o.graphState?.nodes?.find(d=>d.type==="start")?.id,executionPath:n?[n]:[]}}})},pauseExecution:()=>t(r=>{const n={...r.executionContext,isPaused:!0},a=r.getExecutionContextKey(),o=new Map(r.executionContexts);return o.set(a,n),{executionContext:n,executionContexts:o}}),resumeExecution:async(r=null)=>{const n=e(),{selectedAgent:a,selectedThread:o}=n;if(!P||!a||!o){const d="A connected agent and interrupted thread are required to resume execution.";t({error:d}),n.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:d,data:{action:"resume"}});return}const s=o.id,i=a.id,l=d=>t(u=>{const m={...u.executionContext,isPaused:d},f=u.getExecutionContextKey(),x=new Map(u.executionContexts);return x.set(f,m),{executionContext:m,executionContexts:x}});try{l(!1);const d=ft.connect(P.getResumeStreamUrl(i,s),{value:r,action:"approve"},P.getHeaders(),{onRunStart:u=>e().addExecutionLog({nodeId:"system",nodeName:"System",type:"info",message:`Resumed run: ${u.run_id}`,data:u.data}),onNodeStart:u=>{const m=le(u.node);if(!m)return;const f=e();f.setGraphState({...f.graphState,currentNode:m,executionPath:[...f.graphState.executionPath,m]}),f.addExecutionLog({nodeId:m,nodeName:m,type:"input",message:`Resumed node: ${m}`,data:u.data})},onNodeEnd:u=>{const m=le(u.node);if(!m)return;const f=e();f.addExecutionLog({nodeId:m,nodeName:m,type:"output",message:`Completed node: ${m}`,data:u.data,duration:u.duration_ms||void 0}),f.setGraphExecutionState({...f.executionContext.currentState,[m]:u.data})},onStateUpdate:u=>{const m=e();m.setGraphExecutionState({...m.executionContext.currentState,...u.data})},onMessageChunk:u=>R.emit({type:"STREAMING_UPDATE",data:{messageId:`resume-${u.run_id}`,content:u.data?.content||"",isComplete:!1}}),onBreakpointHit:u=>{const m=e();m.pauseExecution(),m.addExecutionLog({nodeId:le(u.node)||"system",nodeName:"System",type:"info",message:`Execution paused at breakpoint${u.node?`: ${u.node}`:""}`,data:u.data})},onRunError:u=>{const m=u.data?.error||"The server could not resume this execution.",f=e();f.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:m,data:u.data}),f.stopExecution(),t({error:m})},onRunComplete:()=>e().stopExecution(),onError:u=>{const m=u.message||"Resume stream failed.",f=e();f.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:m,data:{action:"resume"}}),f.stopExecution(),t({error:m})},onDone:()=>{const u=e();u.executionContext.isExecuting&&!u.executionContext.isPaused&&u.stopExecution()}});t({activeAbortController:d})}catch(d){l(!0);const u=d instanceof Error?d.message:"Could not start the resume request.";t({error:u}),e().addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:u,data:{action:"resume"}})}},stopExecution:()=>t(r=>{const n={...r.executionContext,isExecuting:!1,isPaused:!1,endTime:new Date};r.activeAbortController&&r.activeAbortController.abort();const a=r.getExecutionContextKey(),o=new Map(r.executionContexts);o.set(a,n);const s=n.startTime?n.endTime.getTime()-n.startTime.getTime():0;return R.emit({type:"EXECUTION_COMPLETED",data:{threadId:r.selectedThread?.id||"unknown",finalState:n.currentState,duration:s}}),setTimeout(()=>{e().fitGraphToView()},500),{executionContext:n,executionContexts:o,activeAbortController:null,graphState:{...r.graphState,currentNode:void 0}}}),addExecutionLog:r=>t(n=>{const a={...r,id:`log_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:new Date},o={...n.executionContext,logs:[...n.executionContext.logs,a]},s=n.getExecutionContextKey(),i=new Map(n.executionContexts);return i.set(s,o),R.emit({type:"EXECUTION_LOG",data:a}),{executionContext:o,executionContexts:i}}),clearExecutionLogs:()=>t(r=>{const n={...r.executionContext,logs:[]},a=r.getExecutionContextKey(),o=new Map(r.executionContexts);return o.set(a,n),{executionContext:n,executionContexts:o}}),setGraphExecutionState:r=>t(n=>{const a={...n.executionContext,currentState:r},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),addBreakpoint:(r,n)=>t(a=>{if(a.executionContext.breakpoints.find(d=>d.nodeId===r))return a;const s={...a.executionContext,breakpoints:[...a.executionContext.breakpoints,{nodeId:r,enabled:!0,condition:n}]},i=a.getExecutionContextKey(),l=new Map(a.executionContexts);return l.set(i,s),{executionContext:s,executionContexts:l}}),removeBreakpoint:r=>t(n=>{const a={...n.executionContext,breakpoints:n.executionContext.breakpoints.filter(i=>i.nodeId!==r)},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),toggleBreakpoint:r=>t(n=>{const a={...n.executionContext,breakpoints:n.executionContext.breakpoints.map(i=>i.nodeId===r?{...i,enabled:!i.enabled}:i)},o=n.getExecutionContextKey(),s=new Map(n.executionContexts);return s.set(o,a),{executionContext:a,executionContexts:s}}),focusOnNode:r=>{console.log("Focus on node:",r)},fitGraphToView:()=>{console.log("Fit graph to view")},liveUpdateManager:R,subscribeLiveUpdates:(r,n)=>R.subscribe(r,n),subscribeAllLiveUpdates:r=>R.subscribeAll(r),emitLiveUpdate:r=>R.emit(r),addMessageToThreadLive:(r,n)=>{e().addMessageToThread(r,n)},updateThreadLive:(r,n)=>{e().updateThread(r,n)},setGraphStateLive:r=>{e().setGraphState(r)},focusOnNodeLive:r=>{e().focusOnNode(r),R.emit({type:"NODE_FOCUSED",data:{nodeId:r}})},startGlobalExecution:(r,n={},a)=>{const o=e(),s=o.selectedAgent?o.agentSchemas[o.selectedAgent.id]?.input_schema:void 0,i=s?.properties,d=!!(s&&(!i||Object.keys(i).length===0)&&s.type&&s.type!=="object")&&a!==void 0?a:void 0,u=d===void 0&&a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{},m=typeof d=="string"?d:d!==void 0?JSON.stringify(d):typeof a=="string"?a:tn(u)||(typeof n?.message=="string"?n.message:"");if((o.graphState?.nodes||[]).length===0&&console.info("No graph topology loaded; executing the selected agent directly."),o.clearExecutionLogs(),o.startExecution({...n,...u,...d!==void 0?{__root__:d}:{}}),r==="graph"&&o.selectedThread){const v={id:`msg-${Date.now()}-graph-execution`,role:"assistant",content:`🔄 **Graph Execution Started** + +Execution initiated from the graph view. You can monitor the progress in real-time.`,timestamp:new Date};o.addMessageToThread(o.selectedThread.id,v)}R.emit({type:"EXECUTION_STARTED",data:{threadId:o.selectedThread?.id||"unknown",assistantId:o.selectedAgent?.id||"unknown",initialState:{...n,...u,...d!==void 0?{__root__:d}:{},source:r,userMessage:m}}}),(async()=>{try{const v=e(),{config:p,selectedThread:y,selectedAgent:g}=v;if(!g)throw new Error("No agent selected");if(!o.isConnected||!p.apiUrl){if(console.warn("Cannot execute without an active Agentomatic connection."),v.stopExecution(),v.selectedThread){const T={id:`msg-${Date.now()}-connection-error`,role:"assistant",content:`⚠️ **No active server connection** + +Connect to an Agentomatic server before executing an agent.`,timestamp:new Date};v.addMessageToThread(v.selectedThread.id,T)}return}let C=y?.id;if(!C){if(!P)throw new Error("The Studio API client is unavailable; cannot create a durable conversation.");const T=await P.createThread(g.id,"studio-user",r==="graph"?"Graph Execution":"New Chat"),j=Ve(T,g.id);C=j.id,v.addThread(j),v.setSelectedThread(j)}if(v.addExecutionLog({nodeId:"system",nodeName:"System",type:"info",message:"Starting Agentomatic execution",data:{agentId:g.id,threadId:C,input:d!==void 0?d:u,query:m}}),P){console.log("📡 Using SSE streaming via Studio API...");const T=P.getStreamUrl(g.id),j=P.getHeaders(),N=v.executionContext.breakpoints.filter(b=>b.enabled).map(b=>b.nodeId),A={};let I="";const{breakpoints:q,checkpoint_id:E,thread_id:L,user_id:D,...M}=u,K=en({schemaFields:M,rootInput:d,input:a,userMessage:m,threadId:C,breakpoints:N,checkpointId:n.checkpoint_id}),ne=ft.connect(T,K,j,{onRunStart:b=>{console.log("🚀 Run started:",b.run_id);const w=e();if(b.data?.thread_id&&!w.selectedThread){const k=b.data.thread_id;if(!w.threads.find(O=>O.id===k)){const O={id:k,name:`Thread ${k.slice(-8)}`,agentId:g.id,createdAt:new Date,updatedAt:new Date,metadata:{},messages:[]};w.addThread(O),w.setSelectedThread(O)}}w.addExecutionLog({nodeId:"system",nodeName:"System",type:"info",message:`Run started: ${b.run_id}`,data:b.data})},onNodeStart:b=>{console.log("▶️ Node started:",b.node);const w=e(),k=le(b.node);k&&(w.setGraphState({...w.graphState,currentNode:k,executionPath:[...w.graphState.executionPath,k]}),w.addExecutionLog({nodeId:k,nodeName:k,type:"input",message:`Starting node: ${k}`,data:b.data}),R.emit({type:"EXECUTION_STEP",data:{nodeId:k,nodeName:k,progress:0}}))},onNodeEnd:b=>{console.log("✅ Node ended:",b.node);const w=e(),k=le(b.node);k&&(A[k]=b.data,w.addExecutionLog({nodeId:k,nodeName:k,type:"output",message:`Completed node: ${k}`,data:{...b.data,duration_ms:b.duration_ms,intermediate_results:{...A}},duration:b.duration_ms||void 0}),w.setGraphExecutionState({...w.executionContext.currentState,intermediate_results:A,[k]:b.data}))},onStateUpdate:b=>{const w=e();w.setGraphExecutionState({...w.executionContext.currentState,...b.data})},onMessageChunk:b=>{const w=b.data?.content||"";w&&(I+=w),R.emit({type:"STREAMING_UPDATE",data:{messageId:`stream-${b.run_id}`,content:I,isComplete:!1}})},onRunComplete:b=>{console.log("🏁 Run completed:",b.run_id);const w=e();if(w.stopExecution(),w.selectedThread){const k=sn(w.executionContext.logs,I)||`✅ **Run completed** + +The deployment returned structured state but no chat response. Inspect the execution logs or Graph State for the exact output.`,S={id:`msg-${Date.now()}-result`,role:"assistant",content:k,timestamp:new Date};w.addMessageToThread(w.selectedThread.id,S)}R.emit({type:"EXECUTION_COMPLETED",data:{threadId:w.selectedThread?.id||"unknown",finalState:{...w.executionContext.currentState,intermediate_results:A},duration:w.executionContext.startTime?Date.now()-w.executionContext.startTime.getTime():0}})},onRunError:b=>{console.error("❌ Run error:",b.data);const w=e();if(w.stopExecution(),t({isLoading:!1,error:b.data?.error||"Unknown error"}),w.selectedThread){const k={id:`msg-${Date.now()}-error`,role:"assistant",content:`❌ **Execution Error** + +${b.data?.error||"Unknown error"}`,timestamp:new Date};w.addMessageToThread(w.selectedThread.id,k)}R.emit({type:"EXECUTION_COMPLETED",data:{threadId:w.selectedThread?.id||"unknown",finalState:w.executionContext.currentState,duration:0}})},onBreakpointHit:b=>{const w=e();w.pauseExecution(),b.node&&w.addInterrupt({id:`bp-${Date.now()}`,agentId:g.id,threadId:C||"",toolName:le(b.node)||b.node,toolArgs:b.data||{},reason:`Breakpoint hit at ${b.node}`,status:"pending",timestamp:new Date})},onError:b=>{console.error("❌ SSE error:",b);const w=e(),k=b instanceof Error?b.message:String(b);w.stopExecution(),t({isLoading:!1,error:k}),w.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:`SSE connection failed: ${k}`,data:{error:k}}),w.selectedThread&&w.addMessageToThread(w.selectedThread.id,{id:`msg-${Date.now()}-sse-error`,role:"assistant",content:`❌ **Connection Error** + +${k} + +The agent may not be reachable (check name/slug, server logs, and /studio/agents).`,timestamp:new Date}),R.emit({type:"EXECUTION_COMPLETED",data:{threadId:w.selectedThread?.id||"unknown",finalState:w.executionContext.currentState,duration:0}})},onDone:()=>{console.log("📡 SSE stream complete");const b=e();b.executionContext.isExecuting&&!b.executionContext.isPaused&&b.stopExecution(),t({isLoading:!1})}});t({activeAbortController:ne});return}throw new Error("Studio API client not initialized. Cannot execute agent.")}catch(v){console.error("❌ Agentomatic execution error:",v);const p=e();if(p.stopExecution(),p.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:`Execution failed: ${v instanceof Error?v.message:"Unknown error"}`,data:{error:v instanceof Error?v.message:String(v)}}),p.selectedThread){const y={id:`msg-${Date.now()}-error`,role:"assistant",content:`❌ **Execution Error** + +Failed to execute: ${v instanceof Error?v.message:"Unknown error"}`,timestamp:new Date};p.addMessageToThread(p.selectedThread.id,y)}}})().catch(v=>{console.error("Failed to execute Agentomatic agent:",v),e().stopExecution()})},addInterrupt:r=>t(n=>(R.emit({type:"INTERRUPT_RECEIVED",data:r}),{activeInterrupts:[...n.activeInterrupts,r]})),resolveInterrupt:(r,n)=>t(a=>(R.emit({type:"INTERRUPT_RESOLVED",data:{interruptId:r,resolution:n}}),{activeInterrupts:a.activeInterrupts.map(o=>o.id===r?{...o,status:n==="approved"?"approved":"rejected",resolvedAt:new Date}:o)})),clearInterrupts:()=>t({activeInterrupts:[]}),addSubAgentResult:r=>t(n=>(R.emit({type:"SUB_AGENT_COMPLETED",data:r}),{subAgentResults:[...n.subAgentResults,r]})),clearSubAgentResults:()=>t({subAgentResults:[]}),reset:()=>t({...We,selectedThread:void 0,selectedAgent:void 0,selectedAssistant:void 0,threads:[],agents:[],assistants:[],runs:[],currentRun:void 0,executionContext:Be,executionContexts:new Map,activeInterrupts:[],subAgentResults:[],agentSchemas:{},schemasLoading:!1,isStreaming:!1,streamingMessage:"",activeAbortController:null})}),{name:"studio-store"})),Ro=(t,e,r=[])=>{const n=h.useRef(e);n.current=e,h.useEffect(()=>R.subscribe(t,o=>{n.current(o)}),[t,...r])},Do=(t,e=[])=>{const r=h.useRef(t);r.current=t,h.useEffect(()=>R.subscribeAll(a=>{r.current(a)}),e)};function cn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"}))}const dn=h.forwardRef(cn);function ln({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"}))}const un=h.forwardRef(ln);function mn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 0 1-.825-.242m9.345-8.334a2.126 2.126 0 0 0-.476-.095 48.64 48.64 0 0 0-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0 0 11.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155"}))}const fn=h.forwardRef(mn);function pn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"}))}const pt=h.forwardRef(pn);function hn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m19.5 8.25-7.5 7.5-7.5-7.5"}))}const gn=h.forwardRef(hn);function yn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 0v3.75m-16.5-3.75v3.75m16.5 0v3.75C20.25 16.153 16.556 18 12 18s-8.25-1.847-8.25-4.125v-3.75m16.5 0c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125"}))}const xn=h.forwardRef(yn);function bn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const vn=h.forwardRef(bn);function wn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4.5 12a7.5 7.5 0 0 0 15 0m-15 0a7.5 7.5 0 1 1 15 0m-15 0H3m16.5 0H21m-1.5 0H12m-8.457 3.077 1.41-.513m14.095-5.13 1.41-.513M5.106 17.785l1.15-.964m11.49-9.642 1.149-.964M7.501 19.795l.75-1.3m7.5-12.99.75-1.3m-6.063 16.658.26-1.477m2.605-14.772.26-1.477m0 17.726-.26-1.477M10.698 4.614l-.26-1.477M16.5 19.794l-.75-1.299M7.5 4.205 12 12m6.894 5.785-1.149-.964M6.256 7.178l-1.15-.964m15.352 8.864-1.41-.513M4.954 9.435l-1.41-.514M12.002 12l-3.75 6.495"}))}const pe=h.forwardRef(wn);function Cn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m6.75 7.5 3 2.25-3 2.25m4.5 0h3m-9 8.25h13.5A2.25 2.25 0 0 0 21 18V6a2.25 2.25 0 0 0-2.25-2.25H5.25A2.25 2.25 0 0 0 3 6v12a2.25 2.25 0 0 0 2.25 2.25Z"}))}const Fe=h.forwardRef(Cn);function Sn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418"}))}const En=h.forwardRef(Sn);function kn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z"}))}const Tn=h.forwardRef(kn);function An({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4.5v15m7.5-7.5h-15"}))}const jn=h.forwardRef(An);function _n({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 0 1 0 3.75H5.625a1.875 1.875 0 0 1 0-3.75Z"}))}const Nn=h.forwardRef(_n);function $n({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"}))}const On=h.forwardRef($n);function Rn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"}))}const Dn=h.forwardRef(Rn);function Pn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"}))}const Mn=h.forwardRef(Pn);function In({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const Ln=h.forwardRef(In),Un=()=>{const{assistants:t,selectedAssistant:e,setSelectedAssistant:r,currentView:n,setCurrentView:a,darkMode:o,setDarkMode:s,sidebarCollapsed:i,setSidebarCollapsed:l,config:d,fetchGraphData:u,refreshThreads:m,connectionStatus:f,retryAttempts:x,maxRetryAttempts:v,attemptReconnection:p}=me(),[y,g]=h.useState(!1),C=h.useRef(null),T=h.useRef(null),[j,N]=h.useState({top:0,left:0,width:0});h.useEffect(()=>{const E=L=>{C.current&&!C.current.contains(L.target)&&T.current&&!T.current.contains(L.target)&&g(!1)};if(y)return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[y]),h.useEffect(()=>{if(y&&T.current){const E=()=>{const M=T.current.getBoundingClientRect();N({top:M.bottom+8,left:M.left,width:M.width})};E();const L=()=>E(),D=()=>E();return window.addEventListener("scroll",L,!0),window.addEventListener("resize",D),()=>{window.removeEventListener("scroll",L,!0),window.removeEventListener("resize",D)}}},[y]);const A=async E=>{r(E),g(!1);try{await u(E.id),await m(E.id)}catch(L){console.error("Failed to fetch graph data:",L)}},I=E=>{switch(E){case"langgraph":return o?"bg-emerald-900 text-emerald-300":"bg-emerald-100 text-emerald-700";case"deepagent":return o?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-700";case"langchain":return o?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700";default:return o?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}},q=[{key:"graph",label:"Graph",icon:Fe},{key:"chat",label:"Chat",icon:fn},{key:"debug",label:"Debug",icon:pe},{key:"pipelines",label:"Pipelines",icon:Fe},{key:"builder",label:"Builder",icon:On},{key:"plugins",label:"Plugins",icon:pe},{key:"ingestion",label:"Ingestors",icon:Fe},{key:"tasks",label:"Tasks",icon:Nn},{key:"control",label:"Control",icon:dn},{key:"endpoints",label:"Endpoints",icon:En},{key:"connections",label:"Connections",icon:xn}];return c.jsxs("header",{className:`flex min-h-16 items-center justify-between gap-2 px-3 py-2 sm:px-6 border-b backdrop-blur-sm transition-colors duration-300 ${o?"bg-gray-800/95 border-gray-700 text-white":"bg-white/95 border-gray-200 text-gray-900"}`,children:[c.jsxs("div",{className:"flex min-w-0 items-center space-x-2 sm:space-x-4",children:[c.jsx("button",{onClick:()=>l(!i),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-gray-300":"hover:bg-gray-100 text-gray-600"}`,title:i?"Show Sidebar":"Hide Sidebar",children:i?c.jsx(un,{className:"w-5 h-5"}):c.jsx(Ln,{className:"w-5 h-5"})}),c.jsxs("div",{className:"flex items-center space-x-2 sm:space-x-3",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-violet-600",children:c.jsx("span",{className:"text-white font-bold text-sm",children:"AS"})}),c.jsxs("div",{className:"hidden sm:block",children:[c.jsx("h1",{className:"text-lg font-semibold",children:"Agentomatic Studio"}),c.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:f==="connected"?"Connected":"Reconnecting…"})]})]}),c.jsx("nav",{className:`hidden 2xl:flex min-w-0 items-center space-x-1 rounded-xl p-1 ml-3 xl:ml-6 overflow-x-auto ${o?"bg-gray-700":"bg-gray-100"}`,children:q.map(({key:E,label:L,icon:D})=>c.jsxs("button",{onClick:()=>a(E),className:`flex shrink-0 items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${n===E?o?"bg-blue-600 text-white shadow-lg transform scale-105":"bg-white text-blue-600 shadow-md transform scale-105":o?"text-gray-300 hover:text-white hover:bg-gray-600":"text-gray-600 hover:text-gray-900 hover:bg-white/50"}`,children:[c.jsx(D,{className:"w-4 h-4 mr-2"}),L]},E))}),c.jsx("select",{value:n,onChange:E=>a(E.target.value),"aria-label":"Select Studio view",className:`max-w-28 rounded-lg border px-2 py-2 text-sm font-medium sm:max-w-36 md:max-w-44 2xl:hidden ${o?"border-gray-600 bg-gray-700 text-white":"border-gray-300 bg-white text-gray-900"}`,children:q.map(({key:E,label:L})=>c.jsx("option",{value:E,children:L},E))})]}),c.jsx("div",{className:"flex flex-1 justify-end sm:justify-center",children:c.jsxs("div",{className:"relative",ref:C,children:[c.jsxs("button",{onClick:()=>g(!y),className:`flex max-w-[13rem] items-center space-x-2 px-2 py-2 sm:max-w-none sm:space-x-3 sm:px-4 rounded-xl border transition-all duration-200 ${o?"bg-gray-700 border-gray-600 text-white hover:bg-gray-600":"bg-white border-gray-300 text-gray-900 hover:bg-gray-50"}`,ref:T,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${o?"bg-blue-600":"bg-blue-100"}`,children:c.jsx(pe,{className:`w-4 h-4 ${o?"text-white":"text-blue-600"}`})}),c.jsxs("div",{className:"min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx("span",{className:"truncate text-sm font-medium",children:e?.name||"Select Agent"}),e?.metadata?.framework&&c.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full font-medium ${I(e.metadata.framework)}`,children:e.metadata.framework})]}),c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:e?.description||"No agent selected"})]}),c.jsx(gn,{className:`w-4 h-4 transition-transform ${y?"rotate-180":""}`})]}),y&&Pt.createPortal(c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fixed inset-0 z-[999998] bg-black/10",onClick:()=>g(!1)}),c.jsx("div",{ref:C,className:`fixed rounded-xl border shadow-2xl z-[999999] ${o?"bg-gray-800 border-gray-600":"bg-white border-gray-200"}`,style:{top:j.top,left:j.left,width:Math.max(j.width,320),maxHeight:"400px"},children:c.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:t.length===0?c.jsxs("div",{className:`p-4 text-center ${o?"text-gray-400":"text-gray-500"}`,children:[c.jsx(pe,{className:`w-8 h-8 mx-auto mb-2 ${o?"text-gray-600":"text-gray-300"}`}),c.jsx("p",{className:"text-sm",children:"No agents available"}),c.jsx("p",{className:"text-xs mt-1",children:"Check your server connection"})]}):t.map(E=>c.jsxs("button",{onClick:()=>A(E),className:`w-full flex items-center space-x-3 p-3 rounded-lg transition-colors ${e?.id===E.id?o?"bg-blue-900 border border-blue-700":"bg-blue-50 border border-blue-200":o?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${e?.id===E.id?"bg-blue-600":o?"bg-gray-600":"bg-gray-200"}`,children:c.jsx(pe,{className:`w-4 h-4 ${e?.id===E.id?"text-white":o?"text-gray-300":"text-gray-600"}`})}),c.jsxs("div",{className:"flex-1 text-left",children:[c.jsx("div",{className:`text-sm font-medium ${o?"text-white":"text-gray-900"}`,children:E.name}),E.description&&c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:E.description}),c.jsxs("div",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:["Graph: ",E.graph_id]})]}),e?.id===E.id&&c.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full"})]},E.id))})})]}),document.body)]})}),c.jsxs("div",{className:"flex items-center space-x-1.5 sm:space-x-3",children:[c.jsxs("div",{className:"hidden items-center space-x-2 xl:flex",children:[c.jsx("div",{className:`w-2 h-2 rounded-full ${f==="connected"?"bg-green-500 animate-pulse":f==="reconnecting"?"bg-yellow-500 animate-spin":f==="failed"?"bg-red-500":"bg-gray-500"}`}),c.jsx("span",{className:`text-sm ${o?"text-gray-300":"text-gray-600"}`,children:f==="connected"?c.jsx("span",{title:d.apiUrl,children:d.apiUrl.replace(/^https?:\/\//,"").slice(0,25)}):f==="reconnecting"?`Reconnecting (${x}/${v})`:f==="failed"?"Connection Failed":"Disconnected"}),(f==="disconnected"||f==="failed")&&c.jsx("button",{onClick:p,className:`px-2 py-1 text-xs rounded transition-colors ${o?"bg-blue-600 text-white hover:bg-blue-700":"bg-blue-500 text-white hover:bg-blue-600"}`,title:"Retry Connection",children:"Retry"})]}),c.jsx("button",{onClick:()=>s(!o),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-yellow-400":"hover:bg-gray-100 text-gray-600"}`,title:o?"Switch to Light Mode":"Switch to Dark Mode",children:o?c.jsx(Dn,{className:"w-5 h-5"}):c.jsx(Tn,{className:"w-5 h-5"})}),c.jsx("div",{className:`hidden text-xs px-2 py-1 rounded 2xl:block ${o?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-500"}`,children:"⌘1-9 to switch views"})]})]})};function ce(t){if(t===null||t===!0||t===!1)return NaN;var e=Number(t);return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}function W(t,e){if(e.length1?"s":"")+" required, but only "+e.length+" present")}function X(t){W(1,arguments);var e=Object.prototype.toString.call(t);return t instanceof Date||Et(t)==="object"&&e==="[object Date]"?new Date(t.getTime()):typeof t=="number"||e==="[object Number]"?new Date(t):((typeof t=="string"||e==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function qn(t,e){W(2,arguments);var r=X(t).getTime(),n=ce(e);return new Date(r+n)}var Vn={};function Oe(){return Vn}function Wn(t){var e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),t.getTime()-e.getTime()}function Bn(t){return W(1,arguments),t instanceof Date||Et(t)==="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Fn(t){if(W(1,arguments),!Bn(t)&&typeof t!="number")return!1;var e=X(t);return!isNaN(Number(e))}function zn(t,e){W(2,arguments);var r=ce(e);return qn(t,-r)}var Yn=864e5;function Hn(t){W(1,arguments);var e=X(t),r=e.getTime();e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);var n=e.getTime(),a=r-n;return Math.floor(a/Yn)+1}function je(t){W(1,arguments);var e=1,r=X(t),n=r.getUTCDay(),a=(n=a.getTime()?r+1:e.getTime()>=s.getTime()?r:r-1}function Gn(t){W(1,arguments);var e=$t(t),r=new Date(0);r.setUTCFullYear(e,0,4),r.setUTCHours(0,0,0,0);var n=je(r);return n}var Kn=6048e5;function Jn(t){W(1,arguments);var e=X(t),r=je(e).getTime()-Gn(e).getTime();return Math.round(r/Kn)+1}function _e(t,e){var r,n,a,o,s,i,l,d;W(1,arguments);var u=Oe(),m=ce((r=(n=(a=(o=e?.weekStartsOn)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.weekStartsOn)!==null&&a!==void 0?a:u.weekStartsOn)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.weekStartsOn)!==null&&r!==void 0?r:0);if(!(m>=0&&m<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var f=X(t),x=f.getUTCDay(),v=(x=1&&x<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var v=new Date(0);v.setUTCFullYear(m+1,0,x),v.setUTCHours(0,0,0,0);var p=_e(v,e),y=new Date(0);y.setUTCFullYear(m,0,x),y.setUTCHours(0,0,0,0);var g=_e(y,e);return u.getTime()>=p.getTime()?m+1:u.getTime()>=g.getTime()?m:m-1}function Xn(t,e){var r,n,a,o,s,i,l,d;W(1,arguments);var u=Oe(),m=ce((r=(n=(a=(o=e?.firstWeekContainsDate)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.firstWeekContainsDate)!==null&&a!==void 0?a:u.firstWeekContainsDate)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&r!==void 0?r:1),f=Ot(t,e),x=new Date(0);x.setUTCFullYear(f,0,m),x.setUTCHours(0,0,0,0);var v=_e(x,e);return v}var Qn=6048e5;function Zn(t,e){W(1,arguments);var r=X(t),n=_e(r,e).getTime()-Xn(r,e).getTime();return Math.round(n/Qn)+1}function $(t,e){for(var r=t<0?"-":"",n=Math.abs(t).toString();n.length0?n:1-n;return $(r==="yy"?a%100:a,r.length)},M:function(e,r){var n=e.getUTCMonth();return r==="M"?String(n+1):$(n+1,2)},d:function(e,r){return $(e.getUTCDate(),r.length)},a:function(e,r){var n=e.getUTCHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h:function(e,r){return $(e.getUTCHours()%12||12,r.length)},H:function(e,r){return $(e.getUTCHours(),r.length)},m:function(e,r){return $(e.getUTCMinutes(),r.length)},s:function(e,r){return $(e.getUTCSeconds(),r.length)},S:function(e,r){var n=r.length,a=e.getUTCMilliseconds(),o=Math.floor(a*Math.pow(10,n-3));return $(o,r.length)}},ue={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},ea={G:function(e,r,n){var a=e.getUTCFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});default:return n.era(a,{width:"wide"})}},y:function(e,r,n){if(r==="yo"){var a=e.getUTCFullYear(),o=a>0?a:1-a;return n.ordinalNumber(o,{unit:"year"})}return ee.y(e,r)},Y:function(e,r,n,a){var o=Ot(e,a),s=o>0?o:1-o;if(r==="YY"){var i=s%100;return $(i,2)}return r==="Yo"?n.ordinalNumber(s,{unit:"year"}):$(s,r.length)},R:function(e,r){var n=$t(e);return $(n,r.length)},u:function(e,r){var n=e.getUTCFullYear();return $(n,r.length)},Q:function(e,r,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"Q":return String(a);case"QQ":return $(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(e,r,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"q":return String(a);case"qq":return $(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(e,r,n){var a=e.getUTCMonth();switch(r){case"M":case"MM":return ee.M(e,r);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(e,r,n){var a=e.getUTCMonth();switch(r){case"L":return String(a+1);case"LL":return $(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(e,r,n,a){var o=Zn(e,a);return r==="wo"?n.ordinalNumber(o,{unit:"week"}):$(o,r.length)},I:function(e,r,n){var a=Jn(e);return r==="Io"?n.ordinalNumber(a,{unit:"week"}):$(a,r.length)},d:function(e,r,n){return r==="do"?n.ordinalNumber(e.getUTCDate(),{unit:"date"}):ee.d(e,r)},D:function(e,r,n){var a=Hn(e);return r==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):$(a,r.length)},E:function(e,r,n){var a=e.getUTCDay();switch(r){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(e,r,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(r){case"e":return String(s);case"ee":return $(s,2);case"eo":return n.ordinalNumber(s,{unit:"day"});case"eee":return n.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(o,{width:"short",context:"formatting"});default:return n.day(o,{width:"wide",context:"formatting"})}},c:function(e,r,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(r){case"c":return String(s);case"cc":return $(s,r.length);case"co":return n.ordinalNumber(s,{unit:"day"});case"ccc":return n.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(o,{width:"narrow",context:"standalone"});case"cccccc":return n.day(o,{width:"short",context:"standalone"});default:return n.day(o,{width:"wide",context:"standalone"})}},i:function(e,r,n){var a=e.getUTCDay(),o=a===0?7:a;switch(r){case"i":return String(o);case"ii":return $(o,r.length);case"io":return n.ordinalNumber(o,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(e,r,n){var a=e.getUTCHours(),o=a/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,r,n){var a=e.getUTCHours(),o;switch(a===12?o=ue.noon:a===0?o=ue.midnight:o=a/12>=1?"pm":"am",r){case"b":case"bb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,r,n){var a=e.getUTCHours(),o;switch(a>=17?o=ue.evening:a>=12?o=ue.afternoon:a>=4?o=ue.morning:o=ue.night,r){case"B":case"BB":case"BBB":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,r,n){if(r==="ho"){var a=e.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return ee.h(e,r)},H:function(e,r,n){return r==="Ho"?n.ordinalNumber(e.getUTCHours(),{unit:"hour"}):ee.H(e,r)},K:function(e,r,n){var a=e.getUTCHours()%12;return r==="Ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,r.length)},k:function(e,r,n){var a=e.getUTCHours();return a===0&&(a=24),r==="ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,r.length)},m:function(e,r,n){return r==="mo"?n.ordinalNumber(e.getUTCMinutes(),{unit:"minute"}):ee.m(e,r)},s:function(e,r,n){return r==="so"?n.ordinalNumber(e.getUTCSeconds(),{unit:"second"}):ee.s(e,r)},S:function(e,r){return ee.S(e,r)},X:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();if(s===0)return"Z";switch(r){case"X":return gt(s);case"XXXX":case"XX":return se(s);default:return se(s,":")}},x:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"x":return gt(s);case"xxxx":case"xx":return se(s);default:return se(s,":")}},O:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},z:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},t:function(e,r,n,a){var o=a._originalDate||e,s=Math.floor(o.getTime()/1e3);return $(s,r.length)},T:function(e,r,n,a){var o=a._originalDate||e,s=o.getTime();return $(s,r.length)}};function ht(t,e){var r=t>0?"-":"+",n=Math.abs(t),a=Math.floor(n/60),o=n%60;if(o===0)return r+String(a);var s=e;return r+String(a)+s+$(o,2)}function gt(t,e){if(t%60===0){var r=t>0?"-":"+";return r+$(Math.abs(t)/60,2)}return se(t,e)}function se(t,e){var r=e||"",n=t>0?"-":"+",a=Math.abs(t),o=$(Math.floor(a/60),2),s=$(a%60,2);return n+o+r+s}var yt=function(e,r){switch(e){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});default:return r.date({width:"full"})}},Rt=function(e,r){switch(e){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});default:return r.time({width:"full"})}},ta=function(e,r){var n=e.match(/(P+)(p+)?/)||[],a=n[1],o=n[2];if(!o)return yt(e,r);var s;switch(a){case"P":s=r.dateTime({width:"short"});break;case"PP":s=r.dateTime({width:"medium"});break;case"PPP":s=r.dateTime({width:"long"});break;default:s=r.dateTime({width:"full"});break}return s.replace("{{date}}",yt(a,r)).replace("{{time}}",Rt(o,r))},ra={p:Rt,P:ta},na=["D","DD"],aa=["YY","YYYY"];function oa(t){return na.indexOf(t)!==-1}function sa(t){return aa.indexOf(t)!==-1}function xt(t,e,r){if(t==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var ia={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},ca=function(e,r,n){var a,o=ia[e];return typeof o=="string"?a=o:r===1?a=o.one:a=o.other.replace("{{count}}",r.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a};function ze(t){return function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=e.width?String(e.width):t.defaultWidth,n=t.formats[r]||t.formats[t.defaultWidth];return n}}var da={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},la={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},ua={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ma={date:ze({formats:da,defaultWidth:"full"}),time:ze({formats:la,defaultWidth:"full"}),dateTime:ze({formats:ua,defaultWidth:"full"})},fa={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},pa=function(e,r,n,a){return fa[e]};function he(t){return function(e,r){var n=r!=null&&r.context?String(r.context):"standalone",a;if(n==="formatting"&&t.formattingValues){var o=t.defaultFormattingWidth||t.defaultWidth,s=r!=null&&r.width?String(r.width):o;a=t.formattingValues[s]||t.formattingValues[o]}else{var i=t.defaultWidth,l=r!=null&&r.width?String(r.width):t.defaultWidth;a=t.values[l]||t.values[i]}var d=t.argumentCallback?t.argumentCallback(e):e;return a[d]}}var ha={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ga={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},ya={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},xa={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},ba={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},va={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},wa=function(e,r){var n=Number(e),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},Ca={ordinalNumber:wa,era:he({values:ha,defaultWidth:"wide"}),quarter:he({values:ga,defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:he({values:ya,defaultWidth:"wide"}),day:he({values:xa,defaultWidth:"wide"}),dayPeriod:he({values:ba,defaultWidth:"wide",formattingValues:va,defaultFormattingWidth:"wide"})};function ge(t){return function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.width,a=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],o=e.match(a);if(!o)return null;var s=o[0],i=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],l=Array.isArray(i)?Ea(i,function(m){return m.test(s)}):Sa(i,function(m){return m.test(s)}),d;d=t.valueCallback?t.valueCallback(l):l,d=r.valueCallback?r.valueCallback(d):d;var u=e.slice(s.length);return{value:d,rest:u}}}function Sa(t,e){for(var r in t)if(t.hasOwnProperty(r)&&e(t[r]))return r}function Ea(t,e){for(var r=0;r1&&arguments[1]!==void 0?arguments[1]:{},n=e.match(t.matchPattern);if(!n)return null;var a=n[0],o=e.match(t.parsePattern);if(!o)return null;var s=t.valueCallback?t.valueCallback(o[0]):o[0];s=r.valueCallback?r.valueCallback(s):s;var i=e.slice(a.length);return{value:s,rest:i}}}var Ta=/^(\d+)(th|st|nd|rd)?/i,Aa=/\d+/i,ja={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},_a={any:[/^b/i,/^(a|c)/i]},Na={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},$a={any:[/1/i,/2/i,/3/i,/4/i]},Oa={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Ra={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Da={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Pa={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Ma={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Ia={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},La={ordinalNumber:ka({matchPattern:Ta,parsePattern:Aa,valueCallback:function(e){return parseInt(e,10)}}),era:ge({matchPatterns:ja,defaultMatchWidth:"wide",parsePatterns:_a,defaultParseWidth:"any"}),quarter:ge({matchPatterns:Na,defaultMatchWidth:"wide",parsePatterns:$a,defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:ge({matchPatterns:Oa,defaultMatchWidth:"wide",parsePatterns:Ra,defaultParseWidth:"any"}),day:ge({matchPatterns:Da,defaultMatchWidth:"wide",parsePatterns:Pa,defaultParseWidth:"any"}),dayPeriod:ge({matchPatterns:Ma,defaultMatchWidth:"any",parsePatterns:Ia,defaultParseWidth:"any"})},Ua={code:"en-US",formatDistance:ca,formatLong:ma,formatRelative:pa,localize:Ca,match:La,options:{weekStartsOn:0,firstWeekContainsDate:1}},qa=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Va=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Wa=/^'([^]*?)'?$/,Ba=/''/g,Fa=/[a-zA-Z]/;function za(t,e,r){var n,a,o,s,i,l,d,u,m,f,x,v,p,y;W(2,arguments);var g=String(e),C=Oe(),T=(n=(a=void 0)!==null&&a!==void 0?a:C.locale)!==null&&n!==void 0?n:Ua,j=ce((o=(s=(i=(l=void 0)!==null&&l!==void 0?l:void 0)!==null&&i!==void 0?i:C.firstWeekContainsDate)!==null&&s!==void 0?s:(d=C.locale)===null||d===void 0||(u=d.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&o!==void 0?o:1);if(!(j>=1&&j<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var N=ce((m=(f=(x=(v=void 0)!==null&&v!==void 0?v:void 0)!==null&&x!==void 0?x:C.weekStartsOn)!==null&&f!==void 0?f:(p=C.locale)===null||p===void 0||(y=p.options)===null||y===void 0?void 0:y.weekStartsOn)!==null&&m!==void 0?m:0);if(!(N>=0&&N<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!T.localize)throw new RangeError("locale must contain localize property");if(!T.formatLong)throw new RangeError("locale must contain formatLong property");var A=X(t);if(!Fn(A))throw new RangeError("Invalid time value");var I=Wn(A),q=zn(A,I),E={firstWeekContainsDate:j,weekStartsOn:N,locale:T,_originalDate:A},L=g.match(Va).map(function(D){var M=D[0];if(M==="p"||M==="P"){var K=ra[M];return K(D,T.formatLong)}return D}).join("").match(qa).map(function(D){if(D==="''")return"'";var M=D[0];if(M==="'")return Ya(D);var K=ea[M];if(K)return sa(D)&&xt(D,e,String(t)),oa(D)&&xt(D,e,String(t)),K(q,D,T.localize,E);if(M.match(Fa))throw new RangeError("Format string contains an unescaped latin alphabet character `"+M+"`");return D}).join("");return L}function Ya(t){var e=t.match(Wa);return e?e[1].replace(Ba,"'"):t}const Ha=()=>{const{threads:t,selectedThread:e,setSelectedThread:r,createPersistentThread:n,deletePersistentThread:a,hydrateThreadMessages:o,selectedAssistant:s,darkMode:i}=me(),[l,d]=h.useState(null),[u,m]=h.useState(null),f=async()=>{if(!s?.id){m("Select a live agent before creating a thread.");return}d("new"),m(null);try{await n(s.id,`Thread ${t.length+1}`)}catch(p){m(p?.message||"Could not create a durable thread.")}finally{d(null)}},x=async p=>{const y=p.agentId||s?.id;d(`load:${p.id}`),m(null);try{const g=y?await o(p.id,y):void 0;r(g||p)}catch(g){m(g?.message||"Could not load this thread’s durable history."),r(p)}finally{d(null)}},v=async(p,y)=>{y.stopPropagation(),d(`delete:${p.id}`),m(null);try{await a(p)}catch(g){m(g?.message||"Could not delete the durable thread.")}finally{d(null)}};return c.jsxs("div",{className:`h-full flex flex-col ${i?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} border-r transition-colors duration-300`,children:[c.jsxs("div",{className:`p-4 border-b ${i?"border-gray-700":"border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(pt,{className:`w-5 h-5 ${i?"text-blue-400":"text-blue-600"}`}),c.jsx("h2",{className:`text-lg font-semibold ${i?"text-white":"text-gray-900"}`,children:"Threads"})]}),c.jsx("div",{className:`px-2 py-1 rounded-full text-xs font-medium ${i?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:t.length})]}),c.jsxs("button",{onClick:()=>{f()},disabled:l!==null,className:`w-full flex items-center justify-center px-4 py-3 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md ${i?"bg-blue-600 hover:bg-blue-700 text-white hover:scale-105":"bg-blue-600 text-white hover:bg-blue-700 hover:scale-105"}`,children:[c.jsx(jn,{className:"w-4 h-4 mr-2"}),l==="new"?"Creating…":"New Thread"]})]}),u&&c.jsx("p",{role:"alert",className:`mx-4 mb-3 rounded-md border p-2 text-xs ${i?"border-red-800 bg-red-950/40 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:u}),c.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:t.length===0?c.jsxs("div",{className:`p-6 text-center ${i?"text-gray-400":"text-gray-500"}`,children:[c.jsx("div",{className:`w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center ${i?"bg-gray-700":"bg-gray-100"}`,children:c.jsx(pt,{className:`w-8 h-8 ${i?"text-gray-500":"text-gray-400"}`})}),c.jsx("h3",{className:`text-sm font-medium mb-2 ${i?"text-gray-300":"text-gray-700"}`,children:"No threads yet"}),c.jsx("p",{className:"text-xs leading-relaxed",children:"Create your first thread to start a conversation with your agent"})]}):c.jsx("div",{className:"p-3 space-y-2",children:t.map(p=>c.jsxs("div",{onClick:()=>{x(p)},className:`group relative p-4 rounded-xl cursor-pointer transition-all duration-200 ${e?.id===p.id?i?"bg-blue-900/50 border-2 border-blue-600 shadow-lg":"bg-blue-50 border-2 border-blue-200 shadow-md":i?"hover:bg-gray-700 border-2 border-transparent hover:border-gray-600":"hover:bg-gray-50 border-2 border-transparent hover:border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-start justify-between",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center space-x-2 mb-2",children:[c.jsx("h3",{className:`text-sm font-semibold truncate ${e?.id===p.id?i?"text-blue-300":"text-blue-700":i?"text-white":"text-gray-900"}`,children:p.name}),p.messages.length>0&&c.jsx("span",{className:`px-2 py-0.5 text-xs rounded-full font-medium ${e?.id===p.id?i?"bg-blue-800 text-blue-200":"bg-blue-100 text-blue-700":i?"bg-gray-600 text-gray-300":"bg-gray-200 text-gray-600"}`,children:p.messages.length})]}),p.messages.length>0?c.jsx("p",{className:`text-xs line-clamp-2 mb-2 ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-400":"text-gray-500"}`,children:p.messages[p.messages.length-1].content}):c.jsx("p",{className:`text-xs italic mb-2 ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:"No messages yet"}),c.jsxs("div",{className:`flex items-center space-x-1 text-xs ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:[c.jsx(vn,{className:"w-3 h-3"}),c.jsx("span",{children:za(p.updatedAt,"MMM d, HH:mm")})]})]}),c.jsx("button",{onClick:y=>{v(p,y)},disabled:l!==null,className:`opacity-0 group-hover:opacity-100 p-1.5 rounded-lg transition-all duration-200 ${i?"hover:bg-red-900 text-gray-400 hover:text-red-300":"hover:bg-red-50 text-gray-400 hover:text-red-600"}`,title:"Delete thread",children:l===`delete:${p.id}`?"…":c.jsx(Mn,{className:"w-4 h-4"})})]}),e?.id===p.id&&c.jsx("div",{className:`absolute left-0 top-1/2 transform -translate-y-1/2 w-1 h-8 rounded-r-full ${i?"bg-blue-400":"bg-blue-600"}`})]},p.id))})}),t.length>0&&c.jsx("div",{className:`p-4 border-t ${i?"border-gray-700":"border-gray-200"}`,children:c.jsxs("div",{className:`text-xs text-center ${i?"text-gray-500":"text-gray-400"}`,children:[t.length," thread",t.length!==1?"s":""," •",t.reduce((p,y)=>p+y.messages.length,0)," total messages"]})})]})},Ga=({children:t})=>{const{darkMode:e}=me();return c.jsx("div",{className:`flex-1 flex flex-col min-h-0 overflow-hidden ${e?"bg-gray-900":"bg-gray-50"}`,style:{height:"100%"},children:t})},Ka=B.lazy(()=>G(async()=>{const{GraphView:t}=await import("./GraphView-CMqOwCTc.js");return{GraphView:t}},__vite__mapDeps([0,1,2,3,4])).then(({GraphView:t})=>({default:t}))),bt=B.lazy(()=>G(async()=>{const{ChatView:t}=await import("./ChatView-C7_FNxo9.js");return{ChatView:t}},__vite__mapDeps([5,1,2,3,4,6])).then(({ChatView:t})=>({default:t}))),Ja=B.lazy(()=>G(async()=>{const{DebugView:t}=await import("./DebugView-Bwa7sy_c.js");return{DebugView:t}},__vite__mapDeps([7,1,6,4])).then(({DebugView:t})=>({default:t}))),Xa=B.lazy(()=>G(async()=>{const{PipelinesView:t}=await import("./PipelinesView-DacXbEMw.js");return{PipelinesView:t}},__vite__mapDeps([8,1,2,3,4])).then(({PipelinesView:t})=>({default:t}))),Qa=B.lazy(()=>G(async()=>{const{BuilderView:t}=await import("./BuilderView-C296ULRo.js");return{BuilderView:t}},__vite__mapDeps([9,1,10,2,4])).then(({BuilderView:t})=>({default:t}))),Za=B.lazy(()=>G(async()=>{const{PluginsView:t}=await import("./PluginsView-COAn7Q5V.js");return{PluginsView:t}},__vite__mapDeps([11,1,2,3,4])).then(({PluginsView:t})=>({default:t}))),eo=B.lazy(()=>G(async()=>{const{IngestorsView:t}=await import("./IngestorsView-Cd56f61k.js");return{IngestorsView:t}},__vite__mapDeps([12,1,2,3,4])).then(({IngestorsView:t})=>({default:t}))),to=B.lazy(()=>G(async()=>{const{TasksView:t}=await import("./TasksView-DAoR0f0z.js");return{TasksView:t}},__vite__mapDeps([13,1,2,3,4])).then(({TasksView:t})=>({default:t}))),ro=B.lazy(()=>G(async()=>{const{ControlPlaneView:t}=await import("./ControlPlaneView-CC__Od52.js");return{ControlPlaneView:t}},__vite__mapDeps([14,1,4])).then(({ControlPlaneView:t})=>({default:t}))),no=B.lazy(()=>G(async()=>{const{EndpointsView:t}=await import("./EndpointsView-fCUdmgxr.js");return{EndpointsView:t}},__vite__mapDeps([15,1,2,3,4])).then(({EndpointsView:t})=>({default:t}))),ao=B.lazy(()=>G(async()=>{const{ConnectionsView:t}=await import("./ConnectionsView-Dvq88oBW.js");return{ConnectionsView:t}},__vite__mapDeps([16,1,3,4])).then(({ConnectionsView:t})=>({default:t})));class oo extends B.Component{constructor(){super(...arguments),this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidUpdate(e){e.view!==this.props.view&&this.state.failed&&this.setState({failed:!1})}render(){return this.state.failed?c.jsxs("div",{role:"alert",className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center ${this.props.darkMode?"text-gray-200":"text-gray-800"}`,children:[c.jsxs("div",{children:[c.jsx("h2",{className:"text-lg font-semibold",children:"Workspace could not load"}),c.jsx("p",{className:`mt-1 max-w-md text-sm ${this.props.darkMode?"text-gray-400":"text-gray-600"}`,children:"A Studio module could not be loaded. Reload to fetch the current deployment assets."})]}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-lg bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700",children:"Reload Studio"})]}):this.props.children}}const so=()=>{const{currentView:t,setCurrentView:e,sidebarCollapsed:r,setSidebarCollapsed:n,darkMode:a}=me();h.useEffect(()=>{t||e("chat")},[t,e]),h.useEffect(()=>{const i=window.matchMedia("(max-width: 767px)"),l=()=>{i.matches&&n(!0)};return l(),i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[n]),h.useEffect(()=>{const i=l=>{if(l.ctrlKey||l.metaKey)switch(l.key){case"1":l.preventDefault(),e("chat");break;case"2":l.preventDefault(),e("graph");break;case"3":l.preventDefault(),e("debug");break;case"4":l.preventDefault(),e("pipelines");break;case"9":l.preventDefault(),e("builder");break;case"5":l.preventDefault(),e("plugins");break;case"0":l.preventDefault(),e("ingestion");break;case"-":l.preventDefault(),e("tasks");break;case"6":l.preventDefault(),e("control");break;case"7":l.preventDefault(),e("endpoints");break;case"8":l.preventDefault(),e("connections");break}};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[e]);const o=()=>{switch(t){case"graph":return c.jsx(Ka,{});case"chat":return c.jsx(bt,{});case"debug":return c.jsx(Ja,{});case"pipelines":return c.jsx(Xa,{});case"builder":return c.jsx(Qa,{});case"plugins":return c.jsx(Za,{});case"ingestion":return c.jsx(eo,{});case"tasks":return c.jsx(to,{});case"control":return c.jsx(ro,{});case"endpoints":return c.jsx(no,{});case"connections":return c.jsx(ao,{});default:return c.jsx(bt,{})}},s=c.jsx("div",{className:`flex h-full items-center justify-center p-6 text-sm ${a?"text-gray-400":"text-gray-600"}`,role:"status",children:"Loading workspace…"});return c.jsxs("div",{className:`h-screen w-screen flex flex-col overflow-hidden ${a?"bg-gray-900":"bg-gray-50"}`,children:[c.jsx("div",{className:"flex-shrink-0",children:c.jsx(Un,{})}),c.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden",children:[!r&&c.jsx("button",{type:"button","aria-label":"Close thread sidebar",className:"absolute inset-0 z-30 bg-black/35 md:hidden",onClick:()=>n(!0)}),c.jsx("div",{className:`flex-shrink-0 transition-all duration-300 ease-in-out overflow-hidden ${r?"w-0":"absolute inset-y-0 left-0 z-40 w-80 shadow-2xl md:static md:w-72 md:shadow-none xl:w-80"}`,style:{height:"100%"},children:c.jsx(Ha,{})}),c.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:c.jsx(Ga,{children:c.jsx(oo,{darkMode:a,view:t,children:c.jsx(h.Suspense,{fallback:s,children:o()})})})})]})]})},io=8e3,J=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=(t,e)=>{const r=t?.[e];return J(r)?r:void 0},co=(t,e)=>{const r=U(t,e);if(r||!t)return{pathItem:r,boundPathParameters:new Set};const n=e.split("/");for(const a of Object.keys(t)){if(!a.includes("{"))continue;const o=a.split("/");if(o.length!==n.length)continue;const s=new Set,i=o.every((d,u)=>{const m=/^\{([^}/]+)\}$/.exec(d);return m?(s.add(m[1]),n[u].length>0):d===n[u]}),l=U(t,a);if(i&&l)return{pathItem:l,boundPathParameters:s}}return{pathItem:void 0,boundPathParameters:new Set}},lo=t=>t!==null&&typeof t.name=="string"&&(t.in==="query"||t.in==="header"||t.in==="path"),Ye=(t,e="")=>typeof t=="string"?t:e,uo=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[];class Xe{constructor(e,r,n=io){this.openApiDocument=null,this.baseUrl=e.replace(/\/$/,""),this.apiKey=r||null,this.timeoutMs=n,this.headers={"Content-Type":"application/json",...this.apiKey?{"X-Api-Key":this.apiKey,Authorization:`Bearer ${this.apiKey}`}:{}}}async request(e,r){const n=`${this.baseUrl}${e}`,a=new AbortController,o=setTimeout(()=>a.abort(),this.timeoutMs),s=r?.signal;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));try{const i=await fetch(n,{...r,signal:a.signal,headers:{...this.headers,...r?.headers}});if(!i.ok){const d=await i.text().catch(()=>"");throw new ye(i.status,i.statusText,d)}if(i.status===204||r?.method?.toUpperCase()==="HEAD")return null;const l=await i.text();return l?JSON.parse(l):null}catch(i){throw J(i)&&i.name==="AbortError"?new ye(408,"Request Timeout",`Timed out after ${this.timeoutMs}ms: ${e}`):i}finally{clearTimeout(o)}}async getServerInfo(){return this.request("/studio/info")}async getOperationContract(e,r="post"){if(!this.openApiDocument){const b=this.request("/openapi.json");this.openApiDocument=b,b.catch(()=>{this.openApiDocument===b&&(this.openApiDocument=null)})}const n=await this.openApiDocument,a=U(n,"components"),{pathItem:o,boundPathParameters:s}=co(U(n,"paths"),e),i=U(o,r.toLowerCase());if(!i)throw new ye(404,"Operation not found",`${r.toUpperCase()} ${e}`);const l=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/schemas/"))return{...b,...a?{components:a}:{}};const k=w.slice(21),S=U(U(a,"schemas"),k);return J(S)?{...S,...a?{components:a}:{}}:null},d=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/parameters/"))return b;const k=w.slice(24),S=U(U(a,"parameters"),k);return J(S)?S:null},u=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/requestBodies/"))return b;const k=w.slice(27),S=U(U(a,"requestBodies"),k);return J(S)?S:null},m=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/responses/"))return b;const k=w.slice(23),S=U(U(a,"responses"),k);return J(S)?S:null},f=u(i.requestBody),x=U(U(f??void 0,"content"),"application/json")?.schema,v=new Map;[...Array.isArray(o?.parameters)?o.parameters:[],...Array.isArray(i.parameters)?i.parameters:[]].map(d).filter(lo).filter(b=>!(b.in==="path"&&s.has(b.name))).forEach(b=>v.set(`${b.in}:${b.name}`,b));const p=Array.from(v.values()),y=l(x),g=!!(y&&(y.type==="object"||y.properties)),C="__body",T=f?.required===!0,j=U(y??void 0,"properties")?U(y??void 0,"properties"):{},N=uo(y?.required),A=new Set(Object.keys(j)),I={},q={},E=[];for(const b of p){const w=b.name;let k=w;if(A.has(k)){k=`${b.in}_${w}`;let O=2;for(;A.has(k);)k=`${b.in}_${w}_${O++}`}A.add(k);const S=l(b.schema)||{};q[k]={...S,title:Ye(S.title,w),description:[Ye(S.description),`${b.in} parameter`].filter(Boolean).join(" · ")},I[k]={name:w,in:b.in},(b.required===!0||b.in==="path")&&E.push(k)}const L=p.length?{type:"object",properties:q,...E.length?{required:E}:{},components:a}:null,D=y&&g?{...y,properties:{...j,...q},...N.length||E.length?{required:Array.from(new Set([...N,...E]))}:{}}:y&&L?{type:"object",properties:{[C]:{...y,title:Ye(y.title,"Request body")},...q},...T||E.length?{required:[...T?[C]:[],...E]}:{}}:y||L,M=U(i,"responses")||{},K=m(M[200]||M[201]||M[202]||Object.values(M)[0]),ne=U(U(K??void 0,"content"),"application/json")?.schema;return{input_schema:D,output_schema:l(ne),method:r.toUpperCase(),path:e,...Object.keys(I).length?{parameters:I}:{},...y&&!g&&L?{body_field:C}:{}}}async getEndpointContract(e){const r=Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.toUpperCase()):[],n=Array.from(new Set(["POST",...r])),a=`/api/v1/endpoints/${encodeURIComponent(e.name)}${e.path}`;let o;for(const s of n)try{return await this.getOperationContract(a,s)}catch(i){if(!(i instanceof ye&&i.status===404))throw i;o=i}throw o instanceof Error?o:new ye(404,"Operation not found",`${e.name} has no documented callable method`)}async listAgents(){const e=await this.request("/studio/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:e?.agents&&typeof e.agents=="object"?Object.entries(e.agents).map(([r,n])=>({name:n?.name||r,slug:n?.slug||r,description:n?.description||"",version:n?.version||"1.0.0",framework:n?.framework||"unknown",capabilities:n?.capabilities||[],has_graph:!!n?.has_graph,has_config:!!n?.has_config,has_prompts:!!n?.has_prompts})):[]}async getGraph(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/graph`)}async getSchemas(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/schemas`)}async getAgentConfig(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/config`)}normalizeThread(e,r){return{id:e?.id||e?.thread_id||"",user_id:e?.user_id||"default-user",agent_name:e?.agent_name||r||"",title:e?.title??null,metadata:e?.metadata||{},created_at:e?.created_at||e?.created||new Date().toISOString(),updated_at:e?.updated_at||e?.updated||e?.created_at||new Date().toISOString()}}normalizeMessage(e,r){return{id:String(e?.id||e?.message_id||`${r}-${e?.timestamp||Date.now()}`),thread_id:e?.thread_id||r,role:e?.role||"assistant",content:typeof e?.content=="string"?e.content:JSON.stringify(e?.content??e?.message??""),metadata:e?.metadata||{},timestamp:e?.timestamp||e?.created_at||new Date().toISOString()}}async createThread(e,r,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`,{method:"POST",body:JSON.stringify({user_id:r||"default-user",title:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async listThreads(e){const r=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`);return(Array.isArray(r)?r:Array.isArray(r?.threads)?r.threads:[]).map(a=>this.normalizeThread(a,e))}async getThread(e,r){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}`);return this.normalizeThread(n,e)}async deleteThread(e,r){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}`,{method:"DELETE"})}async getMessages(e,r){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/messages`);return(Array.isArray(n)?n:Array.isArray(n?.messages)?n.messages:[]).map(o=>this.normalizeMessage(o,r))}async forkThread(e,r,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/fork`,{method:"POST",body:JSON.stringify({message_index:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async createRun(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs`,{method:"POST",body:JSON.stringify(r)})}async listRuns(e,r=50){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs?limit=${r}`)}async getRun(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(r)}`)}async getState(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/state`)}async updateState(e,r,n){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/state`,{method:"POST",body:JSON.stringify({updates:n})})}async getHistory(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/history`)}async getPendingApprovals(e,r){return this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/pending`)}async approve(e,r,n){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({approval_id:n})})}async reject(e,r,n,a){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({approval_id:n,reason:a})})}async healthCheck(){try{return await this.request("/studio/info"),!0}catch{return!1}}async listPipelines(){const e=await this.request("/api/v1/pipelines");return(Array.isArray(e)?e:Array.isArray(e?.pipelines)?e.pipelines:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",steps:Array.isArray(n?.steps)?n.steps:[],agents_used:Array.isArray(n?.agents_used)?n.agents_used:[]}))}async runPipeline(e,r){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(r)})}async validatePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/validate`)}async validatePipelineDraft(e){return this.request("/api/v1/pipelines/validate-draft",{method:"POST",body:JSON.stringify(e)})}async savePipeline(e,r){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(r)})}async deletePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"DELETE"})}async listEndpoints(){const e=await this.request("/api/v1/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listIngestors(){const e=await this.request("/api/v1/ingestors");return(Array.isArray(e)?e:Array.isArray(e?.ingestors)?e.ingestors:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",ready:!!n?.ready,input_schema:n?.input_schema||""}))}async runIngestor(e,r){return this.request(`/api/v1/ingestion/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(r)})}async listTasks(e={}){const r=new URLSearchParams;return Object.entries(e).forEach(([n,a])=>{a!==void 0&&a!==""&&r.set(n,String(a))}),this.request(`/api/v1/tasks${r.size?`?${r}`:""}`)}async submitTask(e){return this.request("/api/v1/tasks",{method:"POST",body:JSON.stringify(e)})}async getTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`)}async getTaskResult(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/result`)}async cancelTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/cancel`,{method:"POST"})}async deleteTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`,{method:"DELETE"})}async getPipelineConfig(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/config`)}async visualizePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/visualize`)}async listPlugins(){const e=await this.request("/api/v1/plugins");return(Array.isArray(e)?e:Array.isArray(e?.plugins)?e.plugins:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",is_loaded:!!n?.is_loaded}))}async getPluginModelCard(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/model_card`)}async reloadPlugin(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/reload`,{method:"POST"})}async runPluginPredict(e,r){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/predict`,{method:"POST",body:JSON.stringify(r)})}async callEndpoint(e,r,n,a="POST",o){const s=a.toUpperCase();let i=`/api/v1/endpoints/${encodeURIComponent(e)}${r}`;const l=new URLSearchParams,d={},u={},m=o?.parameters||{},f=o?.body_field,x=n&&typeof n=="object"&&!Array.isArray(n)?n:null,v=f&&x?x[f]:n;for(const[y,g]of Object.entries(x||{})){if(y===f)continue;const C=m[y],j=C?C.in:s==="GET"||s==="HEAD"?"query":"body",N=C?.name||y;if(j==="body"){d[y]=g;continue}if(!(g==null||g==="")){if(j==="path"){i=i.replace(`{${N}}`,encodeURIComponent(String(g)));continue}if(j==="header"){u[N]=Array.isArray(g)?g.map(A=>typeof A=="string"?A:JSON.stringify(A)).join(", "):typeof g=="object"?JSON.stringify(g):String(g);continue}Array.isArray(g)?g.forEach(A=>l.append(N,typeof A=="string"?A:JSON.stringify(A))):l.set(N,typeof g=="object"?JSON.stringify(g):String(g))}}const p=l.size?`?${l.toString()}`:"";return s==="GET"||s==="HEAD"?this.request(`${i}${p}`,{method:s,headers:u}):this.request(`${i}${p}`,{method:s,headers:u,body:JSON.stringify(f||!x?v:d)})}async getControlInfo(){return this.request("/api/v1/control")}async listControlAgents(){const e=await this.request("/api/v1/control/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]}async getControlAgent(e){return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}`)}async listControlEndpoints(){const e=await this.request("/api/v1/control/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listControlConnections(){const e=await this.request("/api/v1/control/connections");return(Array.isArray(e)?e:Array.isArray(e?.connections)?e.connections:[]).map(n=>({scope:n?.scope||"",connections:n?.connections||{}}))}async probeControlConnection(e,r){return this.request(`/api/v1/control/connections/${encodeURIComponent(e)}/${encodeURIComponent(r)}`)}async getControlMetricsSummary(){return this.request("/api/v1/control/metrics/summary")}async getControlHealth(){return this.request("/api/v1/control/health")}async getControlConfig(){return this.request("/api/v1/control/config")}async setAgentEnabled(e,r,n){const a=r?"enable":"disable";return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}/${a}`,{method:"POST",headers:n?{"X-Control-Token":n}:{}})}async setMaintenance(e,r){return this.request("/api/v1/control/maintenance",{method:"POST",headers:r?{"X-Control-Token":r}:{},body:JSON.stringify({enabled:e})})}getStreamUrl(e){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/runs/stream`}getResumeStreamUrl(e,r){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/resume`}getHeaders(){return{...this.headers}}}class ye extends Error{constructor(e,r,n){super(`API Error ${e}: ${r}`),this.status=e,this.statusText=r,this.body=n,this.name="ApiError"}}const mo="agentomatic-studio:lastUrl",Ne="agentomatic-studio:lastApiKey",vt="agentomatic-studio:lastApiKey",fo=()=>{try{const t=sessionStorage.getItem(Ne);if(t)return t;const e=localStorage.getItem(vt);return e?(sessionStorage.setItem(Ne,e),localStorage.removeItem(vt),e):""}catch{return""}},po={graph:{light:"bg-blue-100 text-blue-700 border-blue-200",dark:"bg-blue-900/40 text-blue-300 border-blue-700"},streaming:{light:"bg-green-100 text-green-700 border-green-200",dark:"bg-green-900/40 text-green-300 border-green-700"},hitl:{light:"bg-amber-100 text-amber-700 border-amber-200",dark:"bg-amber-900/40 text-amber-300 border-amber-700"},checkpoints:{light:"bg-purple-100 text-purple-700 border-purple-200",dark:"bg-purple-900/40 text-purple-300 border-purple-700"}},ho={light:"bg-gray-100 text-gray-700 border-gray-200",dark:"bg-gray-700 text-gray-300 border-gray-600"},go=()=>{const t=Mt(),{setConfig:e,setIsConnected:r,setIsLoading:n,addAssistant:a,clearAssistants:o,fetchGraphData:s,refreshThreads:i,setSelectedAgent:l,darkMode:d}=me(),[u,m]=h.useState(()=>{const S=fo();return{apiUrl:Ae(),agentId:"",apiKey:S||""}}),[f,x]=h.useState({status:"idle",message:"Enter server URL to check connectivity"}),[v,p]=h.useState([]),[y,g]=h.useState(!1),[C,T]=h.useState(!1),[j,N]=h.useState(!1),[,A]=h.useState(null),[I,q]=h.useState({}),E=h.useRef(0),L=h.useCallback((S,O)=>{try{localStorage.setItem(mo,S),O?sessionStorage.setItem(Ne,O):sessionStorage.removeItem(Ne)}catch{}},[]),D=h.useCallback(S=>{const O=po[S]||ho,F=d?O.dark:O.light;return c.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border leading-tight ${F}`,children:S},S)},[d]),M=h.useCallback(async S=>{const O=++E.current,F=mt(S);if(!F||!F.startsWith("http")){x({status:"idle",message:"Enter a valid server URL"}),p([]),q({}),N(!1),g(!1);return}x({status:"checking",message:"Checking server connectivity..."}),p([]),q({}),N(!1),g(!0),m(z=>z.agentId?{...z,agentId:""}:z);try{const z=new Xe(F,u.apiKey||void 0),H=await z.getServerInfo();if(O!==E.current)return;A(H);const ae=await z.listAgents();if(O!==E.current)return;if(ae.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ve=ae.map(_=>({id:_.slug||_.name,name:_.name,description:_.description||`${_.framework} agent`,config:{capabilities:_.capabilities,has_graph:_.has_graph,version:_.version}})),oe={};ae.forEach(_=>{oe[_.slug||_.name]=_.capabilities||[]}),q(oe),p(ve),m(_=>({..._,agentId:ve[0].id})),x({status:"success",message:`Connected to ${H.platform_title||"Agentomatic"} v${H.version} — ${H.agent_count} agent(s)`,lastChecked:new Date}),setTimeout(()=>N(!0),300)}catch(z){if(O!==E.current)return;const H=z?.status===401||z?.status===403?"Studio authorization failed. Provide a valid API key and retry.":`Studio API is unavailable: ${z?.message||"start the platform with Studio enabled."}`;x({status:"error",message:H,lastChecked:new Date}),N(!1)}finally{O===E.current&&g(!1)}},[u.apiKey]);h.useEffect(()=>{const S=setTimeout(()=>{u.apiUrl&&M(u.apiUrl)},1e3);return()=>clearTimeout(S)},[u.apiUrl,M]);const K=async S=>{if(S.preventDefault(),f.status!=="success"){Se.error("Please ensure the server connection is healthy before connecting");return}if(!u.agentId){Se.error("Please select a live agent to use");return}T(!0),n(!0);try{const O=mt(u.apiUrl),F=new Xe(O,u.apiKey||void 0),[z,H]=await Promise.all([F.getServerInfo(),F.listAgents()]);if(H.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ae=H.map(_=>({id:_.slug||_.name,name:_.name,description:_.description||"",type:"chat",model:_.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:_.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:_.capabilities,apiName:_.name,slug:_.slug},graph_id:_.slug||_.name}));Je(F),o(),e({...u,apiUrl:O}),ae.forEach(_=>a(_)),r(!0);const ve=u.agentId||H[0]?.slug||H[0]?.name,oe=ae.find(_=>_.id===ve)||ae[0];oe&&(l(oe),s(oe.id).catch(_=>{console.warn("Background graph load failed:",_)}),i(oe.id).catch(()=>{})),L(O,u.apiKey||""),Se.success(`Connected to ${z.platform_title||"Agentomatic"} v${z.version}!`),setTimeout(()=>t("/studio"),500)}catch(O){console.error("Connection error:",O),Se.error("Failed to connect. Please check your configuration.")}finally{T(!1),n(!1)}},ne=(S,O)=>{m(F=>({...F,[S]:O}))},b=()=>{switch(f.status){case"checking":return c.jsxs("svg",{className:"w-5 h-5 animate-spin text-blue-500",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]});case"success":return c.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})});case"error":return c.jsx("svg",{className:"w-5 h-5 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})});default:return c.jsx("svg",{className:"w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}},w=()=>{switch(f.status){case"checking":return"text-blue-600 bg-blue-50 border-blue-200";case"success":return"text-green-600 bg-green-50 border-green-200";case"error":return"text-red-600 bg-red-50 border-red-200";default:return"text-gray-600 bg-gray-50 border-gray-200"}},k=()=>{switch(f.status){case"checking":return"text-blue-400 bg-blue-900/30 border-blue-700";case"success":return"text-green-400 bg-green-900/30 border-green-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return c.jsxs("div",{className:`min-h-screen w-full flex ${d?"bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900":"bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50"} relative overflow-hidden`,children:[c.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[c.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),c.jsx("div",{className:`absolute top-1/4 left-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse ${d?"bg-blue-600":"bg-blue-400"}`}),c.jsx("div",{className:`absolute bottom-1/4 right-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse delay-1000 ${d?"bg-purple-600":"bg-purple-400"}`}),c.jsx("div",{className:`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 rounded-full blur-3xl opacity-10 animate-pulse delay-500 ${d?"bg-indigo-600":"bg-indigo-400"}`})]}),c.jsxs("div",{className:"relative z-10 w-full flex",children:[c.jsx("div",{className:"hidden lg:flex lg:w-1/2 xl:w-2/5 flex-col justify-center items-center p-12 relative",children:c.jsxs("div",{className:"max-w-md text-center animate-slide-in-left",children:[c.jsx("div",{className:`w-32 h-32 rounded-3xl flex items-center justify-center mx-auto mb-8 ${d?"bg-gradient-to-br from-blue-600 via-purple-600 to-indigo-600":"bg-gradient-to-br from-blue-500 via-indigo-500 to-purple-600"} shadow-2xl animate-pulse-glow`,children:c.jsx("svg",{className:"w-16 h-16 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),c.jsxs("h1",{className:`text-5xl font-bold mb-6 ${d?"text-white":"text-gray-900"}`,children:["Agentomatic",c.jsx("span",{className:`block text-4xl ${d?"text-violet-400":"text-violet-600"}`,children:"Studio"})]}),c.jsx("p",{className:`text-xl leading-relaxed mb-8 ${d?"text-gray-300":"text-gray-600"}`,children:"Build, debug, and deploy intelligent agent workflows with visual graph execution"}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-green-400":"bg-green-500"} animate-pulse`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Real-time graph execution"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-blue-400":"bg-blue-500"} animate-pulse delay-300`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Interactive debugging tools"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-purple-400":"bg-purple-500"} animate-pulse delay-700`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Multi-agent orchestration"})]})]})]})}),c.jsx("div",{className:"w-full lg:w-1/2 xl:w-3/5 flex items-center justify-center p-6 lg:p-12",children:c.jsxs("div",{className:`w-full max-w-md rounded-3xl shadow-2xl backdrop-blur-md border ${d?"bg-gray-800/80 border-gray-700":"bg-white/80 border-gray-200"} animate-slide-in-right`,children:[c.jsxs("div",{className:"p-8 text-center",children:[c.jsx("div",{className:"lg:hidden mb-6",children:c.jsx("div",{className:`w-16 h-16 rounded-2xl flex items-center justify-center mx-auto ${d?"bg-gradient-to-br from-blue-600 to-purple-600":"bg-gradient-to-br from-blue-500 to-indigo-600"} shadow-lg`,children:c.jsx("svg",{className:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})})}),c.jsx("h2",{className:`text-2xl lg:text-3xl font-bold mb-3 ${d?"text-white":"text-gray-900"}`,children:"Get Started"}),c.jsx("p",{className:`text-lg ${d?"text-gray-300":"text-gray-600"}`,children:"Connect to your authenticated Agentomatic server"})]}),c.jsxs("div",{className:"px-8 pb-8",children:[c.jsxs("form",{onSubmit:K,className:"space-y-6",children:[c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsx("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:"Server URL"}),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:"url",value:u.apiUrl,onChange:S=>ne("apiUrl",S.target.value),placeholder:Ae(),className:`w-full px-4 py-4 pr-14 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`,required:!0}),c.jsx("div",{className:"absolute right-4 top-1/2 transform -translate-y-1/2",children:b()})]}),c.jsxs("div",{className:`mt-3 p-4 rounded-xl border text-sm flex items-center space-x-3 transition-all duration-300 ${d?k():w()}`,children:[b(),c.jsxs("div",{className:"flex-1",children:[c.jsx("span",{className:"font-medium",children:f.message}),f.lastChecked&&c.jsxs("div",{className:"text-xs opacity-75 mt-1",children:["Last checked: ",f.lastChecked.toLocaleTimeString()]})]})]})]}),c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsxs("label",{htmlFor:"agentomatic-api-key",className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["API key ",c.jsx("span",{className:"font-normal opacity-70",children:"(optional)"})]}),c.jsx("input",{id:"agentomatic-api-key",type:"password",value:u.apiKey||"",onChange:S=>ne("apiKey",S.target.value),placeholder:"Required when server authentication is enabled",autoComplete:"off",spellCheck:!1,className:`w-full px-4 py-4 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`}),c.jsx("p",{className:`mt-2 text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Kept only for this tab session after a successful connection; closing the tab removes it."})]}),j&&c.jsxs("div",{className:"animate-fade-in-up stagger-2",children:[c.jsxs("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["Available agents",y&&c.jsxs("span",{className:"ml-2 text-xs text-blue-500",children:[c.jsxs("svg",{className:"inline w-3 h-3 animate-spin mr-1",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Loading..."]})]}),v.length>0?c.jsx("div",{className:"space-y-3 max-h-48 overflow-y-auto custom-scrollbar",children:v.map((S,O)=>c.jsxs("label",{className:`flex items-center p-4 rounded-xl border cursor-pointer transition-all duration-300 transform hover:scale-105 ${u.agentId===S.id?d?"bg-blue-900/40 border-blue-500 text-blue-400 shadow-lg":"bg-blue-50 border-blue-500 text-blue-700 shadow-lg":d?"bg-gray-700/50 border-gray-600 hover:bg-gray-600/50 text-gray-200":"bg-white/50 border-gray-200 hover:bg-gray-50 text-gray-700"} animate-slide-in-right`,style:{animationDelay:`${O*100}ms`},children:[c.jsx("input",{type:"radio",name:"agentId",value:S.id,checked:u.agentId===S.id,onChange:F=>ne("agentId",F.target.value),className:"sr-only"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"font-semibold",children:S.name}),I[S.id]?.length>0&&c.jsx("span",{className:"flex flex-wrap gap-1",children:I[S.id].map(D)})]}),S.description&&c.jsx("div",{className:`text-sm mt-1 ${u.agentId===S.id?"opacity-90":d?"text-gray-400":"text-gray-500"}`,children:S.description})]}),c.jsx("div",{className:`w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all duration-200 ${u.agentId===S.id?"border-current scale-110":d?"border-gray-500":"border-gray-300"}`,children:u.agentId===S.id&&c.jsx("div",{className:"w-3 h-3 rounded-full bg-current animate-pulse"})})]},S.id))}):c.jsx("div",{className:`p-6 rounded-xl border text-center ${d?"bg-gray-700/50 border-gray-600 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:y?c.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Loading live agents..."})]}):"No live agents available. Check the Studio API and server connection."})]}),c.jsx("div",{className:"space-y-4 animate-fade-in-up stagger-3",children:c.jsx("button",{type:"submit",disabled:f.status!=="success"||!u.agentId||C,className:`w-full py-4 px-6 rounded-2xl font-semibold text-white transition-all duration-300 transform ${f.status==="success"&&u.agentId&&!C?"bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 hover:scale-105 shadow-lg hover:shadow-2xl":"bg-gray-400 cursor-not-allowed opacity-50"}`,children:C?c.jsxs("div",{className:"flex items-center justify-center space-x-3",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Connecting..."})]}):"Connect to Server"})})]}),c.jsx("div",{className:`mt-8 pt-6 border-t ${d?"border-gray-600":"border-gray-200"} animate-fade-in-up stagger-4`,children:c.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-green-400":"text-green-600"}`,children:"🚀"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Authenticated server"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Verify before entering Studio"})]}),c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-blue-400":"text-blue-600"}`,children:"🔗"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Live execution"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Uses deployed resource contracts"})]})]})})]})]})})]})]})},wt="agentomatic-studio:lastApiKey",Ct="agentomatic-studio:lastApiKey",yo=()=>{try{const t=sessionStorage.getItem(wt);if(t)return t;const e=localStorage.getItem(Ct);return e?(sessionStorage.setItem(wt,e),localStorage.removeItem(Ct),e):""}catch{return""}},xo=t=>({id:t.slug||t.name,name:t.name,description:t.description||"",type:"chat",model:t.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:t.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:t.capabilities,apiName:t.name,slug:t.slug},graph_id:t.slug||t.name,metadata:{version:t.version,framework:t.framework,capabilities:t.capabilities,has_graph:t.has_graph,has_config:t.has_config}});function bo(){const{isConnected:t,darkMode:e,setConfig:r,setIsConnected:n,setConnectionStatus:a,clearAssistants:o,addAssistant:s,setSelectedAssistant:i,fetchGraphData:l,refreshThreads:d}=me(),[u,m]=h.useState(!1),f="/studio/ui/".replace(/\/$/,"");h.useEffect(()=>{e?(document.documentElement.setAttribute("data-theme","dark"),document.documentElement.classList.add("dark")):(document.documentElement.removeAttribute("data-theme"),document.documentElement.classList.remove("dark"))},[e]),h.useEffect(()=>{let v=!1;return(async()=>{const y=Ae();let g="";try{g=yo()}catch{}try{const C=new Xe(y,g||void 0);await C.getServerInfo();const T=await C.listAgents();if(v)return;const j=T.map(xo);Je(C);const N=j[0];r({apiUrl:y,apiKey:g||void 0,agentId:N?.id}),o(),j.forEach(s),N&&(i(N),l(N.id),d(N.id).catch(()=>{})),a("connected"),n(!0)}catch{v||(Je(null),a("disconnected"),n(!1))}finally{v||m(!0)}})(),()=>{v=!0}},[s,o,r,a,n,i,l,d]);const x=u?t?c.jsx(so,{}):c.jsx(et,{to:"/setup",replace:!0}):c.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-gray-500",children:"Restoring Studio session…"});return c.jsxs(It,{basename:f,children:[c.jsx("div",{className:`App ${e?"dark":""}`,children:c.jsxs(Lt,{children:[c.jsx(Re,{path:"/setup",element:c.jsx(go,{})}),c.jsx(Re,{path:"/studio",element:x}),c.jsx(Re,{path:"/",element:c.jsx(et,{to:t&&u?"/studio":"/setup",replace:!0})})]})}),c.jsx(Rr,{position:"top-right",toastOptions:{duration:4e3,style:{background:e?"#374151":"#ffffff",color:e?"#f9fafb":"#111827",border:e?"1px solid #4b5563":"1px solid #e5e7eb"},success:{duration:3e3,iconTheme:{primary:"#10b981",secondary:e?"#374151":"#ffffff"}},error:{duration:5e3,iconTheme:{primary:"#ef4444",secondary:e?"#374151":"#ffffff"}}}})]})}const vo=Bt.createRoot(document.getElementById("root"));vo.render(c.jsx(B.StrictMode,{children:c.jsx(bo,{})}));export{Xe as A,jn as F,Se as V,Nt as a,Ro as b,Do as c,No as d,tn as e,za as f,Mn as g,ko as h,_o as i,c as j,Ao as k,To as l,$o as m,Y as n,jo as o,So as p,Oo as q,Eo as s,me as u}; diff --git a/src/agentomatic/studio/static/index.html b/src/agentomatic/studio/static/index.html index 357a7e8a..de2d9502 100644 --- a/src/agentomatic/studio/static/index.html +++ b/src/agentomatic/studio/static/index.html @@ -14,10 +14,10 @@ /> Agentomatic Studio - + - + diff --git a/tests/test_studio_bundle.py b/tests/test_studio_bundle.py index 0825b3f2..de839436 100644 --- a/tests/test_studio_bundle.py +++ b/tests/test_studio_bundle.py @@ -59,6 +59,7 @@ def test_message_ids_are_strings() -> None: def test_operation_contracts_match_templated_paths() -> None: entry = _entry() - start = entry.index("async getOperationContract(") - body = entry[start : start + 1500] - assert "Object.keys(" in body and "RegExp(" in body, "no templated-path fallback" + # agentomatic-studio ``findPathItem``: a concrete path such as + # /api/v1/pipelines//run matches the published + # /api/v1/pipelines/{name}/run through a ``{placeholder}`` segment test. + assert "/^\\{([^}/]+)\\}$/" in entry, "no templated-path fallback in the contract lookup" From 1428e2d25fd3142eac862924aad34c7ef994f274 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 20:50:19 +0000 Subject: [PATCH 12/16] chore(studio): rebuild the Studio UI 0.4.1 bundle with patched dependencies Matches agentomatic-studio 0.4.1 after its lockfile audit fix (updated js-yaml and browserslist change the entry chunk and CSS hashes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- .../static/assets/BuilderView-BChq4Mpg.js | 52 +++++++++++++++++++ .../static/assets/BuilderView-C296ULRo.js | 46 ---------------- ...tView-C7_FNxo9.js => ChatView-Bc4TZ9mm.js} | 2 +- ...vq88oBW.js => ConnectionsView-CD79PtTG.js} | 2 +- ...__Od52.js => ControlPlaneView-Vj8HdZgI.js} | 2 +- ...View-Bwa7sy_c.js => DebugView-BXWYXNI6.js} | 2 +- ...-fCUdmgxr.js => EndpointsView-DqDGXNuG.js} | 2 +- ...View-CMqOwCTc.js => GraphView-CxhhCL_h.js} | 2 +- ...-Cd56f61k.js => IngestorsView-Be0ZMvN2.js} | 2 +- ...RqI.js => OutputSchemaSummary-CiE3pU-0.js} | 2 +- ...-DacXbEMw.js => PipelinesView-Yvdzmlvq.js} | 2 +- ...ew-COAn7Q5V.js => PluginsView-BCct6WZb.js} | 2 +- ...orm-DyHc2s7z.js => SchemaForm-Kr1WPDMd.js} | 2 +- ...View-DAoR0f0z.js => TasksView-B5ml_CT4.js} | 2 +- .../{index-FSSL6O5F.js => index-BMj1jeBL.js} | 4 +- .../studio/static/assets/index-CUex9gTG.css | 1 + .../studio/static/assets/index-Czmh8XoR.css | 1 - src/agentomatic/studio/static/index.html | 4 +- 18 files changed, 69 insertions(+), 63 deletions(-) create mode 100644 src/agentomatic/studio/static/assets/BuilderView-BChq4Mpg.js delete mode 100644 src/agentomatic/studio/static/assets/BuilderView-C296ULRo.js rename src/agentomatic/studio/static/assets/{ChatView-C7_FNxo9.js => ChatView-Bc4TZ9mm.js} (99%) rename src/agentomatic/studio/static/assets/{ConnectionsView-Dvq88oBW.js => ConnectionsView-CD79PtTG.js} (97%) rename src/agentomatic/studio/static/assets/{ControlPlaneView-CC__Od52.js => ControlPlaneView-Vj8HdZgI.js} (99%) rename src/agentomatic/studio/static/assets/{DebugView-Bwa7sy_c.js => DebugView-BXWYXNI6.js} (99%) rename src/agentomatic/studio/static/assets/{EndpointsView-fCUdmgxr.js => EndpointsView-DqDGXNuG.js} (97%) rename src/agentomatic/studio/static/assets/{GraphView-CMqOwCTc.js => GraphView-CxhhCL_h.js} (99%) rename src/agentomatic/studio/static/assets/{IngestorsView-Cd56f61k.js => IngestorsView-Be0ZMvN2.js} (95%) rename src/agentomatic/studio/static/assets/{OutputSchemaSummary-C65WaRqI.js => OutputSchemaSummary-CiE3pU-0.js} (97%) rename src/agentomatic/studio/static/assets/{PipelinesView-DacXbEMw.js => PipelinesView-Yvdzmlvq.js} (96%) rename src/agentomatic/studio/static/assets/{PluginsView-COAn7Q5V.js => PluginsView-BCct6WZb.js} (96%) rename src/agentomatic/studio/static/assets/{SchemaForm-DyHc2s7z.js => SchemaForm-Kr1WPDMd.js} (99%) rename src/agentomatic/studio/static/assets/{TasksView-DAoR0f0z.js => TasksView-B5ml_CT4.js} (98%) rename src/agentomatic/studio/static/assets/{index-FSSL6O5F.js => index-BMj1jeBL.js} (99%) create mode 100644 src/agentomatic/studio/static/assets/index-CUex9gTG.css delete mode 100644 src/agentomatic/studio/static/assets/index-Czmh8XoR.css diff --git a/src/agentomatic/studio/static/assets/BuilderView-BChq4Mpg.js b/src/agentomatic/studio/static/assets/BuilderView-BChq4Mpg.js new file mode 100644 index 00000000..1e719474 --- /dev/null +++ b/src/agentomatic/studio/static/assets/BuilderView-BChq4Mpg.js @@ -0,0 +1,52 @@ +import{j as s,V as oe,p as tt,a as ai,u as si,A as oi,F as jn,g as li}from"./index-BMj1jeBL.js";import{r as b,R as ci}from"./react-vendor-BHJ3EV8m.js";import{F as ui,R as pi,L as fi,N as di,B as mi,I as gi,G as hi,P as xi,a as bi,b as ir,C as ar,c as sr,T as yi,d as or,X as vt,e as ft,f as ln,g as cn,A as lr}from"./ui-vendor-DIaV1y77.js";import{S as vi}from"./SchemaForm-Kr1WPDMd.js";import"./syntax-vendor-ru7AzRyY.js";function Ni({title:e,titleId:t,...n},r){return b.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?b.createElement("title",{id:t},e):null,b.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"}))}const Si=b.forwardRef(Ni);function _i({title:e,titleId:t,...n},r){return b.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?b.createElement("title",{id:t},e):null,b.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const Ci=b.forwardRef(_i);function $i({title:e,titleId:t,...n},r){return b.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?b.createElement("title",{id:t},e):null,b.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17.25 6.75 22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3-4.5 16.5"}))}const Ai=b.forwardRef($i);function ji({title:e,titleId:t,...n},r){return b.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?b.createElement("title",{id:t},e):null,b.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"}))}const wi=b.forwardRef(ji),Ye={agent:{label:"Agent",description:"Invoke a registered agent",icon:"Bot",badge:"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",accent:"border-blue-500"},plugin:{label:"Plugin",description:"Call an ML plugin predict",icon:"Puzzle",badge:"bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300",accent:"border-purple-500"},endpoint:{label:"Endpoint",description:"Call a custom endpoint",icon:"Globe",badge:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",accent:"border-emerald-500"},ingestion:{label:"Ingestion",description:"Run an ingestor",icon:"Inbox",badge:"bg-teal-100 text-teal-700 dark:bg-teal-900 dark:text-teal-300",accent:"border-teal-500"},transform:{label:"Transform",description:"Python code block",icon:"Braces",badge:"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",accent:"border-amber-500"},parallel:{label:"Parallel",description:"Fan out agent steps",icon:"Network",badge:"bg-pink-100 text-pink-700 dark:bg-pink-900 dark:text-pink-300",accent:"border-pink-500"},map:{label:"Map",description:"Agent over a list of items",icon:"ListTree",badge:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300",accent:"border-indigo-500"},loop:{label:"Loop",description:"Iterate an agent step",icon:"Repeat",badge:"bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300",accent:"border-orange-500"},sub_pipeline:{label:"Sub-pipeline",description:"Nest another pipeline",icon:"FolderTree",badge:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300",accent:"border-cyan-500"}},wn=[{kind:"agent",label:"Agent step",description:"Invoke a registered agent"},{kind:"endpoint",label:"Endpoint step",description:"Call a custom endpoint"},{kind:"plugin",label:"Plugin step",description:"Call an ML plugin predict"},{kind:"ingestion",label:"Ingestion step",description:"Run an ingestor"},{kind:"transform",label:"Transform step",description:"Python code block"},{kind:"parallel",label:"Parallel container",description:"Fan out agent steps"},{kind:"map",label:"Map step",description:"Agent over a list of items"},{kind:"loop",label:"Loop container",description:"Iterate an agent step"},{kind:"sub_pipeline",label:"Sub-pipeline step",description:"Nest another pipeline"}];function Gt(e,t){switch(e){case"agent":return{name:t,agent:""};case"plugin":return{name:t,plugin:""};case"endpoint":return{name:t,endpoint:""};case"ingestion":return{name:t,ingestion:""};case"transform":return{name:t,transform:""};case"parallel":return{name:t,parallel:{steps:[]}};case"map":return{name:t,map:{agent:"",items:"$.input.items"}};case"loop":return{name:t,loop:{step:{}}};case"sub_pipeline":return{name:t,sub_pipeline:""}}}function Ei(e,t){return e==="parallel"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Gt("agent",`${t}_child_1`),children:[]}]:e==="loop"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Gt("agent",`${t}_child_1`),children:[]}]:[]}var R=Symbol("NOT_RESOLVED");function te(e,t){return{tagName:e,nodeKind:"scalar",implicit:t.implicit??!1,matchByTagPrefix:t.matchByTagPrefix??!1,implicitFirstChars:t.implicitFirstChars??null,resolve:t.resolve,identify:t.identify,represent:t.represent??(n=>String(n)),representTagName:t.representTagName??(()=>e)}}function un(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"sequence",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addItem:t.addItem,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify,represent:t.represent??(r=>r),representTagName:t.representTagName??(()=>e)}}function Nt(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"mapping",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addPair:t.addPair,has:t.has,keys:t.keys,get:t.get,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify,represent:t.represent??(r=>r),representTagName:t.representTagName??(()=>e)}}var ki=te("tag:yaml.org,2002:str",{resolve:e=>e,identify:e=>typeof e=="string"}),Ti=["","~","null","Null","NULL"],Oi=te("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Ti.indexOf(e)!==-1?null:R,identify:e=>e===null,represent:()=>"null"}),Ii=te("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["n"],resolve:(e,t)=>e==="null"||t&&e===""?null:R,identify:e=>e===null,represent:()=>"null"}),Li=["","~","null","Null","NULL"],Fi=te("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Li.indexOf(e)!==-1?null:R,identify:e=>e===null,represent:()=>"null"}),Ri=["true","True","TRUE"],Pi=["false","False","FALSE"],Di=te("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","T","f","F"],resolve:e=>Ri.indexOf(e)!==-1?!0:Pi.indexOf(e)!==-1?!1:R,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Bi=["true"],Ui=["false"],Ki=te("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","f"],resolve:e=>Bi.indexOf(e)!==-1?!0:Ui.indexOf(e)!==-1?!1:R,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),qi=["true","True","TRUE","y","Y","yes","Yes","YES","on","On","ON"],Yi=["false","False","FALSE","n","N","no","No","NO","off","Off","OFF"],Wi=te("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["y","Y","n","N","t","T","f","F","o","O"],resolve:e=>qi.indexOf(e)!==-1?!0:Yi.indexOf(e)!==-1?!1:R,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Gi=new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$"),Vi=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function zi(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function Mi(e,t){if(t){if(!Vi.test(e))return R}else if(!Gi.test(e))return R;const n=zi(e);return Number.isFinite(n)?n:R}var cr=te("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:Mi,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),Hi=new RegExp("^-?(?:0|[1-9][0-9]*)$"),Qi=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function Ji(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function Xi(e,t){if(t){if(!Qi.test(e))return R}else if(!Hi.test(e))return R;const n=Ji(e);return Number.isFinite(n)?n:R}var Zi=te("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:Xi,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),ea=new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$");function ta(e){let t=e.replace(/_/g,""),n=1;if((t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b"))return n*parseInt(t.slice(2),2);if(t.startsWith("0x"))return n*parseInt(t.slice(2),16);if(t.includes(":")){let r=0;for(const i of t.split(":"))r=r*60+Number(i);return n*r}return t!=="0"&&t[0]==="0"?n*parseInt(t,8):n*parseInt(t,10)}function na(e){if(!ea.test(e))return R;const t=ta(e);return Number.isFinite(t)?t:R}var Vt=te("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:na,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),ra=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),ia=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function aa(e){if(!ra.test(e))return R;let t=e.toLowerCase();const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;const r=n*parseFloat(t);return Number.isFinite(r)||ia.test(e)?r:R}function sa(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var ur=te("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:aa,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:sa}),oa=new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$"),la=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ca(e,t){if(t){if(!la.test(e))return R;let r=e.toLowerCase();const i=r[0]==="-"?-1:1;if("+-".includes(r[0])&&(r=r.slice(1)),r===".inf")return i===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(r===".nan")return NaN;const a=i*parseFloat(r);return Number.isFinite(a)?a:R}if(!oa.test(e))return R;const n=Number(e);return Number.isFinite(n)?n:R}function ua(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var pa=te("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:ca,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:ua}),fa=new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),da=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ma(e){if(!fa.test(e))return R;let t=e.toLowerCase().replace(/_/g,"");const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;let r=0;if(t.includes(":")){for(const i of t.split(":"))r=r*60+Number(i);r*=n}else r=n*parseFloat(t);return Number.isFinite(r)||da.test(e)?r:R}function ga(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var zt=te("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:ma,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:ga}),ha=te("tag:yaml.org,2002:merge",{implicit:!0,implicitFirstChars:["<"],resolve:(e,t)=>e==="<<"||t&&e===""?"<<":R,identify:()=>!1}),xa=/^[A-Za-z0-9+/]*={0,2}$/;function ba(e){const t=e.replace(/\s/g,"");if(t.length%4!==0||!xa.test(t))return R;const n=atob(t),r=new Uint8Array(n.length);for(let i=0;iObject.prototype.toString.call(e)==="[object Uint8Array]",represent:ya}),Na=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),Sa=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function En(e,t,n,r=0,i=0,a=0,l=0){const o=new Date(Date.UTC(e,t,n,r,i,a,l));return o.setUTCFullYear(e,t,n),o}function _a(e){let t=Na.exec(e);if(t===null&&(t=Sa.exec(e)),t===null)return R;const n=+t[1],r=+t[2]-1,i=+t[3];if(!t[4]){const u=En(n,r,i);return u.getUTCFullYear()!==n||u.getUTCMonth()!==r||u.getUTCDate()!==i?R:u}const a=+t[4],l=+t[5],o=+t[6];let c=0;if(a>23||l>59||o>59)return R;if(t[7]){let u=t[7].slice(0,3);for(;u.length<3;)u+="0";c=+u}const p=En(n,r,i,a,l,o,c);if(p.getUTCFullYear()!==n||p.getUTCMonth()!==r||p.getUTCDate()!==i)return R;if(t[9]){const u=+t[10],d=+(t[11]||0);if(u>23||d>59)return R;const m=(u*60+d)*6e4;p.setTime(p.getTime()-(t[9]==="-"?-m:m))}return p}var Ca=te("tag:yaml.org,2002:timestamp",{implicit:!0,implicitFirstChars:[..."0123456789"],resolve:_a,identify:e=>e instanceof Date,represent:e=>e.toISOString()}),$a=un("tag:yaml.org,2002:seq",{create:()=>[],addItem:(e,t)=>{e.push(t)},identify:Array.isArray});function St(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Mt(e,t){const n={};for(const r of t)e[r]!==void 0&&(n[r]=e[r]);return n}var Aa=un("tag:yaml.org,2002:omap",{create:()=>({list:[],seen:new Set}),addItem:(e,t)=>{let n;if(t instanceof Map){if(t.size!==1)return"cannot resolve an ordered map item";n=t.keys().next().value}else if(St(t)){const r=Object.keys(t);if(r.length!==1)return"cannot resolve an ordered map item";n=r[0]}else return"cannot resolve an ordered map item";return e.seen.has(n)?"duplicate key in ordered map":(e.seen.add(n),e.list.push(t),"")},finalize:e=>e.list,identify:()=>!1}),ja=un("tag:yaml.org,2002:pairs",{create:()=>[],addItem:(e,t)=>{if(t instanceof Map)return t.size!==1?"cannot resolve a pairs item":(e.push(t.entries().next().value),"");if(Object.prototype.toString.call(t)!=="[object Object]")return"cannot resolve a pairs item";const n=t,r=Object.keys(n);return r.length!==1?"cannot resolve a pairs item":(e.push([r[0],n[r[0]]]),"")},identify:()=>!1}),wa=Nt("tag:yaml.org,2002:map",{create:()=>({}),identify:St,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{if(t!==null&&typeof t=="object")return"object-based map does not support complex keys";const r=String(t);return r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,""},has:(e,t)=>t!==null&&typeof t=="object"?!1:Object.prototype.hasOwnProperty.call(e,String(t)),keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}}),Ea=Nt("tag:yaml.org,2002:set",{create:()=>new Set,identify:e=>e instanceof Set,represent:e=>{const t=new Map;for(const n of e)t.set(n,null);return t},addPair:(e,t,n)=>n!==null?"cannot resolve a set item":(e.add(t),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:()=>null});function ka(){return{scalar:Object.create(null),sequence:Object.create(null),mapping:Object.create(null)}}function Ta(){return{scalar:[],sequence:[],mapping:[]}}function Oa(e){const t=[];for(const n of e){let r=t.length;for(let i=0;iu.implicitFirstChars===null),o=new Set;for(const u of r)if(u.implicitFirstChars!==null)for(const d of u.implicitFirstChars)o.add(d);const c=new Map;for(const u of o)c.set(u,r.filter(d=>d.implicitFirstChars===null||d.implicitFirstChars.indexOf(u)!==-1));const p=i.scalar["tag:yaml.org,2002:str"];if(!p)throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)");this.tags=n,this.implicitScalarTags=r,this.implicitScalarByFirstChar=c,this.implicitScalarAnyFirstChar=l,this.defaultScalarTag=p,this.defaultSequenceTag=i.sequence["tag:yaml.org,2002:seq"],this.defaultMappingTag=i.mapping["tag:yaml.org,2002:map"],this.exact=i,this.prefix=a}lookupScalarTag(t){const n=this.exact.scalar[t];if(n)return n;for(const r of this.prefix.scalar)if(t.startsWith(r.tagName))return r}lookupSequenceTag(t){const n=this.exact.sequence[t];if(n)return n;for(const r of this.prefix.sequence)if(t.startsWith(r.tagName))return r}lookupMappingTag(t){const n=this.exact.mapping[t];if(n)return n;for(const r of this.prefix.mapping)if(t.startsWith(r.tagName))return r}resolveImplicitScalarTag(t){const n=this.implicitScalarByFirstChar.get(t.charAt(0))??this.implicitScalarAnyFirstChar;for(const i of n){const a=i.resolve(t,!1,i.tagName);if(a!==R)return{value:a,tag:i}}const r=this.defaultScalarTag;return{value:r.resolve(t,!1,r.tagName),tag:r}}withTags(...t){let n=[];for(const r of t)n=n.concat(r);return new pr([...this.tags,...n])}},pn=new _t([ki,$a,wa]);new _t([...pn.tags,Ii,Ki,Zi,pa]);var Ia=new _t([...pn.tags,Oi,Di,cr,ur]),La=new _t([...pn.tags,Fi,Wi,Vt,zt,Ca,ha,va,Aa,ja,Ea]),Fa=La.withTags({...Vt,resolve:(e,t,n)=>{const r=Vt.resolve(e,t,n);return r===R?cr.resolve(e,t,n):r}},{...zt,resolve:(e,t,n)=>{const r=zt.resolve(e,t,n);return r===R?ur.resolve(e,t,n):r}});Nt("tag:yaml.org,2002:map",{create:()=>new Map,addPair:(e,t,n)=>(e.set(t,n),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:(e,t)=>e.get(t),identify:e=>e instanceof Map||St(e),represent:e=>{if(e instanceof Map)return e;const t=new Map,n=e;for(const r of Object.keys(n))t.set(r,n[r]);return t}});function kn(e){if(Array.isArray(e)){const t=Array.prototype.slice.call(e);for(let n=0;n({}),identify:St,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{const r=kn(t);return r===null?"nested arrays are not supported inside keys":(r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,"")},has:(e,t)=>{const n=kn(t);return n!==null&&Object.prototype.hasOwnProperty.call(e,n)},keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}});var Ra={maxLength:79,indent:1,linesBefore:3,linesAfter:2};function Ft(e,t,n,r,i){let a="",l="";const o=Math.floor(i/2)-1;return r-t>o&&(a=" ... ",t=r-o+a.length),n-r>o&&(l=" ...",n=r+o-l.length),{str:a+e.slice(t,n).replace(/\t/g,"→")+l,pos:r-t+a.length}}function Rt(e,t){return" ".repeat(Math.max(t-e.length,0))+e}function Pa(e,t){if(!e.buffer)return null;const n={...Ra,...t},r=/\r?\n|\r|\0/g,i=[0],a=[];let l,o=-1;for(;l=r.exec(e.buffer);)a.push(l.index),i.push(l.index+l[0].length),e.position<=l.index&&o<0&&(o=i.length-2);o<0&&(o=i.length-1);let c="";const p=Math.min(e.line+n.linesAfter,a.length).toString().length,u=n.maxLength-(n.indent+p+3);for(let m=1;m<=n.linesBefore&&!(o-m<0);m++){const v=Ft(e.buffer,i[o-m],a[o-m],e.position-(i[o]-i[o-m]),u);c=`${" ".repeat(n.indent)}${Rt((e.line-m+1).toString(),p)} | ${v.str} +${c}`}const d=Ft(e.buffer,i[o],a[o],e.position,u);c+=`${" ".repeat(n.indent)}${Rt((e.line+1).toString(),p)} | ${d.str} +`,c+=`${"-".repeat(n.indent+p+3+d.pos)}^ +`;for(let m=1;m<=n.linesAfter&&!(o+m>=a.length);m++){const v=Ft(e.buffer,i[o+m],a[o+m],e.position-(i[o]-i[o+m]),u);c+=`${" ".repeat(n.indent)}${Rt((e.line+m+1).toString(),p)} | ${v.str} +`}return c.replace(/\n$/,"")}function Tn(e,t){let n="";return e.mark?(e.mark.name&&(n+=`in "${e.mark.name}" `),n+=`(${e.mark.line+1}:${e.mark.column+1})`,!t&&e.mark.snippet&&(n+=` + +${e.mark.snippet}`),`${e.reason} ${n}`):e.reason}var Ce=class fr extends Error{reason;mark;constructor(t,n){super(),this.name="YAMLException",this.reason=t,this.mark=n,this.message=Tn(this,!1),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(t){return`${this.name}: ${Tn(this,t)}`}static throwAt(t,n,r,i=""){let a=0,l=0;for(let c=0;c>10)+55296,(e-65536&1023)+56320)}function Ua(e){return e>=48&&e<=57?e-48:(e|32)-97+10}function Ka(e){return e===120?2:e===117?4:8}function dt(e,t,n){let r=0;for(;t0;p--){i++;const d=Ua(e.charCodeAt(i));u=(u<<4)+d}r+=Ba(u),i++}a=l=i}else if(o===10||o===13){r+=e.slice(a,l);const c=dt(e,i,n);r+=fn(c.breaks),i=a=l=c.position}else i++,o!==32&&o!==9&&(l=i)}return r+e.slice(a,n)}function In(e,t,n,r,i,a){const l=r<0?0:r,o=e.slice(t,n).replace(/\r\n?/g,` +`),c=o===""?[]:(o.endsWith(` +`)?o.slice(0,-1):o).split(` +`);let p="",u=!1,d=0,m=!1;for(const v of c){let x=0;for(;x=v.length){d++;continue}const S=v.slice(l),w=S.charCodeAt(0);a?w===32||w===9?(m=!0,p+=` +`.repeat(u?1+d:d)):m?(m=!1,p+=` +`.repeat(d+1)):d===0?u&&(p+=" "):p+=` +`.repeat(d):p+=` +`.repeat(u?1+d:d),p+=S,u=!0,d=0}return i===me.KEEP?p+=` +`.repeat(u?1+d:d):i!==me.STRIP&&u&&(p+=` +`),p}function Ga(e,t){if(t.valueStart===Da)return"";const{valueStart:n,valueEnd:r}=t;if(t.fast)return e.slice(n,r);switch(t.style){case j.SINGLE_QUOTED:return Ya(e,n,r);case j.DOUBLE_QUOTED:return Wa(e,n,r);case j.LITERAL_BLOCK:return In(e,n,r,t.indent,t.chomping,!1);case j.FOLDED_BLOCK:return In(e,n,r,t.indent,t.chomping,!0);default:return qa(e,n,r)}}var Va=Object.assign(Object.create(null),{"!":"!","!!":"tag:yaml.org,2002:"});function Pt(e){return encodeURI(e).replace(/!/g,"%21")}function gr(e,t){if(e.startsWith("!<")&&e.endsWith(">"))return decodeURIComponent(e.slice(2,-1));const n=e.indexOf("!",1),r=n===-1?"!":e.slice(0,n+1),i=t?.[r]??Va[r]??r;return decodeURIComponent(i)+decodeURIComponent(e.slice(r.length))}function hr(e){let t=e;return t.charCodeAt(0)===33?(t=t.slice(1),`!${Pt(t)}`):t.slice(0,18)==="tag:yaml.org,2002:"?`!!${Pt(t.slice(18))}`:`!<${Pt(t)}>`}var Ue=-1,za="tag:yaml.org,2002:merge",dn={filename:"",schema:Ia,json:!1,maxTotalMergeKeys:1e4,maxAliases:-1};function Ma(e){return"tagStart"in e&&e.tagStart!==Ue?e.tagStart:"anchorStart"in e&&e.anchorStart!==Ue?e.anchorStart:"valueStart"in e&&e.valueStart!==Ue?e.valueStart:"start"in e?e.start:0}function J(e,t){Ce.throwAt(e.source,e.position,t,e.filename)}function xr(e,t,n,r){try{return n.finalize(r)}catch(i){if(i instanceof Ce)throw i;Ce.throwAt(e.source,t,i instanceof Error?i.message:String(i),e.filename)}}function Ha(e,t){const n=Ga(e.source,t),r=t.tagStart===Ue?"":e.source.slice(t.tagStart,t.tagEnd),i=e.schema.defaultScalarTag;if(r!==""){if(r==="!")return{value:n,tag:i};const a=gr(r,e.tagHandlers),l=e.schema.lookupScalarTag(a);if(l){const c=l.resolve(n,!0,a);return c===R&&J(e,`cannot resolve a node with !<${a}> explicit tag`),{value:c,tag:l}}const o=e.schema.lookupMappingTag(a)??e.schema.lookupSequenceTag(a);if(o){n!==""&&J(e,`cannot resolve a node with !<${a}> explicit tag`);const c=o.create(a);return{value:o.carrierIsResult?c:xr(e,e.position,o,c),tag:o}}J(e,`unknown scalar tag !<${a}>`)}return t.style===j.PLAIN?e.schema.resolveImplicitScalarTag(n):{value:i.resolve(n,!1,i.tagName),tag:i}}function Ln(e,t,n){const r=t.tagStart===Ue?"":e.source.slice(t.tagStart,t.tagEnd);return r===""||r==="!"?n:gr(r,e.tagHandlers)}function br(e){return e.nodeKind==="mapping"}function Fn(e){e.totalMergeKeys++,e.maxTotalMergeKeys!==-1&&e.totalMergeKeys>e.maxTotalMergeKeys&&J(e,`merge keys exceeded maxTotalMergeKeys (${e.maxTotalMergeKeys})`)}function Rn(e,t,n,r){Fn(e);for(const i of r.keys(n)){if(Fn(e),t.tag.has(t.value,i))continue;const a=t.tag.addPair(t.value,i,r.get(n,i));a&&J(e,a),t.overridable??=new Set,t.overridable.add(i)}}function Qa(e,t,n,r){if(e.position=t.keyPosition,br(r))Rn(e,t,n,r);else if(r.nodeKind==="sequence"&&Array.isArray(n)){n.length>100&&J(e,"abnormal merge sequence size");for(const i of n){const a=e.nodeTags.get(i);a||J(e,"cannot merge mappings; the provided source object is unacceptable"),Rn(e,t,i,a)}}else J(e,"cannot merge mappings; the provided source object is unacceptable")}function Ja(e,t,n,r,i){if(e.position=t.keyPosition,t.keyIsMerge){Qa(e,t,r,i);return}!e.json&&t.tag.has(t.value,n)&&!t.overridable?.has(n)&&J(e,"duplicated mapping key");const a=t.tag.addPair(t.value,n,r);a&&J(e,a),t.overridable?.delete(n)}function Dt(e,t,n){const r=e.frames[e.frames.length-1];if(r.kind==="document")r.value=t,r.hasValue=!0;else if(r.kind==="sequence"){br(n)&&e.nodeTags.set(t,n);const i=r.tag.addItem(r.value,t,r.index++);i&&J(e,i)}else if(r.hasKey){const i=r.key;r.key=void 0,r.hasKey=!1,Ja(e,r,i,t,n)}else r.key=t,r.keyPosition=e.position,r.hasKey=!0,r.keyIsMerge=n.tagName===za}function Bt(e,t,n,r,i){if(t.anchorStart!==Ue){const a={value:n,tag:r,isValueFinal:i};return e.anchors.set(e.source.slice(t.anchorStart,t.anchorEnd),a),a}return null}function Xa(e,t){const n={...dn,...t,events:e,documents:[],eventIndex:0,position:0,frames:[],anchors:new Map,nodeTags:new Map,tagHandlers:Object.create(null),totalMergeKeys:0,aliasCount:0};for(;n.eventIndex`);const l=a.create(i),o=Bt(n,r,l,a,a.carrierIsResult);n.frames.push({kind:"sequence",position:n.position,value:l,tag:a,anchor:o,index:0});break}case Z.MAPPING:{const i=Ln(n,r,"tag:yaml.org,2002:map"),a=n.schema.lookupMappingTag(i);a||J(n,`unknown mapping tag !<${i}>`);const l=a.create(i),o=Bt(n,r,l,a,a.carrierIsResult);n.frames.push({kind:"mapping",position:n.position,value:l,tag:a,anchor:o,key:void 0,keyPosition:n.position,hasKey:!1,keyIsMerge:!1,overridable:null});break}case Z.ALIAS:{n.maxAliases!==-1&&++n.aliasCount>n.maxAliases&&J(n,`aliases exceeded maxAliases (${n.maxAliases})`);const i=n.source.slice(r.anchorStart,r.anchorEnd),a=n.anchors.get(i);a||J(n,`unidentified alias "${i}"`),a.isValueFinal||J(n,`recursive alias "${i}" is not supported for tag ${a.tag.tagName} because it uses finalize()`),Dt(n,a.value,a.tag);break}case Z.POP:{const i=n.frames.pop();if(i.kind==="mapping"&&i.hasKey&&(n.position=i.keyPosition,J(n,"incomplete mapping pair in event stream")),i.kind==="document")n.documents.push(i.value);else{const a=i.tag.carrierIsResult?i.value:xr(n,i.position,i.tag,i.value);i.anchor&&(i.anchor.value=a,i.anchor.isValueFinal=!0),Dt(n,a,i.tag)}break}}}return n.documents}var P=-1,yr=Object.prototype.hasOwnProperty,We=1,Ht=2,vr=3,mt=4,Za=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,es=/[,\[\]{}]/,Nr=/^(?:!|!!|![0-9A-Za-z-]+!)$/,Qt=String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$,_.!~*'()\[\]])`,Sr=String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$.~*'()_])`,ts=new RegExp(`^(?:${Qt})*$`),ns=new RegExp(`^(?:${Sr})+$`),rs=new RegExp(`^(?:!(?:${Qt})*|${Sr}(?:${Qt})*)$`),mn={filename:"",maxDepth:100};function is(e,t,n){e.events.push({type:Z.DOCUMENT,explicitStart:t,explicitEnd:n,directives:e.directives})}function _r(e,t,n,r,i,a,l){e.events.push({type:Z.SEQUENCE,start:t,anchorStart:n,anchorEnd:r,tagStart:i,tagEnd:a,style:l})}function Jt(e,t,n,r,i,a,l){e.events.push({type:Z.MAPPING,start:t,anchorStart:n,anchorEnd:r,tagStart:i,tagEnd:a,style:l})}function Pn(e,t){e.events.splice(t.eventsLength,0,{type:Z.MAPPING,start:t.position,anchorStart:P,anchorEnd:P,tagStart:P,tagEnd:P,style:ue.FLOW})}function ze(e,t,n,r,i,a,l,o,c=me.CLIP,p=-1,u=!1){e.events.push({type:Z.SCALAR,valueStart:t,valueEnd:n,anchorStart:r,anchorEnd:i,tagStart:a,tagEnd:l,style:o,chomping:c,indent:p,fast:u})}function as(e,t,n){e.events.push({type:Z.ALIAS,anchorStart:t,anchorEnd:n})}function Ke(e){e.events.push({type:Z.POP})}function re(e){ze(e,P,P,P,P,P,P,j.PLAIN)}function Dn(){return{anchorStart:P,anchorEnd:P,tagStart:P,tagEnd:P}}function qe(e){return{position:e.position,line:e.line,lineStart:e.lineStart,lineIndent:e.lineIndent,firstTabInLine:e.firstTabInLine,eventsLength:e.events.length}}function ke(e,t){e.position=t.position,e.line=t.line,e.lineStart=t.lineStart,e.lineIndent=t.lineIndent,e.firstTabInLine=t.firstTabInLine,e.events.length=t.eventsLength}function A(e,t){Ce.throwAt(e.input.slice(0,e.length),e.position,t,e.filename)}function M(e){return e===10||e===13}function Oe(e){return e===9||e===32}function fe(e){return Oe(e)||M(e)}function xe(e){return e===0||fe(e)}function Ie(e){return e===44||e===91||e===93||e===123||e===125}function ss(e){return e>=48&&e<=57?e-48:-1}function os(e){if(e>=48&&e<=57)return e-48;const t=e|32;return t>=97&&t<=102?t-97+10:-1}function ls(e){return e===120?2:e===117?4:e===85?8:0}function cs(e){return e===48||e===97||e===98||e===116||e===9||e===110||e===118||e===102||e===114||e===101||e===32||e===34||e===47||e===92||e===78||e===95||e===76||e===80}function gt(e){e.input.charCodeAt(e.position)===10?e.position++:(e.position++,e.input.charCodeAt(e.position)===10&&e.position++),e.line++,e.lineStart=e.position,e.lineIndent=0,e.firstTabInLine=-1}function ee(e,t){let n=0,r=e.input.charCodeAt(e.position),i=e.position===e.lineStart||fe(e.input.charCodeAt(e.position-1));for(;r!==0;){for(;Oe(r);)i=!0,r===9&&e.firstTabInLine===-1&&(e.firstTabInLine=e.position),r=e.input.charCodeAt(++e.position);if(t&&i&&r===35)do r=e.input.charCodeAt(++e.position);while(!M(r)&&r!==0);if(!M(r))break;for(gt(e),n++,i=!0,r=e.input.charCodeAt(e.position);r===32;)e.lineIndent++,r=e.input.charCodeAt(++e.position)}return n}function Ge(e,t=e.position){const n=e.input.charCodeAt(t);if((n===45||n===46)&&n===e.input.charCodeAt(t+1)&&n===e.input.charCodeAt(t+2)){const r=e.input.charCodeAt(t+3);return r===0||fe(r)}return!1}function Cr(e){e.position===e.lineStart&&e.input.charCodeAt(e.position)===65279&&(e.position++,e.lineStart=e.position)}function gn(e){if(e.position!==e.lineStart)return!1;if(Ge(e))return!0;if(e.input.charCodeAt(e.position)!==65279)return!1;const t=qe(e);Cr(e),ee(e,!0);const n=e.input.charCodeAt(e.position),r=e.position===e.lineStart&&(n===37||n===45&&Ge(e));return ke(e,t),r}function Bn(e){let t=e.input.charCodeAt(e.position);for(;t!==0&&!M(t);)t=e.input.charCodeAt(++e.position)}function $r(e,t,n){Za.test(e.input.slice(t,n))&&A(e,"the stream contains non-printable characters")}function us(e,t,n){if(e.input.charCodeAt(e.position)!==33)return!1;t.tagStart!==P&&A(e,"duplication of a tag property");const r=e.position;let i=!1,a=!1,l="!",o=e.input.charCodeAt(++e.position);o===60?(i=!0,o=e.input.charCodeAt(++e.position)):o===33&&(a=!0,l="!!",o=e.input.charCodeAt(++e.position));let c=e.position,p;if(i){for(;o!==0&&o!==62;)o=e.input.charCodeAt(++e.position);o!==62&&A(e,"unexpected end of the stream within a verbatim tag"),p=e.input.slice(c,e.position),e.position++}else{for(;o!==0&&!fe(o)&&!(n&&Ie(o));)o===33&&(a?A(e,"tag suffix cannot contain exclamation marks"):(l=e.input.slice(c-1,e.position+1),Nr.test(l)||A(e,"named tag handle cannot contain such characters"),a=!0,c=e.position+1)),o=e.input.charCodeAt(++e.position);p=e.input.slice(c,e.position),es.test(p)&&A(e,"tag suffix cannot contain flow indicator characters")}return p&&!(i?ts.test(p):ns.test(p))&&A(e,`tag name cannot contain such characters: ${p}`),!i&&l!=="!"&&l!=="!!"&&!yr.call(e.tagHandlers,l)&&A(e,`undeclared tag handle "${l}"`),t.tagStart=r,t.tagEnd=e.position,!0}function ps(e,t){if(e.input.charCodeAt(e.position)!==38)return!1;t.anchorStart!==P&&A(e,"duplication of an anchor property"),e.position++;const n=e.position;for(;e.input.charCodeAt(e.position)!==0&&!fe(e.input.charCodeAt(e.position))&&!Ie(e.input.charCodeAt(e.position));)e.position++;return e.position===n&&A(e,"name of an anchor node must contain at least one character"),t.anchorStart=n,t.anchorEnd=e.position,!0}function fs(e,t){if(e.input.charCodeAt(e.position)!==42)return!1;(t.anchorStart!==P||t.tagStart!==P)&&A(e,"alias node should not have any properties"),e.position++;const n=e.position;for(;e.input.charCodeAt(e.position)!==0&&!fe(e.input.charCodeAt(e.position))&&!Ie(e.input.charCodeAt(e.position));)e.position++;return e.position===n&&A(e,"name of an alias node must contain at least one character"),as(e,n,e.position),!0}function Xt(e,t){ee(e,!1),e.lineIndent0;)e.position++,os(e.input.charCodeAt(e.position))<0&&A(e,"expected hexadecimal character");e.position++}}else M(a)?(i=!1,Xt(e,t)):e.position===e.lineStart&&Ge(e)?A(e,"unexpected end of the document within a double quoted scalar"):a!==9&&a<32?A(e,"expected valid JSON character"):e.position++}A(e,"unexpected end of the stream within a double quoted scalar")}function gs(e,t,n){const r=e.input.charCodeAt(e.position);let i=me.CLIP,a=-1,l=!1;if(r!==124&&r!==62)return!1;const o=r===124?j.LITERAL_BLOCK:j.FOLDED_BLOCK;for(e.position++;e.input.charCodeAt(e.position)!==0;){const v=e.input.charCodeAt(e.position),x=ss(v);if(v===43||v===45)i!==me.CLIP&&A(e,"repeat of a chomping mode identifier"),i=v===43?me.KEEP:me.STRIP,e.position++;else if(x>=0)x===0&&A(e,"bad explicit indentation width of a block scalar; it cannot be less than one"),l&&A(e,"repeat of an indentation width identifier"),a=t+x-1,l=!0,e.position++;else break}let c=!1;for(;Oe(e.input.charCodeAt(e.position));)c=!0,e.position++;c&&e.input.charCodeAt(e.position)===35&&Bn(e),M(e.input.charCodeAt(e.position))?gt(e):e.input.charCodeAt(e.position)!==0&&A(e,"a line break is expected");let p=l?a:-1,u=0;const d=e.position;let m=e.position;for(;e.input.charCodeAt(e.position)!==0;){const v=e.position;let x=0;for(;e.input.charCodeAt(v+x)===32;)x++;const S=e.input.charCodeAt(v+x);if(S===0){p>=0?x>p&&(m=v+x):x>0&&(m=v+x);break}if(gn(e))break;if(!l&&p===-1&&M(S)&&(u=Math.max(u,x)),!l&&p===-1&&!M(S)&&(S===9&&x=t){c=!0,l=e.input.charCodeAt(e.position);continue}e.position=p,e.line=u,e.lineStart=d,e.lineIndent=m;break}}Oe(l)||(a=e.position+1),l=e.input.charCodeAt(++e.position)}return a===i?!1:($r(e,i,a),ze(e,i,a,r.anchorStart,r.anchorEnd,r.tagStart,r.tagEnd,j.PLAIN,me.CLIP,-1,!c),!0)}function He(e,t){const n=e.line;ee(e,!0),(e.line>n&&e.lineIndent0;if(e.firstTabInLine!==-1&&e.input.charCodeAt(e.position)===45&&xe(e.input.charCodeAt(e.position+1))&&A(e,"bad indentation of a sequence entry"),i&&e.lineIndent<=t?re(e):Te(e,t,vr,!1,!0),ee(e,!0),e.lineIndent=e.length)break;e.lineIndent>t&&A(e,"bad indentation of a sequence entry"),e.line===r&&e.input.charCodeAt(e.position)===45&&xe(e.input.charCodeAt(e.position+1))&&A(e,"bad indentation of a sequence entry")}return Ke(e),!0}function Ut(e,t,n,r){let i=!1,a=!1,l=!1,o=!1;if(e.firstTabInLine!==-1)return!1;let c=e.input.charCodeAt(e.position);for(;c!==0;){!i&&e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,A(e,"tab characters must not be used in indentation"));const p=e.input.charCodeAt(e.position+1),u=e.line;if((c===63||c===58)&&xe(p))l||(Jt(e,e.position,r.anchorStart,r.anchorEnd,r.tagStart,r.tagEnd,ue.BLOCK),l=!0),c===63?(i&&re(e),a=!0,i=!0):(i||(re(e),a=!0),i=!1),e.position+=1,o=!0;else{i&&(re(e),i=!1);const d=qe(e);if(!Te(e,n,Ht,!1,!0))break;if(e.line===u){for(c=e.input.charCodeAt(e.position);Oe(c);)c=e.input.charCodeAt(++e.position);if(c===58){if(c=e.input.charCodeAt(++e.position),xe(c)||A(e,"a whitespace character is expected after the key-value separator within a block mapping"),!l){for(ke(e,d),Jt(e,d.position,r.anchorStart,r.anchorEnd,r.tagStart,r.tagEnd,ue.BLOCK),l=!0,Te(e,n,Ht,!1,!0),c=e.input.charCodeAt(e.position);Oe(c);)c=e.input.charCodeAt(++e.position);e.position++}a=!0,i=!1,o=!1}else if(a)A(e,"expected ':' after a mapping key");else return r.anchorStart!==P||r.tagStart!==P?(ke(e,d),!1):!0}else if(a)A(e,"can not read a block mapping entry; a multiline key may not be an implicit key");else return r.anchorStart!==P||r.tagStart!==P?(ke(e,d),!1):!0}if(Te(e,t,mt,!0,o)&&(o=!1),i||o&&(re(e),o=!1),ee(e,!0),c=e.input.charCodeAt(e.position),(e.line===u||e.lineIndent>t)&&c!==0)A(e,"bad indentation of a mapping entry");else if(e.lineIndent=e.maxDepth&&A(e,`nesting exceeded maxDepth (${e.maxDepth})`),e.depth++;let l=1,o=!1,c=!1,p=null;const u=Dn();let d=n===mt||n===vr,m=d;const v=d;if(r&&ee(e,!0)&&(o=!0,e.lineIndent>t?l=1:e.lineIndent===t?l=0:l=-1),l===1)for(;;){const x=e.input.charCodeAt(e.position),S=qe(e);if(o&&l!==1&&(x===33||x===38))break;if(o&&v&&(u.tagStart!==P||u.anchorStart!==P)&&(x===33||x===38)){const w=qe(e),U=t+1;if(Ut(e,e.position-e.lineStart,U,u)&&e.events[w.eventsLength]?.type===Z.MAPPING)return e.depth--,!0;ke(e,w)}if(o&&(x===33&&u.tagStart!==P||x===38&&u.anchorStart!==P)||!us(e,u,n===We)&&!ps(e,u))break;p===null&&(p=S),ee(e,!0)?(o=!0,m=v,e.lineIndent>t?l=1:e.lineIndent===t?l=0:l=-1):m=!1}if(m&&(m=o||i),l===1||n===mt){const x=n===We||n===Ht?t:t+1,S=e.position-e.lineStart;if(l===1)if(m&&(Un(e,S,u)||Ut(e,S,x,u))||bs(e,x,u))c=!0;else{const w=e.input.charCodeAt(e.position);if(p!==null&&a&&v&&!m&&w!==124&&w!==62){const U=qe(e),D=p.position-p.lineStart;ke(e,p),Ut(e,D,x,Dn())&&e.events[U.eventsLength]?.type===Z.MAPPING?c=!0:ke(e,U)}!c&&(d&&gs(e,x,u)||ds(e,x,u)||ms(e,x,u)||fs(e,u)||xs(e,x,n,u))&&(c=!0)}else l===0&&(c=m&&Un(e,S,u))}return d=d&&!c,!c&&(u.anchorStart!==P||u.tagStart!==P||d)&&(ze(e,P,P,u.anchorStart,u.anchorEnd,u.tagStart,u.tagEnd,j.PLAIN),c=!0),e.depth--,c||u.anchorStart!==P||u.tagStart!==P}function ys(e){if(e.lineIndent>0||e.input.charCodeAt(e.position)!==37)return!1;e.position++;const t=e.position;for(;e.input.charCodeAt(e.position)!==0&&!fe(e.input.charCodeAt(e.position));)e.position++;const n=e.input.slice(t,e.position),r=[];for(n.length===0&&A(e,"directive name must not be less than one character in length");e.input.charCodeAt(e.position)!==0&&!M(e.input.charCodeAt(e.position));){for(;Oe(e.input.charCodeAt(e.position));)e.position++;if(e.input.charCodeAt(e.position)===35||M(e.input.charCodeAt(e.position))||e.input.charCodeAt(e.position)===0)break;const i=e.position;for(;e.input.charCodeAt(e.position)!==0&&!fe(e.input.charCodeAt(e.position));)e.position++;r.push(e.input.slice(i,e.position))}if(M(e.input.charCodeAt(e.position))&>(e),n==="YAML"){e.directives.some(a=>a.kind==="yaml")&&A(e,"duplication of %YAML directive"),r.length!==1&&A(e,"YAML directive accepts exactly one argument");const i=/^([0-9]+)\.([0-9]+)$/.exec(r[0]);i===null&&A(e,"ill-formed argument of the YAML directive"),parseInt(i[1],10)!==1&&A(e,"unacceptable YAML version of the document"),e.directives.push({kind:"yaml",version:r[0]})}else if(n==="TAG"){r.length!==2&&A(e,"TAG directive accepts exactly two arguments");const[i,a]=r;Nr.test(i)||A(e,"ill-formed tag handle (first argument) of the TAG directive"),yr.call(e.tagHandlers,i)&&A(e,`there is a previously declared suffix for "${i}" tag handle`),rs.test(a)||A(e,"ill-formed tag prefix (second argument) of the TAG directive"),e.tagHandlers[i]=a,e.directives.push({kind:"tag",handle:i,prefix:a})}return!0}function vs(e){e.directives=[],e.tagHandlers=Object.create(null);let t=!1;for(ee(e,!0);ys(e);)t=!0,ee(e,!0);let n=!1,r=!1,i=!0;if(e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45&&xe(e.input.charCodeAt(e.position+3))){n=!0;const o=e.line;e.position+=3,ee(e,!0),i=e.line>o}else t&&A(e,"directives end mark is expected");const a=e.events.length;if(!n&&e.position===e.lineStart&&e.input.charCodeAt(e.position)===46&&Ge(e)){e.position+=3,ee(e,!0);return}if(is(e,n,!1),Te(e,e.lineIndent-1,mt,!1,i,i)||re(e),ee(e,!0),e.position===e.lineStart&&Ge(e)&&(r=e.input.charCodeAt(e.position)===46,r)){const o=e.line;e.position+=3,ee(e,!0),e.line===o&&e.position=r.length));){const a=r.position;vs(r),r.position===a&&A(r,"can not read a document")}return r.events}var Ss={...mn,...dn};function _s(e,t={}){const n={...Ss,...t},r=String(e),i=Object.keys(mn),a=Object.keys(dn);return Xa(Ns(r,Mt(n,i)),{...Mt(n,a),source:r})}function Cs(e,t){const n=_s(e,t);if(n.length===0)throw new Ce("expected a document, but the input is empty");if(n.length===1)return n[0];throw new Ce("expected a single document in the stream, but found more")}var Ee=Symbol("INVALID");function $s(e){const t=new Set([e.defaultScalarTag,e.defaultSequenceTag,e.defaultMappingTag].filter(a=>a!==void 0)),n=e.implicitScalarTags,r=e.tags.filter(a=>!(a.nodeKind==="scalar"&&a.implicit)&&!t.has(a)),i=e.tags.filter(a=>t.has(a));return[...n.map(a=>({tag:a,implicitTag:!0})),...r.map(a=>({tag:a,implicitTag:!1})),...i.map(a=>({tag:a,implicitTag:!0}))]}function As(e,t){for(let n=0,r=e.representTypes.length;ni&&p[0]!==" "&&/ [^ \t]/.test(p)&&(l=!0),c===-1)break;a=c+1}l?e.style=j.FOLDED_BLOCK:n&&(e.style=j.LITERAL_BLOCK)}function Ls(e){e.style===j.PLAIN&&!Ct(e.allowedStylesMask,j.PLAIN)&&(e.style=jr(e))}function Fs(e){Ct(e.allowedStylesMask,e.style)||(e.style=j.DOUBLE_QUOTED)}function Qe(e,t){return e|1<'\"%@`]",Bs="[,\\[\\]{}]",Zt=$t,en=`(?:(?!${Bs})${$t})`,Us=`(?:(?:(?!${kr})${$t})|[?:-](?=${Zt}))`,Ks=`(?:(?:(?!${kr})${$t})|[?:-](?=${en}))`,Tr=`(?:(?:(?![:#])${Zt})|:(?=${Zt}))#*`,Or=`(?:(?:(?![:#])${en})|:(?=${en}))#*`,Ir=`(?:${hn}*${Tr})*`,Lr=`(?:${hn}*${Or})*`,Fr=`${Us}#*${Ir}`,Rr=`${Ks}#*${Lr}`,qs=Fr,Ys=Rr,Ws=`\\n+${Tr}${Ir}`,Gs=`\\n+${Or}${Lr}`,Vs=`${Fr}(?:${Ws})*`,zs=`${Rr}(?:${Gs})*`,Ms=new RegExp(`^(?:${Vs})$`,"u"),Hs=new RegExp(`^(?:${zs})$`,"u"),Qs=new RegExp(`^(?:${qs})$`,"u"),Js=new RegExp(`^(?:${Ys})$`,"u"),Xs=new RegExp(`^(?:${Er})*$`,"u"),Zs=new RegExp(`^(?:${Er}|\\n)*$`,"u"),eo=new RegExp(`^(?:${wr}|\\n)*$`,"u"),to=/^(?:---|\.\.\.)(?=$|[ \t\n\r])/,xn=/^(?:---|\.\.\.)(?=$|[ \t\n\r])/m;function no(e){const t=e.node.value;if(t!==""){if(!(e.isKey?e.flowOnly?Js:Qs:e.flowOnly?Hs:Ms).test(t)||e.shiftOfFirstLine===0&&to.test(t))return!1;if(e.shiftOfContent===0){const r=t.indexOf(` +`);if(r!==-1){const i=t.slice(r+1);if(xn.test(i))return!1}}}const n=e.presenterOptions.schema.resolveImplicitScalarTag(t).tag.tagName;return!(!e.node.tagged&&n!==e.node.tag||!e.node.tagged&&t==="="&&n===e.presenterOptions.schema.defaultScalarTag.tagName)}function ro(e){const t=e.node.value;if(!(e.isKey?Xs:Zs).test(t)||/[ \t]\n|\n[ \t]/.test(t))return!1;if(!e.isKey&&e.shiftOfContent===0){const n=t.indexOf(` +`);if(n!==-1&&xn.test(t.slice(n+1)))return!1}return!0}function io(e){if(e.flowOnly||!eo.test(e.node.value))return!1;const t=e.shiftOfContent-e.shiftOfParent;return!(t<1||t>9&&/^\n* /.test(e.node.value)||e.shiftOfContent===0&&xn.test(e.node.value))}function ao(e){let t=Qe(0,j.DOUBLE_QUOTED);no(e)&&(t=Qe(t,j.PLAIN)),ro(e)&&(t=Qe(t,j.SINGLE_QUOTED)),io(e)&&(t=Qe(Qe(t,j.LITERAL_BLOCK),j.FOLDED_BLOCK)),e.allowedStylesMask=t}function so(e){switch(e.style){case j.PLAIN:return oo(e);case j.SINGLE_QUOTED:return lo(e);case j.LITERAL_BLOCK:return co(e);case j.FOLDED_BLOCK:return uo(e);case j.DOUBLE_QUOTED:return po(e)}}function oo(e){return Pr(e.node.value,e.shiftOfContent)}function lo(e){return`'${Pr(e.node.value,e.shiftOfContent).replace(/'/g,"''")}'`}function co(e){const t=e.node.value;return"|"+Br(t,e.shiftOfParent,e.shiftOfContent)+Ur(Dr(t,e.shiftOfContent))}function uo(e){const t=e.node.value,n=e.presenterOptions.lineWidth;let r=1/0;return n!==-1&&(r=Math.max(Math.min(n,40),n-e.shiftOfContent)),">"+Br(t,e.shiftOfParent,e.shiftOfContent)+Ur(Dr(mo(t,r),e.shiftOfContent))}function po(e){return`"${xo(e.node.value)}"`}function Pr(e,t){let n=e.indexOf(` +`);if(n===-1)return e;const r=" ".repeat(t);let i=e.slice(0,n);const a=/(\n+)([^\n]*)/g;a.lastIndex=n;let l;for(;l=a.exec(e);){const o=l[1].length,c=l[2];i+=` +`.repeat(o+1)+r+c}return i}function Dr(e,t){const n=" ".repeat(t);let r=0,i="";const a=e.length;for(;rt&&(a=l>i?l:o,c+=` +${e.slice(i,a)}`,i=a+1),l=o;return c+=` +`,e.length-i>t&&l>i?c+=`${e.slice(i,l)} +${e.slice(l+1)}`:c+=e.slice(i),c.slice(1)}function mo(e,t){const n=/(\n+)([^\n]*)/g;let r=e.indexOf(` +`);r===-1&&(r=e.length),n.lastIndex=r;let i=Yn(e.slice(0,r),t),a=e[0]===` +`||tn(e[0]),l,o;for(;o=n.exec(e);){const c=o[1],p=o[2];l=p!==""&&tn(p[0]),i+=c+(!a&&!l&&p!==""?` +`:"")+Yn(p,t),a=l}return i}var go=/["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu;function ho(e){switch(e){case"\0":return"\\0";case"\x07":return"\\a";case"\b":return"\\b";case" ":return"\\t";case` +`:return"\\n";case"\v":return"\\v";case"\f":return"\\f";case"\r":return"\\r";case"\x1B":return"\\e";case'"':return'\\"';case"\\":return"\\\\";case"…":return"\\N";case" ":return"\\_";case"\u2028":return"\\L";case"\u2029":return"\\P"}const t=e.charCodeAt(0),n=t.toString(16).toUpperCase();return t<=255?`\\x${"0".repeat(2-n.length)}${n}`:`\\u${"0".repeat(4-n.length)}${n}`}function xo(e){return e.replace(go,ho)}var ht=10,bn={indent:2,seqNoIndent:!1,seqInlineFirst:!0,lineWidth:80,flowBracketPadding:!1,flowSkipCommaSpace:!1,flowSkipColonSpace:!1,quoteFlowKeys:!1,quoteStyle:"single",forceQuotes:!1,scalarStyleRules:Object.keys(qn).map(e=>Reflect.get(qn,e)),tagBeforeAnchor:!1};function bo(e){return e.tagged?e.tag:hr(e.tag)}function yo(e){const t={...bn,...e};return t.flowSkipColonSpace&&(t.quoteFlowKeys=!0),{...t,defaultScalarTagName:t.schema.defaultScalarTag.tagName,openEnded:!1}}function nn(e,t){return` +${" ".repeat(e.indent*t)}`}function vo(e,t,n,r,i,a){return{node:t,parent:n,level:r,isKey:i,flowOnly:a,shiftOfParent:r===0?-1:e.indent*(r-1),shiftOfContent:e.indent*Math.max(1,r),shiftOfFirstLine:r===0?0:e.indent*r,presenterOptions:e,allowedStylesMask:0,style:t.style}}function No(e,t,n){let r="";for(let a=0,l=n.items.length;a0&&(r+=`,${e.flowSkipCommaSpace?"":" "}`),r+=o}const i=e.flowBracketPadding&&n.items.length>0?" ":"";return`[${i}${r}${i}]`}function Wn(e,t,n,r){let i="";for(let a=0,l=n.items.length;a1024&&/^[\s\S]{1025}/u.test(m),S=u||v||x;S&&(m&&ht===m.charCodeAt(0)?o+="?":o+="? "),o+=m,S&&(o+=nn(e,t));const w=be(e,t+1,p,n,{block:!0,compact:S,isblockseq:S&&!rn(e,p,t+1)}).text,U=c.kind==="scalar"&&d.noBody&&(c.tagged||c.anchor!==void 0),D=!S&&(c.kind==="alias"||U)?" ":"";w===""||ht===w.charCodeAt(0)?o+=`${D}:`:o+=`${D}: `,o+=w,i+=o}return i}function rn(e,t,n){return t.kind==="alias"?!0:t.tagged||t.anchor!==void 0||e.indent<2&&n>0}function be(e,t,n,r,i){if(n.kind==="alias")return e.openEnded=!1,{text:`*${n.anchor}`,noBody:!1};const{block:a=!1,iskey:l=!1,isblockseq:o=!1}=i;let c=i.compact??!1;const p=n.anchor!==void 0;rn(e,n,t)&&(c=!1);let u,d=n.tagged;const m=a&&(n.kind==="mapping"||n.kind==="sequence")&&n.style===ue.BLOCK&&n.items.length!==0;if(n.kind==="mapping")m?u=_o(e,t,n,c):u=So(e,t,n);else if(n.kind==="sequence")m?e.seqNoIndent&&!o&&t>0?u=Wn(e,t-1,n,c):u=Wn(e,t,n,c):u=No(e,t,n);else{const S=vo(e,n,r,t,l,!a);ao(S);for(const w of e.scalarStyleRules)w(S);u=so(S),e.openEnded=(S.style===j.LITERAL_BLOCK||S.style===j.FOLDED_BLOCK)&&(n.value===` +`||n.value.endsWith(` + +`)),d=n.tagged||u===""&&S.flowOnly&&r?.kind==="sequence"&&!p||S.style!==j.PLAIN&&n.tag!==e.defaultScalarTagName}(n.kind==="mapping"||n.kind==="sequence")&&!m&&(e.openEnded=!1),m&&c&&t>0&&e.indent>2&&(u=`${" ".repeat(e.indent-2)}${u}`);const v=u==="";let x=u;if(d||p){const S=[],w=d?bo(n):null,U=p?`&${n.anchor}`:null;e.tagBeforeAnchor?(w!==null&&S.push(w),U!==null&&S.push(U)):(U!==null&&S.push(U),w!==null&&S.push(w));const D=u===""||u.charCodeAt(0)===ht?"":" ";x=`${S.join(" ")}${D}${u}`}return{text:x,noBody:v}}function Co(e){return(e.kind==="sequence"||e.kind==="mapping")&&e.style===ue.BLOCK&&e.items.length!==0&&!e.tagged&&e.anchor===void 0}function $o(e){let t="";for(const n of e.directives){if(n.kind==="yaml"){t+=`%YAML ${n.version} +`;continue}const{handle:r,prefix:i}=n;t+=`%TAG ${r} ${i} +`}return t}function Ao(e,t){const n=yo(t);let r="",i=!1;for(let a=0;a0&&!i;if(r+=o,l.contents===null)p&&(r+=`--- +`);else if(p){const u=be(n,0,l.contents,null,{block:!0,compact:!0}).text,d=u===""?"":c||Co(l.contents)?` +`:" ";r+=`---${d}${u} +`}else r+=be(n,0,l.contents,null,{block:!0,compact:!0}).text+` +`;i=l.explicitEnd||n.openEnded,i&&(r+=`... +`)}return r}var jo={...bn,schema:Fa,skipInvalid:!1,noRefs:!1,flowLevel:-1,sortKeys:!1,transform:()=>{}};function wo(e,t){const n=String(e),r=String(t);return nr?1:0}function Eo(e,t={}){const n={...jo,...t},r=js(e,n.schema,{noRefs:n.noRefs,skipInvalid:n.skipInvalid});if(n.flowLevel>=0&&Kn(r,(i,a)=>{if(!(a.depth{a.kind==="mapping"&&a.items.sort((l,o)=>i(l.key.kind==="scalar"?l.key.value:"",o.key.kind==="scalar"?o.key.value:""))})}return n.transform(r),Ao(r,{...Mt(n,Object.keys(bn)),schema:n.schema})}const Q=[];for(let e=0;e<256;++e)Q.push((e+256).toString(16).slice(1));function ko(e,t=0){return(Q[e[t+0]]+Q[e[t+1]]+Q[e[t+2]]+Q[e[t+3]]+"-"+Q[e[t+4]]+Q[e[t+5]]+"-"+Q[e[t+6]]+Q[e[t+7]]+"-"+Q[e[t+8]]+Q[e[t+9]]+"-"+Q[e[t+10]]+Q[e[t+11]]+Q[e[t+12]]+Q[e[t+13]]+Q[e[t+14]]+Q[e[t+15]]).toLowerCase()}const To=new Uint8Array(16);function Oo(){return crypto.getRandomValues(To)}function Kr(e,t,n){return crypto.randomUUID?crypto.randomUUID():Io(e)}function Io(e,t,n){e=e||{};const r=e.random??e.rng?.()??Oo();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,ko(r)}function Lo(){return{name:"my_pipeline",description:"",version:"1.0.0",on_error:"fail_fast",timeout:300,strict_schema:!1,input_schema:{},output_schema:{},defaults:{},metadata:{}}}function Kt(){return{meta:Lo(),steps:[]}}function At(e,t){return{id:Kr(),kind:e,name:t,config:Gt(e,t),children:Ei(e,t)}}function Ve(e,t){const n=new Set(t);let r=e,i=2;for(;n.has(r);)r=`${e}_${i}`,i+=1;return r}function Fo(e){if(e&&typeof e=="object"){if(typeof e.step_type=="string"&&["agent","plugin","endpoint","ingestion","transform","parallel","map","loop","sub_pipeline"].includes(e.step_type))return e.step_type;if(e.agent!==void 0)return"agent";if(e.plugin!==void 0)return"plugin";if(e.endpoint!==void 0)return"endpoint";if(e.ingestion!==void 0)return"ingestion";if(e.transform!==void 0)return"transform";if(e.parallel!==void 0)return"parallel";if(e.map!==void 0)return"map";if(e.loop!==void 0)return"loop";if(e.sub_pipeline!==void 0)return"sub_pipeline"}return null}function G(e){return!e||typeof e!="object"||Array.isArray(e)?{}:typeof e.mappings=="object"&&e.mappings!==null&&!Array.isArray(e.mappings)?{...e.mappings}:{...e}}function an(e){const t=Fo(e)??"agent",n=typeof e.name=="string"&&e.name?e.name:t,r={...e,name:n};t==="ingestion"&&r.ingestion===void 0&&typeof e.ingestor=="string"&&(r.ingestion=e.ingestor),delete r.ingestor,delete r.step_type;let i=[];if(t==="parallel"&&Array.isArray(e.parallel?.steps))i=e.parallel.steps.map(a=>an(a));else if(t==="loop"&&e.loop&&typeof e.loop=="object"){const a=e.loop.step&&typeof e.loop.step=="object"?e.loop.step:{};i=[an(a)]}for(const a of["input","output"])r[a]!==void 0&&(r[a]=G(r[a]));if(t==="map"&&r.map&&typeof r.map=="object")for(const a of["input","output"])r.map[a]!==void 0&&(r.map[a]=G(r.map[a]));return{id:Kr(),kind:t,name:n,config:r,children:i}}function qr(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(t.steps)?t.steps:[];return{meta:{name:typeof t.name=="string"&&t.name?t.name:"my_pipeline",description:typeof t.description=="string"?t.description:"",version:typeof t.version=="string"?t.version:"1.0.0",on_error:["fail_fast","continue","rollback"].includes(t.on_error)?t.on_error:"fail_fast",timeout:typeof t.timeout=="number"?t.timeout:300,strict_schema:!!t.strict_schema,input_schema:t.input_schema&&typeof t.input_schema=="object"?t.input_schema:{},output_schema:t.output_schema&&typeof t.output_schema=="object"?t.output_schema:{},defaults:t.defaults&&typeof t.defaults=="object"?t.defaults:{},metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{}},steps:n.map(i=>an(i))}}const Ze={agent:30,plugin:30,endpoint:30,ingestion:300,transform:10,parallel:60,map:120,loop:120,sub_pipeline:120};function xt(e){if(!(!e||Object.keys(e).length===0))return{...e}}function Yr(e){if(!e||typeof e!="object")return;const t={};return e.max_attempts!==void 0&&(t.max_attempts=e.max_attempts),e.backoff&&(t.backoff=e.backoff),e.base_delay!==void 0&&(t.base_delay=e.base_delay),Object.keys(t).length>0?t:void 0}function Gn(e,t){const n=e.kind,r=e.config,i=xt(r.input);i&&(t.input=i);const a=xt(r.output);a&&(t.output=a),typeof r.condition=="string"&&r.condition.trim()&&(t.condition=r.condition),r.on_error&&r.on_error!=="fail"&&(t.on_error=r.on_error),r.fallback_agent&&(t.fallback_agent=r.fallback_agent),Array.isArray(r.upstreams)&&r.upstreams.length>0&&(t.upstreams=[...r.upstreams]);const l=Yr(r.retry);return l&&(t.retry=l),typeof r.timeout=="number"&&r.timeout!==Ze[n]&&(t.timeout=r.timeout),r.metadata&&typeof r.metadata=="object"&&Object.keys(r.metadata).length>0&&(t.metadata={...r.metadata}),typeof r.rollback=="string"&&r.rollback.trim()&&(t.rollback=r.rollback),t}function sn(e){const t=e.kind,n=e.config;if(t==="transform"){const a={name:e.name,transform:n.transform??""};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(a.upstreams=[...n.upstreams]),typeof n.condition=="string"&&n.condition.trim()&&(a.condition=n.condition),n.on_error&&n.on_error!=="fail"&&(a.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Ze.transform&&(a.timeout=n.timeout),a}if(t==="parallel"){const a={steps:e.children.map(o=>sn(o))};n.parallel?.strategy&&n.parallel.strategy!=="all"&&(a.strategy=n.parallel.strategy),typeof n.parallel?.max_concurrency=="number"&&n.parallel.max_concurrency!==5&&(a.max_concurrency=n.parallel.max_concurrency);const l={name:e.name,parallel:a};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(l.upstreams=[...n.upstreams]),n.on_error&&n.on_error!=="fail"&&(l.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Ze.parallel&&(l.timeout=n.timeout),l}if(t==="map"){const a=n.map&&typeof n.map=="object"?n.map:{},l={agent:typeof a.agent=="string"?a.agent:"",items:typeof a.items=="string"?a.items:""};a.item_key&&a.item_key!=="item"&&(l.item_key=a.item_key),a.index_key&&a.index_key!=="index"&&(l.index_key=a.index_key);const o=xt(a.input);o&&(l.input=o);const c=xt(a.output);c&&(l.output=c),typeof a.max_concurrency=="number"&&a.max_concurrency!==4&&(l.max_concurrency=a.max_concurrency),a.strategy&&a.strategy!=="all"&&(l.strategy=a.strategy);const p=Yr(a.retry);p&&(l.retry=p),typeof a.item_timeout=="number"&&a.item_timeout!==60&&(l.item_timeout=a.item_timeout),a.fallback_agent&&(l.fallback_agent=a.fallback_agent);const u={name:e.name,map:l};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(u.upstreams=[...n.upstreams]),typeof n.condition=="string"&&n.condition.trim()&&(u.condition=n.condition),n.on_error&&n.on_error!=="fail"&&(u.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Ze.map&&(u.timeout=n.timeout),n.metadata&&typeof n.metadata=="object"&&Object.keys(n.metadata).length>0&&(u.metadata={...n.metadata}),typeof n.rollback=="string"&&n.rollback.trim()&&(u.rollback=n.rollback),u}if(t==="loop"){const a=e.children[0],l={step:a?sn(a):{name:"",agent:""}};typeof n.loop?.max_iterations=="number"&&n.loop.max_iterations!==10&&(l.max_iterations=n.loop.max_iterations),typeof n.loop?.until=="string"&&n.loop.until.trim()&&(l.until=n.loop.until);const o={name:e.name,loop:l};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(o.upstreams=[...n.upstreams]),n.on_error&&n.on_error!=="fail"&&(o.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Ze.loop&&(o.timeout=n.timeout),o}if(t==="sub_pipeline"){const a={name:e.name,sub_pipeline:n.sub_pipeline??""};return Gn(e,a)}const r={agent:"agent",plugin:"plugin",endpoint:"endpoint",ingestion:"ingestion"},i={name:e.name,[r[t]]:typeof n[r[t]]=="string"?n[r[t]]:""};return Gn(e,i)}function pt(e){const t=e.meta,n={name:t.name,steps:e.steps.map(r=>sn(r))};return t.description&&(n.description=t.description),t.version&&t.version!=="1.0.0"&&(n.version=t.version),Object.keys(t.input_schema).length>0&&(n.input_schema=t.input_schema),Object.keys(t.output_schema).length>0&&(n.output_schema=t.output_schema),Object.keys(t.defaults).length>0&&(n.defaults=t.defaults),t.on_error&&t.on_error!=="fail_fast"&&(n.on_error=t.on_error),t.strict_schema&&(n.strict_schema=!0),t.timeout!==300&&(n.timeout=t.timeout),Object.keys(t.metadata).length>0&&(n.metadata=t.metadata),n}function Ro(e){return Eo(pt(e),{noRefs:!0})}function Po(e){let t;try{t=Cs(e)}catch(n){throw new Error(`Invalid YAML: ${n?.message??String(n)}`)}if(!t||typeof t!="object"||!Array.isArray(t.steps))throw new Error('YAML must be a pipeline mapping with a "steps" list');return qr(t)}function Do(e,t,n,r){const i=e.steps.map(a=>{if(a.id!==t)return a;if(n.length===0)return{...a,config:{...r,name:a.name}};const l=a.children.map(o=>o.id!==n[0]?o:{...o,config:{...r,name:o.name}});return{...a,children:l}});return{...e,steps:i}}function Bo(e,t,n,r){const i=e.steps.map(l=>l.name),a=e.steps.map(l=>{if(l.id!==t)return l;if(n.length===0){const p=Ve(r||l.name,i.filter(u=>u!==l.name));return{...l,name:p,config:{...l.config,name:p}}}const o=l.children.map(p=>p.name),c=l.children.map(p=>{if(p.id!==n[0])return p;const u=Ve(r||p.name,o.filter(d=>d!==p.name));return{...p,name:u,config:{...p.config,name:u}}});return{...l,children:c}});return{...e,steps:a}}function Wr(e,t){return{...e,meta:t}}function Uo(e,t){const n=Ve(t==="sub_pipeline"?"sub":t,e.steps.map(r=>r.name));return{...e,steps:[...e.steps,At(t,n)]}}function Vn(e,t,n){const r=Ve(n||t,e.steps.map(l=>l.name)),i=At(t,r),a={agent:"agent",plugin:"plugin",endpoint:"endpoint",ingestion:"ingestion",sub_pipeline:"sub_pipeline"};return{...e,steps:[...e.steps,{...i,config:{...i.config,[a[t]]:n}}]}}function Ko(e,t){return{...e,steps:e.steps.filter(n=>n.id!==t)}}function zn(e,t,n,r){const i=a=>{const l=[...a],[o]=l.splice(t,1);if(!o)return a;const c=Math.max(0,Math.min(n,l.length));return l.splice(c,0,o),l};return r?{...e,steps:e.steps.map(a=>a.id===r?{...a,children:i(a.children)}:a)}:{...e,steps:i(e.steps)}}function qo(e,t){const n=e.steps.map(r=>{if(r.id!==t)return r;const i="agent",a=Ve("child",r.children.map(o=>o.name)),l=At(i,a);return{...r,children:[...r.children,l]}});return{...e,steps:n}}function Yo(e,t,n){const r=e.steps.map(i=>{if(i.id!==t)return i;const a=i.children.filter(l=>l.id!==n);return i.kind==="loop"&&a.length===0?{...i,children:[At("agent",Ve("child",[]))]}:{...i,children:a}});return{...e,steps:r}}const qt=["input","defaults","context","current","steps"];function Wo(e,t){const n=[],r=(i,a,l)=>{const o=G(i);Object.keys(o).length>0&&n.push({label:`Step '${e.name}' ${a} mapping`,mapping:o,isInput:l,index:t})};r(e.config.input,"input",!0),r(e.config.output,"output",!1),e.kind==="map"&&e.config.map&&typeof e.config.map=="object"&&(r(e.config.map.input,"input",!0),r(e.config.map.output,"output",!1));for(const i of e.children)r(i.config.input,"input",!0),r(i.config.output,"output",!1);return n}function Go(e,t,n,r,i,a,l,o){if(typeof e!="string"||!e.startsWith("$"))return;const c=e.replace(/^\$\.?/,"").split(".").filter(u=>u.length>0);if(!n){c.length>0&&qt.includes(c[0])&&l.push({stepName:o,severity:"warning",message:`${t}: output mapping '${e}' starts with '${c[0]}' — output mappings resolve against this step's own output, not the pipeline context`});return}if(c.length===0){l.push({stepName:o,severity:"warning",message:`${t}: expression '${e}' resolves to nothing — use a path like '$.input.query'`});return}const p=c[0];if(!qt.includes(p)){l.push({stepName:o,severity:"error",message:`${t}: unknown mapping root '${p}' in '${e}' (expected one of: ${qt.join(", ")})`});return}if(p==="steps"&&c.length>=2){const u=c[1].split("[")[0];if(u!=="*"){const d=i.indexOf(u);d===-1?l.push({stepName:o,severity:"error",message:`${t}: '${e}' references step '${u}' which does not exist in the pipeline`}):d>=r&&!a.has(u)&&l.push({stepName:o,severity:"error",message:`${t}: '${e}' references step '${u}' which runs after this step — move it earlier or declare it in upstreams`})}}}function ot(e,t,n,r){const i=e.on_error;i==="skip"?n.push({stepName:r,severity:"warning",message:`${t} uses on_error=skip — failures will be silently ignored`}):i==="retry"&&!e.retry?n.push({stepName:r,severity:"warning",message:`${t} uses on_error=retry but has no retry config`}):i==="fallback"&&!e.fallback_agent&&n.push({stepName:r,severity:"warning",message:`${t} uses on_error=fallback but has no fallback_agent`})}function Vo(e,t,n,r){const i=`Step '${e.name}'`,a=e.config,l=new Set(et(e));for(const o of et(e))o===e.name?r.push({stepName:e.name,severity:"error",message:`${i} cannot depend on itself`}):n.includes(o)||r.push({stepName:e.name,severity:"error",message:`${i} references unknown upstream '${o}'`});switch(e.kind){case"agent":a.agent||r.push({stepName:e.name,severity:"error",message:`${i} has no agent selected`});break;case"plugin":a.plugin||r.push({stepName:e.name,severity:"error",message:`${i} has no plugin selected`});break;case"endpoint":a.endpoint||r.push({stepName:e.name,severity:"error",message:`${i} has no endpoint selected`});break;case"ingestion":a.ingestion||r.push({stepName:e.name,severity:"error",message:`${i} has no ingestor selected`});break;case"sub_pipeline":a.sub_pipeline||r.push({stepName:e.name,severity:"error",message:`${i} has no pipeline selected`});break;case"transform":!a.transform||!String(a.transform).trim()?r.push({stepName:e.name,severity:"error",message:`${i} has no transform code`}):String(a.transform).includes("return")||r.push({stepName:e.name,severity:"warning",message:`${i} transform code does not contain a 'return' — the step will produce no output`});break;case"parallel":e.children.length===0&&r.push({stepName:e.name,severity:"error",message:`${i} has no steps — add at least one agent step`});for(const o of e.children)o.config.agent||r.push({stepName:o.name,severity:"error",message:`Step '${o.name}' (inside parallel '${e.name}') has no agent selected`}),et(o).length>0&&r.push({stepName:o.name,severity:"warning",message:`Step '${o.name}' (inside parallel '${e.name}') declares upstreams — nested steps are not independently scheduled; declare the dependency on the container step instead`}),ot(o.config,`Step '${o.name}' (inside parallel '${e.name}')`,r,o.name);break;case"map":{const o=a.map&&typeof a.map=="object"?a.map:{};o.agent||r.push({stepName:e.name,severity:"error",message:`${i} has no agent selected`}),o.items||r.push({stepName:e.name,severity:"error",message:`${i} has no items expression`}),ot(o,i,r,e.name);break}case"loop":if(e.children.length!==1)r.push({stepName:e.name,severity:"error",message:`${i} must contain exactly one agent step`});else{const o=e.children[0];o.config.agent||r.push({stepName:o.name,severity:"error",message:`Step '${o.name}' (inside loop '${e.name}') has no agent selected`}),et(o).length>0&&r.push({stepName:o.name,severity:"warning",message:`Step '${o.name}' (inside loop '${e.name}') declares upstreams — nested steps are not independently scheduled; declare the dependency on the container step instead`}),ot(o.config,`Step '${o.name}' (inside loop '${e.name}')`,r,o.name)}break}e.kind!=="parallel"&&e.kind!=="loop"&&ot(a,i,r,e.name);for(const o of Wo(e,t))for(const[c,p]of Object.entries(o.mapping))Go(p,`${o.label} '${c}'`,o.isInput,o.index,n,l,r,e.name)}function et(e){const t=e.config.upstreams;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function zo(e){const t=e.map(c=>c.name),n=new Map;t.forEach((c,p)=>{n.has(c)||n.set(c,p)});const r=new Array(e.length).fill(0),i=e.map(()=>[]);for(let c=0;c0;){const c=a.shift();l.add(c);for(const p of i[c])r[p]-=1,r[p]===0&&a.push(p)}const o=e.map((c,p)=>p).filter(c=>!l.has(c));return o.length>0?o.map(c=>t[c]):null}function Mn(e){const t=[],n=e.meta;if(!n.name||!n.name.trim()?t.push({severity:"error",message:"Pipeline name is required"}):/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(n.name)||t.push({severity:"error",message:"Invalid pipeline name — use letters, digits, '_', '-', '.'"}),e.steps.length===0)return t.push({severity:"error",message:"Add at least one step to the pipeline"}),t;const r=e.steps.map(l=>l.name),i=new Set;for(const l of r)!l||!l.trim()?t.push({severity:"error",message:"Every step needs a name"}):i.has(l)&&t.push({severity:"error",message:`Duplicate step name: '${l}'`}),i.add(l);e.steps.forEach((l,o)=>Vo(l,o,r,t));const a=zo(e.steps);return a&&t.push({severity:"error",message:`Cycle detected in upstream dependencies involving steps: ${a.join(", ")}`}),t}const Hn=/Step '([^']+)'/g;function Mo(e,t,n){const r=[...e];for(const[i,a]of[[t,"error"],[n,"warning"]])for(const l of i){const o=Hn.exec(l);Hn.lastIndex=0,r.push({message:l,severity:a,stepName:o?o[1]:void 0})}return r}function Ho(e){const t={};for(const n of e){if(!n.stepName)continue;const r=t[n.stepName]??{errors:0,warnings:0};n.severity==="error"?r.errors+=1:r.warnings+=1,t[n.stepName]=r}return t}const Qn="application/x-agentomatic-step-kind",Jn="application/x-agentomatic-resource",Gr={agent:bi,plugin:xi,endpoint:hi,ingestion:gi,transform:mi,parallel:di,map:fi,loop:pi,sub_pipeline:ui},Vr={agent:"text-blue-500",plugin:"text-purple-500",endpoint:"text-emerald-500",ingestion:"text-teal-500",transform:"text-amber-500",parallel:"text-pink-500",map:"text-indigo-500",loop:"text-orange-500",sub_pipeline:"text-cyan-500"};function bt(e,t){const n=e[t];return typeof n=="string"?n:""}function yt(e){return e.map&&typeof e.map=="object"?e.map:{}}function Xn(e){if(!e||typeof e!="object"||Array.isArray(e))return 0;const t=e,n=t.mappings;return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).length:Object.keys(t).length}function Qo(e){const t=e.kind==="map"?yt(e.config).input:e.config.input;if(!t||typeof t!="object"||Array.isArray(t))return[];const n=t,r=n.mappings&&typeof n.mappings=="object"&&!Array.isArray(n.mappings)?n.mappings:n;return Object.entries(r).filter(([,i])=>typeof i=="string"&&i.length>0).map(([i,a])=>({target:i==="__root__"?"Request body":i,source:String(a).replace(/^\$\.steps\./,"").replace(/^\$\.input\./,"input · ").replace(/^\$\.defaults\./,"defaults · ")}))}function Jo(e){const{kind:t,config:n,children:r}=e;switch(t){case"agent":case"plugin":case"endpoint":case"ingestion":{const i=n[t];return typeof i=="string"&&i.trim()?i:"—"}case"transform":{const i=n.transform,a=typeof i=="string"?i:"";return a.trim()?a.length>40?`${a.slice(0,40)}…`:a:"—"}case"map":return bt(yt(n),"agent")||"—";case"parallel":return`${r.length} step${r.length===1?"":"s"}`;case"loop":return bt(r[0]?.config??{},"agent")||"—";case"sub_pipeline":{const i=n.sub_pipeline;return typeof i=="string"&&i.trim()?i:"—"}}}function Xo(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${Math.round(e)}ms`}function Yt(e){const t=e.config.upstreams;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}const zr=({issues:e})=>e?s.jsxs(s.Fragment,{children:[e.errors>0&&s.jsx("span",{title:`${e.errors} error${e.errors===1?"":"s"}`,className:"flex h-4 min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-semibold leading-none text-white",children:e.errors}),e.warnings>0&&s.jsx("span",{title:`${e.warnings} warning${e.warnings===1?"":"s"}`,className:"flex h-4 min-w-[16px] items-center justify-center rounded-full bg-amber-500 px-1 text-[10px] font-semibold leading-none text-white",children:e.warnings})]}):null,Zo=({status:e})=>{if(!e||e.status==="pending")return null;const t=e.status==="running"?"bg-blue-500 animate-pulse":e.status==="success"?"bg-green-500":e.status==="failed"?"bg-red-500":"bg-gray-400";return s.jsxs("span",{className:"flex items-center gap-1",title:e.error??e.status,children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${t}`}),e.durationMs!=null&&s.jsx("span",{className:"text-[10px] leading-none text-gray-400 dark:text-gray-500",children:Xo(e.durationMs)})]})},el=({child:e,parentId:t,selected:n,issues:r,dragState:i,onDragStart:a,onDragEnd:l,onDrop:o,onSelect:c,onRemove:p,darkMode:u})=>{const[d,m]=b.useState(!1),v=Gr[e.kind],x=i!==null&&i.containerId===t,S=d&&x,w=K=>{x&&(K.preventDefault(),K.dataTransfer.dropEffect="move",m(!0))},U=K=>{K.currentTarget.contains(K.relatedTarget)||m(!1)},D=K=>{x&&(K.preventDefault(),m(!1),o())};return s.jsxs("div",{className:`group flex cursor-pointer select-none items-center gap-1.5 rounded-md border p-1.5 transition-colors ${u?"border-gray-600 text-gray-100":"border-gray-200 text-gray-900"} ${S?"bg-blue-50 dark:bg-blue-900/30":u?"bg-gray-700":"bg-white"} ${S?"ring-2 ring-blue-400":n?"ring-2 ring-blue-500":""}`,onClick:K=>{K.stopPropagation(),c()},onDragOver:w,onDragLeave:U,onDrop:D,children:[s.jsx("span",{draggable:!0,onDragStart:K=>{K.dataTransfer.effectAllowed="move",K.dataTransfer.setData("text/plain",e.id),a()},onDragEnd:l,className:`cursor-grab active:cursor-grabbing ${u?"text-gray-500 hover:text-gray-300":"text-gray-400 hover:text-gray-600"}`,title:"Drag to reorder",children:s.jsx(ir,{size:14})}),s.jsx("span",{className:Vr[e.kind],children:s.jsx(v,{size:14})}),s.jsxs("button",{type:"button",onClick:K=>{K.stopPropagation(),c()},className:`min-w-0 flex-1 truncate text-left text-xs font-medium underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-blue-500 ${u?"text-gray-100":"text-gray-900"}`,"aria-label":`Configure ${Ye[e.kind].label} step ${e.name}`,title:"Configure this step",children:[s.jsx("span",{children:e.name}),s.jsx("span",{className:`ml-1.5 shrink-0 rounded px-1.5 py-0.5 text-[10px] font-semibold no-underline ${u?"bg-blue-950/60 text-blue-300":"bg-blue-50 text-blue-700"}`,children:"Configure"})]}),s.jsx(zr,{issues:r}),s.jsx("button",{onClick:K=>{K.stopPropagation(),p()},className:`rounded p-0.5 transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100 ${u?"text-gray-400 hover:bg-gray-600 hover:text-red-400":"text-gray-400 hover:bg-gray-200 hover:text-red-600"}`,title:"Remove child step",children:s.jsx(vt,{size:14})})]})},tl=({step:e,selected:t,selectedChildId:n,runStatus:r,issueCounts:i,canMoveUp:a,canMoveDown:l,dragState:o,onDragStart:c,onDragEnd:p,onDrop:u,onDropChild:d,onSelect:m,onSelectChild:v,onMove:x,onDelete:S,onAddChild:w,onRemoveChild:U,darkMode:D})=>{const[K,X]=b.useState(!1),L=Gr[e.kind],y=Ye[e.kind],O=i[e.name],E=Jo(e),H=Qo(e),ie=o!==null&&o.containerId===null,ne=K&&ie,ge=ne?"ring-2 ring-blue-400":r?.status==="running"?"ring-2 ring-blue-500":r?.status==="success"?"ring-2 ring-green-500":r?.status==="failed"?"ring-2 ring-red-500":t?"ring-2 ring-blue-500":"",Le=ne?"bg-blue-50 dark:bg-blue-900/30":"bg-gray-100 dark:bg-gray-800",$e=k=>{ie&&(k.preventDefault(),k.dataTransfer.dropEffect="move",X(!0))},Fe=k=>{k.currentTarget.contains(k.relatedTarget)||X(!1)},Ae=k=>{ie&&(k.preventDefault(),X(!1),u())},ae=`rounded p-0.5 transition-colors disabled:pointer-events-none disabled:opacity-30 ${D?"text-gray-500 hover:bg-gray-700 hover:text-gray-200":"text-gray-400 hover:bg-gray-200 hover:text-gray-700"}`;return s.jsxs("div",{className:`group w-full max-w-2xl cursor-pointer select-none rounded-xl border p-3 transition-colors ${Le} ${ge} ${D?"border-gray-700 text-gray-100":"border-gray-200 text-gray-900"}`,onClick:m,onDragOver:$e,onDragLeave:Fe,onDrop:Ae,children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{draggable:!0,onDragStart:k=>{k.dataTransfer.effectAllowed="move",k.dataTransfer.setData("text/plain",e.id),c(e.id,null)},onDragEnd:p,className:`cursor-grab active:cursor-grabbing ${D?"text-gray-500 hover:text-gray-300":"text-gray-400 hover:text-gray-600"}`,title:"Drag to reorder",children:s.jsx(ir,{size:16})}),s.jsx("span",{className:Vr[e.kind],children:s.jsx(L,{size:16})}),s.jsxs("button",{type:"button",onClick:k=>{k.stopPropagation(),m()},className:`min-w-0 flex-1 truncate text-left text-sm font-medium underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-blue-500 ${D?"text-gray-100":"text-gray-900"}`,"aria-label":`Configure ${y.label} step ${e.name}`,title:"Configure this step",children:[s.jsx("span",{children:e.name}),s.jsx("span",{className:`ml-1.5 shrink-0 rounded px-1.5 py-0.5 text-[10px] font-semibold no-underline ${D?"bg-blue-950/60 text-blue-300":"bg-blue-50 text-blue-700"}`,children:"Configure"})]}),s.jsx(zr,{issues:O}),s.jsx(Zo,{status:r}),s.jsx("button",{onClick:k=>{k.stopPropagation(),x(-1)},disabled:!a,className:ae,title:"Move up",children:s.jsx(ar,{size:14})}),s.jsx("button",{onClick:k=>{k.stopPropagation(),x(1)},disabled:!l,className:ae,title:"Move down",children:s.jsx(sr,{size:14})}),s.jsx("button",{onClick:k=>{k.stopPropagation(),S()},className:`${ae} opacity-0 group-hover:opacity-100 focus:opacity-100`,title:"Delete step",children:s.jsx(yi,{size:14})})]}),s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:s.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${y.badge}`,children:y.label})}),s.jsx("p",{className:"mt-1 truncate text-xs text-gray-500 dark:text-gray-400",title:E,children:E}),s.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2 text-[10px]",children:[s.jsxs("div",{className:"rounded-md bg-white/60 px-2 py-1.5 dark:bg-gray-900/40",children:[s.jsx("span",{className:"block font-semibold uppercase tracking-wide text-gray-400",children:"receives"}),s.jsxs("span",{className:"truncate text-gray-600 dark:text-gray-300",children:[Xn(e.config.input)||"default"," input mapping(s)"]})]}),s.jsxs("div",{className:"rounded-md bg-white/60 px-2 py-1.5 dark:bg-gray-900/40",children:[s.jsx("span",{className:"block font-semibold uppercase tracking-wide text-gray-400",children:"emits"}),s.jsxs("span",{className:"truncate text-gray-600 dark:text-gray-300",children:[Xn(e.config.output)||"default"," output mapping(s)"]})]})]}),H.length>0&&s.jsxs("div",{className:`mt-2 rounded-md border px-2 py-1.5 text-[10px] ${D?"border-blue-900/70 bg-blue-950/30":"border-blue-100 bg-blue-50/70"}`,children:[s.jsx("span",{className:`block font-semibold uppercase tracking-wide ${D?"text-blue-300":"text-blue-700"}`,children:"field links"}),H.slice(0,3).map(k=>s.jsxs("p",{className:`mt-0.5 truncate font-mono ${D?"text-gray-300":"text-gray-700"}`,title:`${k.source} → ${k.target}`,children:[k.source," → ",k.target]},`${k.target}:${k.source}`)),H.length>3&&s.jsxs("p",{className:`mt-0.5 ${D?"text-gray-400":"text-gray-500"}`,children:["+",H.length-3," more"]})]}),Yt(e).length>0&&s.jsxs("p",{className:"mt-1 truncate text-[10px] font-medium text-indigo-500 dark:text-indigo-400",title:`Runs after: ${Yt(e).join(", ")}`,children:["⤴ ",Yt(e).join(", ")]}),e.kind==="map"&&s.jsxs("div",{className:`mt-2 space-y-1 rounded-lg border border-dashed p-2 text-xs ${D?"border-gray-600 text-gray-400":"border-gray-300 text-gray-500"}`,children:[s.jsxs("p",{className:"truncate",children:[s.jsx("span",{className:"font-medium text-gray-400 dark:text-gray-500",children:"items:"})," ",bt(yt(e.config),"items")||"—"]}),s.jsxs("p",{className:"truncate",children:[s.jsx("span",{className:"font-medium text-gray-400 dark:text-gray-500",children:"strategy:"})," ",bt(yt(e.config),"strategy")||"—"]})]}),(e.kind==="parallel"||e.kind==="loop")&&s.jsxs("div",{className:`mt-2 rounded-lg border-2 border-dashed p-2 ${D?"border-gray-600":"border-gray-300"}`,children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500",children:y.label}),s.jsx("div",{className:"space-y-1.5",children:e.children.map(k=>s.jsx(el,{child:k,parentId:e.id,selected:k.id===n,issues:i[k.name],dragState:o,onDragStart:()=>c(k.id,e.id),onDragEnd:p,onDrop:()=>d(k.id),onSelect:()=>v(k.id),onRemove:()=>U(k.id),darkMode:D},k.id))}),e.kind==="parallel"&&s.jsxs("button",{onClick:w,className:`mt-1.5 flex w-full items-center justify-center gap-1 rounded-md border border-dashed py-1 text-xs transition-colors ${D?"border-gray-600 text-gray-400 hover:bg-gray-700 hover:text-gray-200":"border-gray-300 text-gray-500 hover:bg-gray-200 hover:text-gray-700"}`,title:"Add child agent step",children:[s.jsx(or,{size:14}),"Add agent"]})]})]})},nl=({draft:e,selectedId:t,selectedChildPath:n,runStatuses:r,issueCounts:i,onSelect:a,onReorder:l,onMove:o,onAddChild:c,onRemoveChild:p,onDelete:u,onAddFromPalette:d,onAddResource:m,darkMode:v})=>{const[x,S]=b.useState(null),w=L=>Array.from(L.dataTransfer.types).includes(Qn),U=L=>Array.from(L.dataTransfer.types).includes(Jn),D=L=>{!w(L)&&!U(L)||(L.preventDefault(),L.dataTransfer.dropEffect="copy")},K=L=>{if(!w(L)&&!U(L))return;if(L.preventDefault(),U(L))try{const O=JSON.parse(L.dataTransfer.getData(Jn));if(O&&typeof O.name=="string"&&typeof O.kind=="string"&&["agent","plugin","endpoint","ingestion","sub_pipeline"].includes(O.kind)){m(O.kind,O.name);return}}catch{}const y=L.dataTransfer.getData(Qn);Ye[y]&&d(y)},X=(L,y)=>{if(!x||x.containerId!==y)return;const O=y===null?e.steps:e.steps.find(ie=>ie.id===y)?.children??[],E=O.findIndex(ie=>ie.id===x.id),H=O.findIndex(ie=>ie.id===L);E===-1||H===-1||E===H||(l(E,H,y??void 0),S(null))};return s.jsx("div",{className:"flex-1 overflow-auto rounded-2xl border border-dashed border-gray-200 bg-[radial-gradient(circle_at_1px_1px,rgba(148,163,184,0.20)_1px,transparent_0)] bg-[size:18px_18px] dark:border-gray-700 dark:bg-[radial-gradient(circle_at_1px_1px,rgba(148,163,184,0.12)_1px,transparent_0)]",onDragOver:D,onDrop:K,children:e.steps.length===0?s.jsx("div",{className:"flex h-full items-center justify-center p-8",children:s.jsxs("div",{className:"max-w-sm rounded-2xl border border-dashed border-blue-300 bg-white/75 p-6 text-center shadow-sm dark:border-blue-800 dark:bg-gray-800/75",children:[s.jsx("p",{className:"text-sm font-semibold",children:"Build your flow visually"}),s.jsx("p",{className:`mt-1 text-sm ${v?"text-gray-400":"text-gray-500"}`,children:"Drag a step or a discovered resource here, or use the quick-add menu. Connections appear in execution order."})]})}):s.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col items-center p-4",children:e.steps.map((L,y)=>{const O=t===L.id&&n&&n.length>0?n[0]:null;return s.jsxs(ci.Fragment,{children:[s.jsx(tl,{step:L,selected:t===L.id&&O===null,selectedChildId:O,runStatus:r[L.name],issueCounts:i,canMoveUp:y>0,canMoveDown:yS({id:E,containerId:H}),onDragEnd:()=>S(null),onDrop:()=>X(L.id,null),onDropChild:E=>X(E,L.id),onSelect:()=>a(L.id,null),onSelectChild:E=>a(L.id,[E]),onMove:E=>o(L.id,E),onDelete:()=>u(L.id),onAddChild:()=>c(L.id),onRemoveChild:E=>p(L.id,E),darkMode:v}),y{const E=e.steps[y+1];return s.jsxs("button",{type:"button","aria-label":`Configure field links from ${L.name} to ${E.name}`,title:`Configure schema-aware field links into ${E.name}`,onClick:()=>a(E.id,null),className:`group/link flex h-12 shrink-0 flex-col items-center justify-center gap-1 rounded-md px-3 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 ${v?"hover:bg-blue-950/40":"hover:bg-blue-50"}`,children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${v?"bg-blue-500":"bg-blue-400"}`}),s.jsx("span",{className:`h-5 w-px ${v?"bg-blue-700":"bg-blue-300"}`}),s.jsx("span",{className:`text-[10px] leading-none ${v?"text-blue-400":"text-blue-500"}`,children:"Connect fields ↓"})]})})()]},L.id)})})})},rl="w-full px-3 py-2 rounded-lg border text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",il=e=>e?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900",nt=e=>`block text-xs font-medium mb-1 ${e?"text-gray-400":"text-gray-600"}`,rt=(e,t=!1)=>`${rl} ${il(e)}${t?" font-mono":""}`,de=({label:e,value:t,onChange:n,placeholder:r,darkMode:i,mono:a,hint:l,list:o})=>s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:nt(i),children:e}),s.jsx("input",{type:"text",value:t,placeholder:r,list:o,onChange:c=>n(c.target.value),className:rt(i,a)}),l&&s.jsx("p",{className:`mt-1 text-xs ${i?"text-gray-500":"text-gray-400"}`,children:l})]}),Se=({label:e,value:t,onChange:n,min:r,max:i,step:a,darkMode:l})=>s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:nt(l),children:e}),s.jsx("input",{type:"number",value:t,min:r,max:i,step:a,onChange:o=>n(Number(o.target.value)),className:rt(l)})]}),_e=({label:e,value:t,options:n,onChange:r,darkMode:i,placeholder:a})=>{const l=a?[{value:"",label:a},...n]:n;return s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:nt(i),children:e}),s.jsx("select",{value:t,onChange:o=>r(o.target.value),className:rt(i),children:l.map(o=>s.jsx("option",{value:o.value,children:o.label},o.value))})]})},Wt=({label:e,value:t,onChange:n,rows:r=3,darkMode:i,mono:a,placeholder:l})=>s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:nt(i),children:e}),s.jsx("textarea",{value:t,rows:r,placeholder:l,onChange:o=>n(o.target.value),className:rt(i,a)})]}),al=({label:e,checked:t,onChange:n,darkMode:r})=>s.jsxs("label",{className:`flex items-center gap-2 mb-3 cursor-pointer text-sm ${r?"text-gray-300":"text-gray-700"}`,children:[s.jsx("input",{type:"checkbox",checked:t,onChange:i=>n(i.target.checked),className:"w-4 h-4 rounded accent-blue-500"}),e]}),Je=({label:e,value:t,onChange:n,darkMode:r})=>{const[i,a]=b.useState(()=>JSON.stringify(t,null,2)),[l,o]=b.useState(!1),c=b.useRef(i);c.current=i,b.useEffect(()=>{let u;try{u=JSON.parse(c.current)}catch{return}JSON.stringify(u)!==JSON.stringify(t)&&(a(JSON.stringify(t,null,2)),o(!1))},[t]);const p=u=>{a(u);try{const d=JSON.parse(u);o(!1),n(d)}catch{o(!0)}};return s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:nt(r),children:e}),s.jsx("textarea",{value:i,rows:6,spellCheck:!1,onChange:u=>p(u.target.value),className:rt(r,!0)}),l&&s.jsx("p",{className:"mt-1 text-xs text-red-500",children:"Invalid JSON"})]})},Y=({title:e,children:t,darkMode:n})=>s.jsxs("div",{className:`p-3 mb-3 rounded-lg border ${n?"border-gray-700 bg-gray-800/30":"border-gray-200 bg-gray-50/50"}`,children:[s.jsx("h3",{className:`text-xs font-semibold uppercase tracking-wide mb-3 ${n?"text-gray-400":"text-gray-500"}`,children:e}),t]}),lt=e=>Object.entries(e??{}).map(([t,n],r)=>({id:r,key:t,value:typeof n=="string"?n:n==null?"":String(n)})),ct=e=>{const t={};for(const n of e)t[n.key]=n.value;return t},Zn="application/x-agentomatic-mapping-source",jt="__root__",er=e=>e===jt?"Request body":e,tr=e=>{if(e.startsWith("$.input."))return`Pipeline input · ${e.slice(8)}`;if(e.startsWith("$.steps.")){const[,,t,...n]=e.split(".");return n.length?`${t} · ${n.join(".")}`:`${t} · full result`}return e.startsWith("$.defaults.")?`Pipeline default · ${e.slice(11)}`:e==="$.defaults."?"Pipeline defaults":e==="$.context."?"Shared context":e==="$.current."?"Current item":e},sl=e=>e.startsWith("$.input.")?"Pipeline input":e.startsWith("$.steps.")?e.split(".")[2]||"Step output":e.startsWith("$.defaults.")?"Pipeline defaults":e.startsWith("$.context.")?"Shared context":e.startsWith("$.current.")?"Current item":"Other source",ol=(e,t)=>{const n=t.filter(a=>!a.endsWith(".")),r={};let i=!1;for(const a of e){const l=n.findIndex(p=>p.replace(/\[\d+\]/g,"").split(".").at(-1)===a);if(l<0&&i)continue;const o=l>=0?l:0,c=n[o];c&&(r[a]=c,n.splice(o,1),i||=l<0)}return r},ll=(e,t,n)=>{const r=new Set(Object.values(e).filter(l=>typeof l=="string"&&l.length>0)),i=t.filter(l=>!e[l]),a=ol(i,n.filter(l=>!r.has(l)));return{...e,...a}},nr=({label:e,mappings:t,suggestions:n,targetSuggestions:r=[],onChange:i,darkMode:a})=>{const[l,o]=b.useState(()=>lt(t)),c=n.filter(y=>!y.endsWith(".")),[p,u]=b.useState(r[0]??""),[d,m]=b.useState(c[0]??""),v=b.useRef(l);v.current=l;const x=b.useRef(l.length);b.useEffect(()=>{const y=ct(v.current);JSON.stringify(y)!==JSON.stringify(t??{})&&o(lt(t??{}))},[t]),b.useEffect(()=>{r.includes(p)||u(r[0]??"")},[p,r]),b.useEffect(()=>{c.includes(d)||m(c[0]??"")},[c,d]);const S=y=>{o(y),i(ct(y))},w=()=>{x.current+=1,S([...l,{id:x.current,key:"",value:""}])},U=()=>{const y=ll(ct(l),r,n);Object.keys(y).length!==0&&(x.current=Object.keys(y).length,S(lt(y)))},D=(y=p,O=d)=>{if(!y||!O)return;const E=ct(l);E[y]=O,x.current=Object.keys(E).length,S(lt(E))},K=c.reduce((y,O)=>{const E=sl(O);return(y[E]??=[]).push(O),y},{}),X=(y,O)=>{S(l.map(E=>E.id===y?{...E,...O}:E))},L=y=>{S(l.filter(O=>O.id!==y))};return s.jsxs("div",{className:"mb-3",children:[s.jsx("span",{className:`block text-xs font-medium mb-1 ${a?"text-gray-400":"text-gray-600"}`,children:e==="input"?"Input mappings":"Output mappings"}),s.jsx("datalist",{id:`builder-mapping-${e}`,children:n.map(y=>s.jsx("option",{value:y},y))}),s.jsx("datalist",{id:`builder-mapping-target-${e}`,children:r.map(y=>s.jsx("option",{value:y},y))}),r.length>0&&c.length>0&&s.jsxs("div",{className:`mb-3 rounded-lg border p-2.5 ${a?"border-blue-900/80 bg-blue-950/20":"border-blue-100 bg-blue-50/60"}`,children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-xs font-semibold ${a?"text-blue-200":"text-blue-800"}`,children:e==="input"?"Connect fields visually":"Route output visually"}),s.jsx("span",{className:`text-[10px] ${a?"text-blue-300/70":"text-blue-700/70"}`,children:"Click two fields or drag an output onto an input"})]}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wide ${a?"text-gray-400":"text-gray-600"}`,children:"Available outputs"}),s.jsx("div",{className:"space-y-1.5",children:Object.entries(K).map(([y,O])=>s.jsxs("div",{children:[s.jsx("p",{className:`mb-1 text-[10px] ${a?"text-blue-300/70":"text-blue-700/70"}`,children:y}),s.jsx("div",{className:"flex flex-wrap gap-1",children:O.map(E=>s.jsx("button",{type:"button",draggable:!0,"aria-pressed":d===E,title:"Click to select, or drag onto a target field",onDragStart:H=>{H.dataTransfer.effectAllowed="link",H.dataTransfer.setData(Zn,E)},onClick:()=>m(E),className:`max-w-full truncate rounded border px-1.5 py-1 text-left text-[11px] transition-colors ${d===E?"border-blue-600 bg-blue-600 text-white":a?"border-gray-600 bg-gray-800 text-gray-200 hover:border-blue-400":"border-gray-200 bg-white text-gray-700 hover:border-blue-500"}`,children:tr(E)},E))})]},y))})]}),s.jsxs("div",{children:[s.jsx("p",{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wide ${a?"text-gray-400":"text-gray-600"}`,children:e==="input"?"Step inputs":"Pipeline outputs"}),s.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(y=>s.jsx("button",{type:"button","aria-label":e==="input"?`Field to receive a visual connection: ${y}`:`Pipeline output field to receive a visual route: ${y}`,"aria-pressed":p===y,onClick:()=>u(y),onDragOver:O=>O.preventDefault(),onDrop:O=>{O.preventDefault();const E=O.dataTransfer.getData(Zn);c.includes(E)&&(m(E),u(y),D(y,E))},className:`rounded-md border px-2 py-1.5 font-mono text-xs transition-colors ${p===y?"border-blue-600 bg-blue-600 text-white":a?"border-dashed border-gray-500 bg-gray-800 text-gray-100 hover:border-blue-400":"border-dashed border-gray-300 bg-white text-gray-800 hover:border-blue-500"}`,title:"Select as the connection target, or drop an output here to link it",children:er(y)},y))})]})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[p&&d&&s.jsxs("p",{className:`min-w-0 flex-1 truncate text-[11px] ${a?"text-blue-300/80":"text-blue-700/80"}`,children:[tr(d)," → ",s.jsx("span",{className:"font-mono",children:er(p)})]}),s.jsx("button",{type:"button",onClick:()=>D(),disabled:!p||!d,className:"rounded-md bg-blue-600 px-2.5 py-1.5 text-xs font-semibold text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-400",children:"Link fields"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${a?"text-gray-400":"text-gray-600"}`,children:"Need a custom expression? The editable mapping rows below remain available."})]}),l.length===0&&s.jsx("p",{className:`text-xs mb-2 ${a?"text-gray-500":"text-gray-400"}`,children:"No mappings"}),l.map(y=>s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx(de,{value:y.key,placeholder:"field",mono:!0,list:`builder-mapping-target-${e}`,onChange:O=>X(y.id,{key:O}),darkMode:a}),y.key===jt&&s.jsx("p",{className:`mt-1 text-[10px] ${a?"text-blue-300/80":"text-blue-700/80"}`,children:"Request body"})]}),s.jsx("div",{className:"flex-[1.5]",children:s.jsx(de,{value:y.value,placeholder:e==="input"?"$.input...":"$",mono:!0,list:`builder-mapping-${e}`,onChange:O=>X(y.id,{value:O}),darkMode:a})}),s.jsx("button",{onClick:()=>L(y.id),title:"Remove mapping",className:`p-1.5 rounded-lg transition-colors ${a?"hover:bg-gray-600 text-gray-400":"hover:bg-gray-200 text-gray-500"}`,children:s.jsx(vt,{size:14})})]},y.id)),n.length>0&&s.jsxs("div",{className:`mb-2 flex flex-wrap items-center gap-1 text-[11px] ${a?"text-gray-400":"text-gray-500"}`,children:[r.length>0&&s.jsx("button",{type:"button",onClick:U,title:e==="input"?"Connect compatible upstream outputs to this step's input fields":"Route compatible step outputs to this pipeline's declared outputs",className:`mr-1 rounded border px-1.5 py-0.5 font-medium transition-colors ${a?"border-blue-700 bg-blue-900/30 text-blue-300 hover:bg-blue-900/60":"border-blue-200 bg-blue-50 text-blue-700 hover:bg-blue-100"}`,children:"Auto-connect"}),s.jsx("span",{className:"mr-1",children:"Quick sources"}),n.slice(0,14).map(y=>s.jsx("button",{type:"button",title:`Use ${y} for the current mapping`,onClick:()=>{const O=l.find(E=>!E.value)??l[l.length-1];O?X(O.id,{value:y}):(x.current+=1,S([{id:x.current,key:r[0]??"",value:y}]))},className:`rounded border px-1.5 py-0.5 font-mono transition-colors ${a?"border-gray-600 hover:border-blue-400 hover:text-blue-300":"border-gray-200 hover:border-blue-500 hover:text-blue-700"}`,children:y},y))]}),s.jsxs("button",{onClick:w,className:`flex items-center gap-1 text-sm font-medium transition-colors ${a?"text-blue-400 hover:text-blue-300":"text-blue-600 hover:text-blue-700"}`,children:[s.jsx(or,{size:14}),"Add mapping"]})]})},T=e=>typeof e=="string"?e:e==null?"":String(e),De=e=>typeof e=="number"?e:0,z=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},cl=(e,t,n)=>{const r=new Set(t),i=new Set(Array.isArray(n)?n.filter(a=>typeof a=="string"):[]);for(const a of Object.values(e)){if(typeof a!="string")continue;const l=/^\$\.steps\.([^.[\]]+)/.exec(a);l?.[1]&&r.has(l[1])&&i.add(l[1])}return Array.from(i)},ul=[{value:"fail",label:"fail"},{value:"skip",label:"skip"},{value:"retry",label:"retry"},{value:"fallback",label:"fallback"}],pl=[{value:"fail_fast",label:"fail_fast"},{value:"continue",label:"continue"},{value:"rollback",label:"rollback"}],rr=[{value:"all",label:"all"},{value:"first",label:"first"},{value:"majority",label:"majority"}],fl=[{value:"fixed",label:"fixed"},{value:"linear",label:"linear"},{value:"exponential",label:"exponential"}],dl=["$","$.response","$.output","$.result","$.text"],ml={agent:30,plugin:30,endpoint:30,ingestion:300,transform:10,parallel:60,map:120,loop:120,sub_pipeline:120},gl=(e,t)=>typeof t=="number"?t:ml[e],Be=e=>{const t=z(e),n=z(t.properties);return Object.keys(n).length>0?Object.keys(n):Object.keys(t).filter(r=>!["$schema","$defs","$ref","type","title","description","required","additionalProperties","anyOf","oneOf","allOf","default","examples"].includes(r))},hl=e=>{const t=Be(e);if(t.length>0)return t;const n=z(e);return n.type&&n.type!=="object"?[jt]:[]},xl=(e,t)=>{const n=z(e),r=new Set(Array.isArray(n.required)?n.required.filter(l=>typeof l=="string"):[]),i=Object.entries(z(n.properties)).map(([l,o])=>{const c=z(o);return{name:l,type:T(c.type)||(Array.isArray(c.anyOf)?"union":"value"),required:r.has(l),description:T(c.description)}});if(i.length>0)return i;const a=T(n.type);return a&&a!=="object"?[{name:t,type:a,required:!0,description:T(n.description)}]:[]},on={type:"object",properties:{items:{type:"array",description:"One result for every processed item."},by_key:{type:"object",description:"Results indexed by item position."},count:{type:"integer",description:"Number of input items."},succeeded:{type:"integer",description:"Number of successful item runs."}}},bl=e=>Be(on).map(t=>`$.steps.${e}.${t}`),yl=({draft:e,selection:t,resources:n,agentSchemas:r,resourceSchemas:i={},resourceContractErrors:a={},onChange:l,darkMode:o})=>{if(t.type==="pipeline"){const f=e.meta,$=g=>l(Wr(e,{...f,...g}));return s.jsx("div",{className:"p-4",children:s.jsxs(Y,{title:"Pipeline settings",darkMode:o,children:[s.jsx(de,{label:"Name",value:f.name,onChange:g=>$({name:g}),darkMode:o}),s.jsx(Wt,{label:"Description",value:f.description,onChange:g=>$({description:g}),darkMode:o}),s.jsx(de,{label:"Version",value:f.version,onChange:g=>$({version:g}),darkMode:o}),s.jsx(_e,{label:"On error",value:f.on_error,options:pl,onChange:g=>$({on_error:g}),darkMode:o}),s.jsx(Se,{label:"Timeout (s)",value:f.timeout,onChange:g=>$({timeout:g}),darkMode:o}),s.jsx(al,{label:"Strict schema",checked:f.strict_schema,onChange:g=>$({strict_schema:g}),darkMode:o}),s.jsx(Je,{label:"Input schema",value:z(f.input_schema),onChange:g=>$({input_schema:g}),darkMode:o}),s.jsx(Je,{label:"Output schema",value:z(f.output_schema),onChange:g=>$({output_schema:g}),darkMode:o}),s.jsx(Je,{label:"Defaults",value:z(f.defaults),onChange:g=>$({defaults:g}),darkMode:o}),s.jsx(Je,{label:"Metadata",value:z(f.metadata),onChange:g=>$({metadata:g}),darkMode:o})]})})}const c=e.steps.find(f=>f.id===t.id);if(!c)return s.jsx("div",{className:"p-4",children:s.jsx("p",{className:`text-sm ${o?"text-gray-400":"text-gray-500"}`,children:"Select a step or pipeline settings"})});let p=c;if(t.childPath.length>0){const f=c.children.find($=>$.id===t.childPath[0]);f&&(p=f)}const u=f=>l(Do(e,t.id,t.childPath,f)),d={...p.config},m=p.kind,v=t.childPath.length>0,x=Ye[m].label,S=n.agents.map(f=>({value:f.name,label:f.name})),w=n.plugins.map(f=>({value:f.name,label:f.name})),U=n.endpoints.map(f=>({value:f.name,label:f.name})),D=n.ingestors.map(f=>({value:f.name,label:f.name})),K=n.pipelines.filter(f=>f.name!==e.meta.name).map(f=>({value:f.name,label:f.name})),X=()=>{const f=v||m==="agent"?T(d.agent):m==="map"?T(z(d.map).agent):"";return f?r[f]?.input_schema??null:m==="plugin"?i[`plugin:${T(d.plugin)}`]?.input_schema??null:m==="endpoint"?i[`endpoint:${T(d.endpoint)}`]?.input_schema??null:m==="ingestion"?i[`ingestion:${T(d.ingestion)}`]?.input_schema??null:m==="sub_pipeline"?i[`sub_pipeline:${T(d.sub_pipeline)}`]?.input_schema??null:null},L=()=>{if(m==="map")return on;const f=v||m==="agent"?T(d.agent):"";return f?r[f]?.output_schema??null:m==="plugin"?i[`plugin:${T(d.plugin)}`]?.output_schema??null:m==="endpoint"?i[`endpoint:${T(d.endpoint)}`]?.output_schema??null:m==="ingestion"?i[`ingestion:${T(d.ingestion)}`]?.output_schema??null:m==="sub_pipeline"?i[`sub_pipeline:${T(d.sub_pipeline)}`]?.output_schema??null:null},y=f=>{if(f.kind==="map")return bl(f.name);const $=f.kind==="agent"?T(f.config.agent):f.kind==="plugin"?T(f.config.plugin):f.kind==="endpoint"?T(f.config.endpoint):f.kind==="ingestion"?T(f.config.ingestion):f.kind==="sub_pipeline"?T(f.config.sub_pipeline):"",g=f.kind==="agent"?r[$]?.output_schema:i[`${f.kind}:${$}`]?.output_schema,B=Be(g);return B.length?B.map(W=>`$.steps.${f.name}.${W}`):[`$.steps.${f.name}`]},O=e.steps.findIndex(f=>f.id===t.id),E=e.steps.filter((f,$)=>${if(v)return{};const $=cl(f,e.steps.filter(g=>g.id!==t.id).map(g=>g.name),d.upstreams);return $.length?{upstreams:$}:{}},ge=[...H.map(f=>`$.input.${f}`),"$.defaults.","$.context.","$.current.",...E.flatMap(y)],Le=hl(X()),$e=Be(L()),Fe=$e.length?["$",...$e.map(f=>`$.${f}`)]:dl,Ae=f=>s.jsx("p",{className:`text-xs mb-3 ${o?"text-gray-500":"text-gray-400"}`,children:f}),ae=(f,$,g,B,W)=>g.length===0?Ae(W):s.jsx(_e,{label:f,value:$,options:g,onChange:B,darkMode:o}),k=(f,$)=>s.jsxs(Y,{title:"Execution",darkMode:o,children:[f&&s.jsx(de,{label:"Condition",value:T(d.condition),placeholder:"e.g. $.input.ok == true",onChange:g=>u({...d,condition:g}),darkMode:o}),s.jsx(_e,{label:"On error",value:T(d.on_error)||"fail",options:ul,onChange:g=>u({...d,on_error:g}),darkMode:o}),s.jsx(Se,{label:"Timeout (s)",value:gl(m,d.timeout),min:.1,step:.1,onChange:g=>u({...d,timeout:g}),darkMode:o}),$&&s.jsx(Wt,{label:"Rollback",value:T(d.rollback),rows:3,mono:!0,onChange:g=>u({...d,rollback:g}),darkMode:o})]}),Me=(f,$)=>s.jsxs(Y,{title:"Retry",darkMode:o,children:[s.jsx(Se,{label:"Max attempts",value:De(f.max_attempts)||3,min:1,max:10,onChange:g=>$({...f,max_attempts:g}),darkMode:o}),s.jsx(_e,{label:"Backoff",value:T(f.backoff)||"fixed",options:fl,onChange:g=>$({...f,backoff:g}),darkMode:o}),s.jsx(Se,{label:"Base delay (s)",value:De(f.base_delay)||.5,min:.1,max:60,step:.1,onChange:g=>$({...f,base_delay:g}),darkMode:o})]}),he=(f,$,g,B)=>s.jsxs(Y,{title:"Mappings",darkMode:o,children:[s.jsx(nr,{label:"input",mappings:f,suggestions:ge,targetSuggestions:Le,onChange:g,darkMode:o}),s.jsx(nr,{label:"output",mappings:$,suggestions:Fe,targetSuggestions:ie,onChange:B,darkMode:o})]}),ye=()=>s.jsx(Y,{title:"Metadata",darkMode:o,children:s.jsx(Je,{label:"Metadata",value:z(d.metadata),onChange:f=>u({...d,metadata:f}),darkMode:o})}),ve=s.jsx(de,{label:"Name",value:p.name,onChange:f=>l(Bo(e,t.id,t.childPath,f)),darkMode:o}),it=()=>{const f={agent:"agent",plugin:"plugin",endpoint:"endpoint",ingestion:"ingestion",sub_pipeline:"sub_pipeline"},$=f[m]?T(d[f[m]]):x,g=Object.keys(G(d.input)).length,B=Object.keys(G(d.output)).length;return s.jsxs(Y,{title:"Step contract",darkMode:o,children:[s.jsxs("p",{className:`mb-2 text-xs ${o?"text-gray-400":"text-gray-500"}`,children:["This ",x.toLowerCase()," runs as ",s.jsx("span",{className:"font-mono font-semibold",children:$||"not configured"}),"."]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[s.jsxs("div",{className:`rounded-md p-2 ${o?"bg-gray-900/50 text-gray-300":"bg-white text-gray-700"}`,children:[s.jsx("span",{className:"block text-[10px] font-semibold uppercase text-gray-400",children:"Input"}),g?`${g} mapping(s)`:"Uses pipeline context"]}),s.jsxs("div",{className:`rounded-md p-2 ${o?"bg-gray-900/50 text-gray-300":"bg-white text-gray-700"}`,children:[s.jsx("span",{className:"block text-[10px] font-semibold uppercase text-gray-400",children:"Output"}),B?`${B} mapping(s)`:"Default step output"]})]})]})},wt=()=>{const f=v||m==="agent"?T(d.agent):m==="map"?T(z(d.map).agent):"",$=f?"agent":m==="plugin"||m==="endpoint"||m==="ingestion"||m==="sub_pipeline"?m:null,g=f||($?T(d[$]):"");if(!$||!g)return null;const B=`${$}:${g}`,W=$==="agent"?r[g]:i[B],je=a[B],we=$==="agent"?"Agent schema":`${Ye[$].label} schema`;if(!W)return s.jsx(Y,{title:we,darkMode:o,children:s.jsxs("p",{role:"alert",className:`rounded-md border px-3 py-2 text-xs ${o?"border-amber-800 bg-amber-950/40 text-amber-200":"border-amber-300 bg-amber-50 text-amber-800"}`,children:[je||`Loading or unavailable for '${g}'.`," Retry live resources before relying on inferred mappings or test inputs. You can still configure explicit mappings below."]})});const F=(V,Et,at)=>{const Pe=xl(V,at);return Pe.length?s.jsx("ul",{className:"space-y-1",children:Pe.map(Ne=>s.jsxs("li",{className:`flex items-center justify-between gap-2 rounded px-2 py-1 text-xs ${o?"bg-gray-900/50 text-gray-300":"bg-white text-gray-700"}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",title:Ne.description,children:Ne.name}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[10px] text-gray-400",children:[Ne.type,Ne.required?" · required":""]})]},Ne.name))}):s.jsx("p",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:Et})};return m==="map"?s.jsxs(Y,{title:"Map step contract",darkMode:o,children:[s.jsxs("p",{className:`mb-3 text-xs ${o?"text-gray-400":"text-gray-500"}`,children:["Each item is sent to ",s.jsx("span",{className:"font-mono font-semibold",children:g})," using its live input schema. The map step itself emits an aggregate result for downstream links."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Per-item agent accepts"}),F(W.input_schema??{},"No declared input fields","Item value")]}),s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Map produces"}),F(on,"No declared output fields","Response body")]})]})]}):s.jsxs(Y,{title:we,darkMode:o,children:[s.jsxs("p",{className:`mb-3 text-xs ${o?"text-gray-400":"text-gray-500"}`,children:["Live contract for ",s.jsx("span",{className:"font-mono font-semibold",children:g}),". Map inputs to the required fields and route outputs explicitly when needed."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Accepts"}),F(W.input_schema??{},"No declared input fields","Request body")]}),s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Produces"}),F(W.output_schema??{},"No declared output fields","Response body")]})]})]})},Re=()=>{const f=new Set((Array.isArray(d.upstreams)?d.upstreams:[]).filter(B=>typeof B=="string")),$=e.steps.map(B=>B.name).filter(B=>B!==p.name),g=B=>{const W=new Set(f);W.has(B)?W.delete(B):W.add(B),u({...d,upstreams:Array.from(W)})};return s.jsxs(Y,{title:"Upstreams (DAG)",darkMode:o,children:[Ae("Steps that must complete before this one runs — makes their output available via $.steps regardless of canvas order."),$.length===0?s.jsx("p",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:"No other steps yet — add more steps to declare dependencies."}):s.jsx("div",{className:"space-y-1",children:$.map(B=>s.jsxs("label",{className:`flex items-center gap-2 text-sm cursor-pointer ${o?"text-gray-300":"text-gray-700"}`,children:[s.jsx("input",{type:"checkbox",checked:f.has(B),onChange:()=>g(B),className:"w-4 h-4 accent-blue-600"}),s.jsx("span",{className:"font-mono text-xs",children:B})]},B))})]})};let se;if(v)se=s.jsxs(s.Fragment,{children:[s.jsx(Y,{title:x,darkMode:o,children:ae("Agent",T(d.agent),S,f=>u({...d,agent:f}),"No agents registered")}),he(G(d.input),G(d.output),f=>u({...d,input:f,...ne(f)}),f=>u({...d,output:f})),Me(z(d.retry),f=>u({...d,retry:f})),k(!0,!0)]});else switch(m){case"agent":se=s.jsxs(s.Fragment,{children:[s.jsxs(Y,{title:x,darkMode:o,children:[ae("Agent",T(d.agent),S,f=>u({...d,agent:f}),"No agents registered"),s.jsx(_e,{label:"Fallback agent",value:T(d.fallback_agent),options:S,placeholder:"None",onChange:f=>u({...d,fallback_agent:f}),darkMode:o})]}),k(!0,!0),Me(z(d.retry),f=>u({...d,retry:f})),he(G(d.input),G(d.output),f=>u({...d,input:f,...ne(f)}),f=>u({...d,output:f})),ye()]});break;case"plugin":se=s.jsxs(s.Fragment,{children:[s.jsx(Y,{title:x,darkMode:o,children:ae("Plugin",T(d.plugin),w,f=>u({...d,plugin:f}),"No plugins registered")}),k(!0,!0),he(G(d.input),G(d.output),f=>u({...d,input:f,...ne(f)}),f=>u({...d,output:f})),ye()]});break;case"endpoint":se=s.jsxs(s.Fragment,{children:[s.jsx(Y,{title:x,darkMode:o,children:ae("Endpoint",T(d.endpoint),U,f=>u({...d,endpoint:f}),"No endpoints registered")}),k(!0,!0),he(G(d.input),G(d.output),f=>u({...d,input:f,...ne(f)}),f=>u({...d,output:f})),ye()]});break;case"ingestion":se=s.jsxs(s.Fragment,{children:[s.jsx(Y,{title:x,darkMode:o,children:ae("Ingestor",T(d.ingestion),D,f=>u({...d,ingestion:f}),"No ingestors registered")}),k(!0,!0),he(G(d.input),G(d.output),f=>u({...d,input:f,...ne(f)}),f=>u({...d,output:f})),ye()]});break;case"sub_pipeline":se=s.jsxs(s.Fragment,{children:[s.jsx(Y,{title:x,darkMode:o,children:ae("Pipeline",T(d.sub_pipeline),K,f=>u({...d,sub_pipeline:f}),"No pipelines registered")}),k(!0,!0),he(G(d.input),G(d.output),f=>u({...d,input:f,...ne(f)}),f=>u({...d,output:f})),ye()]});break;case"transform":se=s.jsxs(s.Fragment,{children:[s.jsx(Y,{title:x,darkMode:o,children:s.jsx(Wt,{label:"Code",value:T(d.transform),rows:10,mono:!0,placeholder:`def transform(ctx): + return ctx.input`,onChange:f=>u({...d,transform:f}),darkMode:o})}),k(!0,!1)]});break;case"parallel":{const f=z(d.parallel),$=g=>u({...d,parallel:g});se=s.jsxs(s.Fragment,{children:[s.jsxs(Y,{title:x,darkMode:o,children:[Ae("Children are edited on the canvas."),s.jsx(_e,{label:"Strategy",value:T(f.strategy)||"all",options:rr,onChange:g=>$({...f,strategy:g}),darkMode:o}),s.jsx(Se,{label:"Max concurrency",value:De(f.max_concurrency)||5,min:1,max:20,onChange:g=>$({...f,max_concurrency:g}),darkMode:o})]}),k(!1,!1)]});break}case"map":{const f=z(d.map),$=g=>u({...d,map:g});se=s.jsxs(s.Fragment,{children:[s.jsxs(Y,{title:x,darkMode:o,children:[ae("Agent",T(f.agent),S,g=>$({...f,agent:g}),"No agents registered"),s.jsx(de,{label:"Items",value:T(f.items),placeholder:"$.input.items",mono:!0,onChange:g=>$({...f,items:g}),darkMode:o}),s.jsx(de,{label:"Item key",value:T(f.item_key),onChange:g=>$({...f,item_key:g}),darkMode:o}),s.jsx(de,{label:"Index key",value:T(f.index_key),onChange:g=>$({...f,index_key:g}),darkMode:o}),s.jsx(Se,{label:"Max concurrency",value:De(f.max_concurrency)||4,min:1,max:64,onChange:g=>$({...f,max_concurrency:g}),darkMode:o}),s.jsx(_e,{label:"Strategy",value:T(f.strategy)||"all",options:rr,onChange:g=>$({...f,strategy:g}),darkMode:o}),s.jsx(Se,{label:"Item timeout (s)",value:De(f.item_timeout)||60,min:.1,step:.1,onChange:g=>$({...f,item_timeout:g}),darkMode:o}),s.jsx(_e,{label:"Fallback agent",value:T(f.fallback_agent),options:S,placeholder:"None",onChange:g=>$({...f,fallback_agent:g}),darkMode:o})]}),he(G(f.input),G(f.output),g=>u({...d,map:{...f,input:g},...ne(g)}),g=>$({...f,output:g})),k(!0,!0)]});break}case"loop":{const f=z(d.loop),$=g=>u({...d,loop:g});se=s.jsxs(s.Fragment,{children:[s.jsxs(Y,{title:x,darkMode:o,children:[s.jsx(Se,{label:"Max iterations",value:De(f.max_iterations)||10,min:1,max:100,onChange:g=>$({...f,max_iterations:g}),darkMode:o}),s.jsx(de,{label:"Until",value:T(f.until),placeholder:"e.g. $.result.done == true",mono:!0,onChange:g=>$({...f,until:g}),darkMode:o})]}),k(!1,!1)]});break}default:se=null}return s.jsxs("div",{className:"p-4",children:[ve,it(),wt(),!v&&Re(),se]})},vl=({issues:e,valid:t,validating:n,onSelectStep:r,darkMode:i})=>{const[a,l]=b.useState(!0),o=e.filter(p=>p.severity==="error"),c=e.filter(p=>p.severity==="warning");return s.jsxs("div",{className:`border-t flex flex-col ${a?"h-40":""} ${i?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[s.jsxs("div",{className:"flex items-center gap-3 px-4 py-2 shrink-0",children:[s.jsx("h3",{className:`text-sm font-semibold ${i?"text-gray-200":"text-gray-800"}`,children:"Problems"}),o.length>0&&s.jsxs("span",{className:`text-xs font-medium ${i?"text-red-400":"text-red-600"}`,children:[o.length," error",o.length!==1?"s":""]}),c.length>0&&s.jsxs("span",{className:`text-xs font-medium ${i?"text-amber-400":"text-amber-600"}`,children:[c.length," warning",c.length!==1?"s":""]}),t&&e.length===0&&s.jsxs("span",{className:`flex items-center gap-1 text-xs font-medium ${i?"text-green-400":"text-green-600"}`,children:[s.jsx(ft,{className:"w-4 h-4"}),"Valid"]}),n&&s.jsxs("span",{className:`flex items-center gap-1 text-xs ${i?"text-gray-400":"text-gray-500"}`,children:[s.jsx(ln,{className:"w-4 h-4 animate-spin"}),"Validating…"]}),s.jsx("button",{onClick:()=>l(!a),className:`ml-auto p-1 rounded transition-colors ${i?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:a?"Collapse":"Expand",children:a?s.jsx(sr,{className:"w-4 h-4"}):s.jsx(ar,{className:"w-4 h-4"})})]}),a&&s.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-3",children:e.length===0?s.jsxs("div",{className:`flex items-center gap-2 text-sm ${i?"text-gray-400":"text-gray-500"}`,children:[s.jsx(ft,{className:`w-4 h-4 ${i?"text-green-400":"text-green-600"}`}),"No problems — pipeline is valid"]}):[...o,...c].map((p,u)=>s.jsxs("button",{disabled:!p.stepName,onClick:()=>p.stepName&&r(p.stepName),className:`w-full flex items-start gap-2 text-left text-sm py-1 rounded ${p.stepName?"cursor-pointer hover:underline":"cursor-default"} ${p.severity==="error"?i?"text-red-400":"text-red-600":i?"text-amber-400":"text-amber-600"}`,children:[p.severity==="error"?s.jsx(cn,{className:"w-4 h-4 mt-0.5 shrink-0"}):s.jsx(lr,{className:"w-4 h-4 mt-0.5 shrink-0"}),p.stepName&&s.jsx("span",{className:`shrink-0 font-mono text-[10px] px-1.5 py-0.5 rounded ${i?"bg-gray-700 text-gray-300":"bg-gray-200 text-gray-600"}`,children:p.stepName}),s.jsx("span",{children:p.message})]},`${u}-${p.message}`))})]})},Nl=({yaml:e,applyError:t,onApply:n,onClose:r,darkMode:i})=>{const[a,l]=b.useState(e);b.useEffect(()=>{l(e)},[e]);const o=async()=>{try{await navigator.clipboard.writeText(a),oe.success("Copied to clipboard")}catch{oe.error("Failed to copy")}};return s.jsxs("div",{className:"fixed inset-0 z-40",children:[s.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:r}),s.jsxs("div",{className:`absolute right-0 top-0 h-full w-[480px] max-w-full flex flex-col shadow-2xl ${i?"bg-gray-800 border-l border-gray-700":"bg-white border-l border-gray-200"}`,children:[s.jsxs("div",{className:`flex items-center justify-between px-4 py-3 border-b ${i?"border-gray-700":"border-gray-200"}`,children:[s.jsx("h2",{className:`text-sm font-semibold ${i?"text-white":"text-gray-900"}`,children:"YAML"}),s.jsx("button",{onClick:r,className:`p-1.5 rounded transition-colors ${i?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"Close",children:s.jsx(vt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx("textarea",{value:a,onChange:c=>l(c.target.value),spellCheck:!1,className:`w-full h-full p-4 font-mono text-xs resize-none focus:outline-none ${i?"bg-gray-900 text-gray-200":"bg-gray-50 text-gray-800"}`})}),t&&s.jsx("div",{className:`px-4 py-2 text-xs border-t ${i?"bg-red-900/50 text-red-300 border-red-800":"bg-red-50 text-red-600 border-red-200"}`,children:t}),s.jsxs("div",{className:`flex items-center gap-2 px-4 py-3 border-t ${i?"border-gray-700":"border-gray-200"}`,children:[s.jsx("button",{onClick:o,className:`px-3 py-1.5 text-xs font-medium rounded transition-colors ${i?"bg-gray-700 text-gray-200 hover:bg-gray-600":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:"Copy"}),s.jsx("button",{onClick:()=>n(a),className:`px-3 py-1.5 text-xs font-medium text-white rounded transition-colors ${i?"bg-blue-600 hover:bg-blue-700":"bg-blue-500 hover:bg-blue-600"}`,children:"Apply YAML"})]})]})]})},Sl=({status:e,darkMode:t})=>{switch(e){case"success":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${t?"text-green-400":"text-green-600"}`,children:[s.jsx(ft,{className:"w-3.5 h-3.5"}),"Success"]});case"failed":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${t?"text-red-400":"text-red-600"}`,children:[s.jsx(cn,{className:"w-3.5 h-3.5"}),"Failed"]});case"running":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${t?"text-blue-400":"text-blue-600"}`,children:[s.jsx(ln,{className:"w-3.5 h-3.5 animate-spin"}),"Running"]});case"skipped":return s.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Skipped"});default:return s.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Pending"})}},_l=({open:e,pipelineName:t,running:n,result:r,error:i,inputSchema:a,inputSchemaSource:l,initialInput:o,onClose:c,onRun:p,darkMode:u})=>{const d=b.useMemo(()=>tt(a),[a]),[m,v]=b.useState({});if(b.useEffect(()=>{e&&v({...ai(d||void 0),...o})},[e,t,d,o]),!e)return null;const x=(()=>{switch(r?.status){case"success":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${u?"text-green-400":"text-green-600"}`,children:[s.jsx(ft,{className:"w-4 h-4"}),"Success"]});case"failed":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${u?"text-red-400":"text-red-600"}`,children:[s.jsx(cn,{className:"w-4 h-4"}),"Failed"]});case"partial":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${u?"text-amber-400":"text-amber-600"}`,children:[s.jsx(lr,{className:"w-4 h-4"}),"Partial"]});case"running":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${u?"text-blue-400":"text-blue-600"}`,children:[s.jsx(ln,{className:"w-4 h-4 animate-spin"}),"Running"]});default:return null}})();return s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:c}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"pipeline-run-title",className:`relative max-w-2xl w-full max-h-[85vh] flex flex-col rounded-xl shadow-2xl ${u?"bg-gray-800 border border-gray-700":"bg-white border border-gray-200"}`,children:[s.jsxs("div",{className:`flex items-center justify-between px-4 py-3 border-b shrink-0 ${u?"border-gray-700":"border-gray-200"}`,children:[s.jsxs("h2",{id:"pipeline-run-title",className:`text-sm font-semibold ${u?"text-white":"text-gray-900"}`,children:["Run pipeline"," ",s.jsx("span",{className:`font-mono text-xs ${u?"text-gray-400":"text-gray-500"}`,children:t})]}),s.jsx("button",{onClick:c,className:`p-1.5 rounded transition-colors ${u?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"Close","aria-label":"Close pipeline run dialog",children:s.jsx(vt,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:`mb-2 text-xs font-medium ${u?"text-gray-300":"text-gray-600"}`,children:"Test input"}),l==="inferred"&&s.jsx("p",{className:`mb-2 text-xs ${u?"text-blue-300":"text-blue-700"}`,children:"Suggested from unconnected fields in the draft's live resource contracts. Declare a pipeline input schema to take full control."}),s.jsx(vi,{schema:d,value:m,onChange:v,onSubmit:p,submitLabel:n?"Running…":"Run pipeline",disabled:n,darkMode:u}),l==="declared"&&s.jsx("p",{className:`mt-2 text-xs ${u?"text-gray-400":"text-gray-500"}`,children:"The live pipeline schema and defaults are prefilled. Switch Form, Dict, or Raw JSON mode to match the test case."})]}),i&&s.jsx("div",{className:`px-3 py-2 text-xs rounded-lg ${u?"bg-red-900/50 text-red-300":"bg-red-50 text-red-600"}`,children:i}),r&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[x,s.jsxs("span",{className:`text-xs ${u?"text-gray-400":"text-gray-500"}`,children:["Duration: ",r.durationMs," ms"]})]}),r.error&&s.jsx("div",{className:`px-3 py-2 text-xs rounded-lg ${u?"bg-red-900/50 text-red-300":"bg-red-50 text-red-600"}`,children:r.error}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:`block text-xs font-medium ${u?"text-gray-300":"text-gray-600"}`,children:"Output"}),s.jsx("pre",{className:`p-3 font-mono text-xs whitespace-pre-wrap break-all rounded-lg border overflow-auto max-h-64 ${u?"bg-gray-900 text-gray-200 border-gray-600":"bg-gray-50 text-gray-800 border-gray-300"}`,children:JSON.stringify(r.output,null,2)})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:`block text-xs font-medium ${u?"text-gray-300":"text-gray-600"}`,children:"Steps"}),s.jsxs("table",{className:`w-full text-xs border rounded-lg ${u?"border-gray-600":"border-gray-300"}`,children:[s.jsx("thead",{children:s.jsxs("tr",{className:`text-left ${u?"bg-gray-900 text-gray-400":"bg-gray-100 text-gray-500"}`,children:[s.jsx("th",{className:"px-3 py-2 font-medium",children:"Step"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Status"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Duration"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Error"})]})}),s.jsx("tbody",{children:Object.entries(r.steps).map(([S,w])=>s.jsxs("tr",{className:`border-t ${u?"border-gray-700 text-gray-300":"border-gray-200 text-gray-700"}`,children:[s.jsx("td",{className:"px-3 py-2 font-mono",children:S}),s.jsx("td",{className:"px-3 py-2",children:s.jsx(Sl,{status:w.status,darkMode:u})}),s.jsx("td",{className:"px-3 py-2",children:w.durationMs!==void 0?`${w.durationMs} ms`:"—"}),s.jsx("td",{className:`px-3 py-2 ${u?"text-red-400":"text-red-600"}`,children:w.error??""})]},S))})]})]})]})]})]})]})},le=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Cl=(e,t,n)=>{const r=e.config;if(e.kind==="agent")return t[typeof r.agent=="string"?r.agent:""]?.input_schema??null;if(e.kind==="map"){const i=le(r.map);return t[typeof i.agent=="string"?i.agent:""]?.input_schema??null}if(e.kind==="plugin"||e.kind==="endpoint"||e.kind==="ingestion"||e.kind==="sub_pipeline"){const i=typeof r[e.kind]=="string"?r[e.kind]:"";return n[`${e.kind}:${i}`]?.input_schema??null}return null},$l=e=>{const t=e.kind==="map"?le(le(e.config.map).input):le(e.config.input);return le(t.mappings??t)},Mr=e=>e.flatMap(t=>[t,...Mr(t.children)]),Al=(e,t)=>{const n=le(t.components),r=le(n.schemas);Object.keys(r).length>0&&(e.components={...le(e.components),schemas:{...le(le(e.components).schemas),...r}});const i=le(t.$defs);Object.keys(i).length>0&&(e.$defs={...le(e.$defs),...i})},jl=(e,t,n)=>{const r=tt(e.meta.input_schema);if(r&&Object.keys(r.properties??{}).length>0)return{schema:r,source:"declared"};const i={title:"Suggested test input",description:"Derived from unbound fields in the live contracts of this draft.",type:"object",properties:{}},a=new Set;for(const l of Mr(e.steps)){const o=Cl(l,t,n),c=o?tt(o):null;if(!c)continue;Al(i,c);const p=le(c.properties),u=new Set(Array.isArray(c.required)?c.required:[]),d=$l(l);if(c.type&&c.type!=="object"&&Object.keys(p).length===0){const v=d[jt];if(typeof v=="string"&&v.startsWith("$.input.")){const x=v.slice(8);i.properties[x]??=c,a.add(x)}continue}for(const[v,x]of Object.entries(p)){const S=d[v],w=typeof S=="string"&&S.startsWith("$.input.")?S.slice(8):S===void 0?v:"";w&&(i.properties[w]||(i.properties[w]=x),u.has(v)&&a.add(w))}}return Object.keys(i.properties).length===0?{schema:{},source:"unspecified"}:(a.size>0&&(i.required=Array.from(a)),{schema:i,source:"inferred"})},wl=350,Ll=()=>{const{config:e,darkMode:t,builderPipelineToLoad:n,setBuilderPipelineToLoad:r}=si(),[i,a]=b.useState(()=>Kt()),[l,o]=b.useState({type:"pipeline"}),[c,p]=b.useState([]),[u,d]=b.useState(!1),[m,v]=b.useState({agents:[],plugins:[],endpoints:[],ingestors:[],pipelines:[]}),[x,S]=b.useState(!0),[w,U]=b.useState(null),[D,K]=b.useState(0),[X,L]=b.useState({}),[y,O]=b.useState({}),[E,H]=b.useState({}),[ie,ne]=b.useState([]),[ge,Le]=b.useState(!1),[$e,Fe]=b.useState(!1),[Ae,ae]=b.useState(!1),[k,Me]=b.useState(null),[he,ye]=b.useState(!1),[ve,it]=b.useState(!1),[wt,Re]=b.useState(null),[se,f]=b.useState(null),[$,g]=b.useState({}),[B,W]=b.useState(!1),je=b.useRef(null),we=b.useRef(0),F=b.useMemo(()=>e?.apiUrl?new oi(e.apiUrl,e.apiKey||void 0):null,[e?.apiKey,e?.apiUrl]);b.useEffect(()=>{if(!F){S(!1);return}let h=!1;return(async()=>{S(!0);try{const _=await Promise.all([F.listAgents().then(N=>({label:"agents",value:N,error:null})).catch(N=>({label:"agents",value:[],error:N})),F.listPlugins().then(N=>({label:"plugins",value:N,error:null})).catch(N=>({label:"plugins",value:[],error:N})),F.listEndpoints().then(N=>({label:"endpoints",value:N,error:null})).catch(N=>({label:"endpoints",value:[],error:N})),F.listIngestors().then(N=>({label:"ingestors",value:N,error:null})).catch(N=>({label:"ingestors",value:[],error:N})),F.listPipelines().then(N=>({label:"pipelines",value:N,error:null})).catch(N=>({label:"pipelines",value:[],error:N}))]);if(h)return;const[C,I,q,ce,It]=_,yn=C.value,vn=I.value,Nn=q.value,Sn=ce.value,Lt=It.value,ii={agents:yn.map(N=>({name:N.name,description:N.description})),plugins:vn.map(N=>({name:N.name,description:N.description})),endpoints:Nn.map(N=>({name:N.name,description:N.description})),ingestors:Sn.map(N=>({name:N.name,description:N.description})),pipelines:Lt.map(N=>({name:N.name,description:N.description}))},_n=await Promise.all(yn.map(async N=>{try{return{key:`agent:${N.name}`,schema:await F.getSchemas(N.name),error:null}}catch{return{key:`agent:${N.name}`,schema:null,error:`Live agent schema for '${N.name}' is unavailable.`}}})),Cn=await Promise.all([...vn.map(async N=>{const pe=`plugin:${N.name}`;try{return{key:pe,contract:await F.getOperationContract(`/api/v1/plugins/${encodeURIComponent(N.name)}/predict`),error:null}}catch{return{key:pe,contract:null,error:`Live plugin schema for '${N.name}' is unavailable.`}}}),...Nn.map(async N=>{const pe=`endpoint:${N.name}`;try{return{key:pe,contract:await F.getEndpointContract(N),error:null}}catch{return{key:pe,contract:null,error:`Live endpoint schema for '${N.name}' is unavailable.`}}}),...Sn.map(async N=>{const pe=`ingestion:${N.name}`;try{return{key:pe,contract:await F.getOperationContract(`/api/v1/ingestion/${encodeURIComponent(N.name)}/run`),error:null}}catch{return{key:pe,contract:null,error:`Live ingestor schema for '${N.name}' is unavailable.`}}}),...Lt.map(async N=>{const pe=`sub_pipeline:${N.name}`;try{const An=await F.getPipelineConfig(N.name);return{key:pe,contract:{input_schema:tt(An.input_schema),output_schema:tt(An.output_schema)},error:null}}catch{return{key:pe,contract:null,error:`Live sub-pipeline schema for '${N.name}' is unavailable.`}}})]);if(h)return;v(ii),L(Object.fromEntries(_n.flatMap(N=>N.schema?[[N.key.slice(6),N.schema]]:[]))),O(Object.fromEntries(Cn.flatMap(N=>N.contract?[[N.key,N.contract]]:[]))),H(Object.fromEntries([..._n,...Cn].flatMap(N=>N.error?[[N.key,N.error]]:[]))),ne(Lt.map(N=>({name:N.name,description:N.description})));const $n=_.filter(N=>N.error).map(N=>N.label);U($n.length?`Could not load live ${$n.join(", ")}. Check authentication, rate limits, or connectivity, then retry.`:null)}catch(_){h||U(_?.message||"Could not load the live Builder palette. Retry after checking connectivity.")}finally{h||S(!1)}})(),()=>{h=!0}},[F,D]),b.useEffect(()=>{if(!F)return;d(!0),je.current&&clearTimeout(je.current);const h=++we.current;return je.current=setTimeout(async()=>{try{const _=Mn(i),C=await F.validatePipelineDraft({pipeline:pt(i)});if(h!==we.current)return;p(Mo(_,C.errors,C.warnings))}catch{if(h!==we.current)return;p(Mn(i))}finally{h===we.current&&d(!1)}},wl),()=>{je.current&&clearTimeout(je.current)}},[i,F]);const V=b.useMemo(()=>{const h=Ho(c);let _=0,C=0;for(const I of c)I.severity==="error"?_+=1:C+=1;return{byStep:h,errors:_,warnings:C}},[c]),Et=b.useMemo(()=>Ro(i),[i]),at=b.useMemo(()=>jl(i,X,y),[X,i,y]),Pe=b.useCallback(h=>{a(_=>{const C=h==="agent"?m.agents[0]?.name:h==="plugin"?m.plugins[0]?.name:h==="endpoint"?m.endpoints[0]?.name:h==="ingestion"?m.ingestors[0]?.name:h==="sub_pipeline"?m.pipelines.find(It=>It.name!==_.meta.name)?.name:void 0,I=["agent","plugin","endpoint","ingestion","sub_pipeline"].includes(h)?h:null,q=C&&I?Vn(_,I,C):Uo(_,h),ce=q.steps[q.steps.length-1];return ce&&(o({type:"step",id:ce.id,childPath:[]}),W(!0)),q})},[m]),Ne=b.useCallback((h,_)=>{a(C=>{const I=Vn(C,h,_),q=I.steps[I.steps.length-1];return q&&(o({type:"step",id:q.id,childPath:[]}),W(!0)),I})},[]),Hr=b.useCallback(h=>{a(_=>{const C=qo(_,h),I=C.steps.find(ce=>ce.id===h),q=I?.children[I.children.length-1];return q&&(o({type:"step",id:h,childPath:[q.id]}),W(!0)),C})},[]),Qr=b.useCallback((h,_)=>{o(h?{type:"step",id:h,childPath:_??[]}:{type:"pipeline"}),h&&W(!0)},[]),Jr=b.useCallback(h=>{const _=i.steps.find(C=>C.name===h);if(_){o({type:"step",id:_.id,childPath:[]});return}for(const C of i.steps){const I=C.children.find(q=>q.name===h);if(I){o({type:"step",id:C.id,childPath:[I.id]});return}}},[i.steps]),Xr=b.useCallback(async()=>{if(F){Le(!0);try{const h=pt(i),_=await F.savePipeline(i.meta.name,{pipeline:h});if(_.valid)oe.success(`Saved pipeline '${_.name}'`),ne(C=>C.some(q=>q.name===_.name)?C:[...C,{name:_.name}]);else{const C=_.errors.join(" · ")||"Pipeline validation failed";oe.error(C)}}catch(h){let _=h?.message||"Failed to save pipeline";try{const C=JSON.parse(h?.body||"{}")?.detail;C?.message&&(_=C.message),Array.isArray(C?.errors)&&C.errors.length>0&&(_=`${C.message}: ${C.errors.join(" · ")}`)}catch{}oe.error(_)}finally{Le(!1)}}},[F,i]),Zr=b.useCallback(async()=>{if(!F)return;const h=i.meta.name;if(window.confirm(`Delete pipeline '${h}'? This removes its YAML file.`)){Fe(!0);try{await F.deletePipeline(h),oe.success(`Deleted pipeline '${h}'`),a(Kt()),o({type:"pipeline"}),g({}),ne(_=>_.filter(C=>C.name!==h))}catch(_){let C=_?.message||"Failed to delete pipeline";try{const I=JSON.parse(_?.body||"{}")?.detail;typeof I=="string"?C=I:I?.message&&(C=I.message)}catch{}oe.error(C)}finally{Fe(!1)}}},[F,i.meta.name]),kt=b.useCallback(async h=>{if(F)try{const _=await F.getPipelineConfig(h);a(qr(_)),o({type:"pipeline"}),g({}),Re(null),f(null),oe.success(`Loaded pipeline '${h}'`)}catch(_){oe.error(_?.message||`Failed to load pipeline '${h}'`)}},[F]);b.useEffect(()=>{!n||!F||kt(n).finally(()=>r(null))},[n,F,kt,r]);const ei=b.useCallback(()=>{a(Kt()),o({type:"pipeline"}),g({}),Re(null),f(null)},[]),ti=b.useCallback(async h=>{if(F){it(!0),f(null),Re(null),g({});try{const _=await F.savePipeline(i.meta.name,{pipeline:pt(i)});if(!_.valid)throw new Error(_.errors.join(" · ")||"Pipeline validation failed");ne(q=>q.some(ce=>ce.name===_.name)?q:[...q,{name:_.name}]);const C=await F.runPipeline(i.meta.name,{input:h}),I={};for(const[q,ce]of Object.entries(C.steps))I[q]={status:ce.status,durationMs:ce.duration_ms,error:ce.error};g(I),Re({status:C.status,output:C.output,steps:I,durationMs:C.duration_ms,error:C.error}),C.status==="success"?oe.success(`Pipeline run completed in ${C.duration_ms.toFixed(1)}ms`):oe.error(C.error||`Pipeline run finished with status '${C.status}'`)}catch(_){let C=_?.message||"Failed to run pipeline";try{const I=JSON.parse(_?.body||"{}")?.detail;typeof I=="string"?C=I:I?.message?C=I.message:Array.isArray(I?.errors)&&I.errors.length>0&&(C=I.errors.join(" · "))}catch{}f(C),oe.error(C)}finally{it(!1)}}},[F,i]),ni=b.useCallback(h=>{try{const _=Po(h);a(_),o({type:"pipeline"}),Me(null),oe.success("YAML applied — canvas updated")}catch(_){Me(_?.message||"Invalid YAML")}},[]),ri=[{title:"Agents",items:m.agents,color:"blue",kind:"agent"},{title:"Plugins",items:m.plugins,color:"purple",kind:"plugin"},{title:"Endpoints",items:m.endpoints,color:"emerald",kind:"endpoint"},{title:"Ingestors",items:m.ingestors,color:"teal",kind:"ingestion"},{title:"Sub-pipelines",items:m.pipelines.filter(h=>h.name!==i.meta.name),color:"cyan",kind:"sub_pipeline"}],Tt=t?"bg-gray-800 text-white":"bg-white text-gray-900",Ot=t?"border-gray-700":"border-gray-200",st=t?"text-gray-400":"text-gray-500";return s.jsxs("div",{className:`flex flex-col h-full ${t?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[s.jsxs("div",{className:`flex min-h-14 flex-wrap items-center gap-2 border-b px-3 py-2 sm:px-4 ${Ot} ${Tt} flex-shrink-0`,children:[s.jsx("input",{value:i.meta.name,onChange:h=>a(Wr(i,{...i.meta,name:h.target.value})),placeholder:"pipeline_name","aria-label":"Pipeline name",className:`min-w-0 flex-1 px-3 py-1.5 rounded-lg border text-sm font-medium sm:w-52 sm:flex-none focus:outline-none focus:ring-2 focus:ring-blue-500 ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,title:"Pipeline name"}),s.jsxs("button",{onClick:ei,className:`flex items-center px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${t?"hover:bg-gray-700 text-gray-200":"hover:bg-gray-100 text-gray-700"}`,title:"New pipeline",children:[s.jsx(jn,{className:"w-4 h-4 mr-1.5"}),"New"]}),s.jsxs("select",{defaultValue:"",onChange:h=>{h.target.value&&Pe(h.target.value),h.target.value=""},className:`px-3 py-1.5 rounded-lg border text-sm focus:outline-none lg:hidden ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,"aria-label":"Quick add pipeline step",children:[s.jsx("option",{value:"",children:"Add step…"}),wn.map(h=>s.jsx("option",{value:h.kind,children:h.label},h.kind))]}),s.jsxs("select",{value:"",onChange:h=>h.target.value&&kt(h.target.value),className:`px-3 py-1.5 rounded-lg border text-sm focus:outline-none ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,"aria-label":"Load existing pipeline",title:"Load existing pipeline",children:[s.jsx("option",{value:"",disabled:!0,children:ie.length>0?"Load…":"No saved pipelines"}),ie.map(h=>s.jsx("option",{value:h.name,children:h.name},h.name))]}),s.jsx("div",{className:"hidden flex-1 sm:block"}),s.jsx("div",{className:`flex items-center text-xs font-medium px-3 py-1.5 rounded-full ${V.errors>0?t?"bg-red-900 text-red-200":"bg-red-100 text-red-700":V.warnings>0?t?"bg-amber-900 text-amber-200":"bg-amber-100 text-amber-700":t?"bg-green-900 text-green-200":"bg-green-100 text-green-700"}`,children:u?s.jsx("span",{children:"Validating…"}):V.errors>0?s.jsxs("span",{children:[V.errors," error",V.errors!==1?"s":""]}):V.warnings>0?s.jsxs("span",{children:[V.warnings," warning",V.warnings!==1?"s":""]}):s.jsxs("span",{className:"flex items-center",children:[s.jsx(Ci,{className:"w-4 h-4 mr-1"})," Valid"]})}),s.jsxs("button",{onClick:()=>ae(!0),className:`flex items-center px-3 py-1.5 rounded-lg text-sm font-medium ${t?"bg-gray-700 text-gray-200 hover:bg-gray-600":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,title:"YAML view",children:[s.jsx(Ai,{className:"w-4 h-4 mr-1.5"}),"YAML"]}),s.jsxs("button",{onClick:Xr,disabled:ge||ve||V.errors>0,className:`flex items-center px-4 py-1.5 rounded-lg text-sm font-medium text-white transition-colors ${ge||ve||V.errors>0?"bg-gray-400 cursor-not-allowed":"bg-blue-600 hover:bg-blue-700"}`,title:V.errors>0?"Fix validation errors before saving":"Save pipeline",children:[s.jsx(Si,{className:"w-4 h-4 mr-1.5"}),ge?"Saving…":"Save"]}),s.jsxs("button",{onClick:()=>ye(!0),disabled:ge||ve||V.errors>0,className:`flex items-center px-4 py-1.5 rounded-lg text-sm font-medium text-white transition-colors ${ge||ve||V.errors>0?"bg-gray-400 cursor-not-allowed":"bg-green-600 hover:bg-green-700"}`,title:V.errors>0?"Fix validation errors before running":"Save this draft, then run it with test input",children:[s.jsx(wi,{className:"w-4 h-4 mr-1.5"}),ve?"Running…":"Save & Run"]}),s.jsxs("button",{onClick:Zr,disabled:$e,className:`flex items-center px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${t?"text-red-300 hover:bg-red-900/40":"text-red-600 hover:bg-red-50"}`,title:"Delete pipeline",children:[s.jsx(li,{className:"w-4 h-4 mr-1.5"}),$e?"…":"Delete"]}),s.jsx("button",{type:"button",onClick:()=>W(h=>!h),className:`rounded-lg px-3 py-1.5 text-sm font-medium xl:hidden ${t?"bg-gray-700 text-gray-200":"bg-gray-100 text-gray-700"}`,"aria-expanded":B,children:"Inspector"})]}),(x||w)&&s.jsxs("div",{role:"status",className:`flex flex-wrap items-center justify-between gap-2 border-b px-3 py-2 text-xs sm:px-4 ${w?t?"border-amber-900 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800":t?"border-gray-700 bg-gray-800 text-gray-300":"border-gray-200 bg-gray-50 text-gray-600"}`,children:[s.jsx("span",{children:w||"Refreshing live Builder resources and contracts…"}),w&&s.jsx("button",{type:"button",onClick:()=>K(h=>h+1),className:`rounded-md border px-2 py-1 font-medium ${t?"border-amber-700 hover:bg-amber-900/60":"border-amber-300 hover:bg-amber-100"}`,children:"Retry live resources"})]}),s.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden",children:[s.jsxs("div",{className:`hidden w-56 flex-shrink-0 overflow-y-auto border-r lg:block ${Ot} ${Tt} p-3`,children:[s.jsx("h3",{className:`text-xs font-semibold uppercase tracking-wider mb-2 ${st}`,children:"Step types"}),s.jsx("div",{className:"space-y-1.5 mb-4",children:wn.map(h=>{const _=Ye[h.kind];return s.jsx("button",{onClick:()=>Pe(h.kind),draggable:!0,onDragStart:C=>{C.dataTransfer.effectAllowed="copy",C.dataTransfer.setData("application/x-agentomatic-step-kind",h.kind)},className:`w-full text-left px-3 py-2 rounded-lg border transition-colors ${t?"hover:bg-gray-700 border-gray-700":"hover:bg-gray-50 border-gray-200"}`,title:h.description,children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("span",{className:`text-[10px] font-semibold px-1.5 py-0.5 rounded ${_.badge}`,children:_.label}),s.jsx(jn,{className:`w-3.5 h-3.5 ml-auto ${st}`})]})},h.kind)})}),ri.map(h=>s.jsxs("div",{className:"mb-3",children:[s.jsxs("h3",{className:`text-xs font-semibold uppercase tracking-wider mb-1.5 ${st}`,children:[h.title," (",h.items.length,")"]}),h.items.length===0?s.jsx("p",{className:`text-xs italic ${st}`,children:"none"}):s.jsx("div",{className:"flex flex-wrap gap-1",children:h.items.map(_=>s.jsxs("button",{type:"button",draggable:!0,onClick:()=>Ne(h.kind,_.name),onDragStart:C=>{C.dataTransfer.effectAllowed="copy",C.dataTransfer.setData("application/x-agentomatic-resource",JSON.stringify({kind:h.kind,name:_.name}))},title:`Add configured ${h.kind.replace("_"," ")} step for ${_.name}`,className:`rounded px-1.5 py-0.5 text-left text-xs transition-colors ${t?"bg-gray-700 text-gray-300 hover:bg-gray-600 hover:text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200 hover:text-gray-900"}`,children:["+ ",_.name]},_.name))})]},h.title))]}),s.jsx("div",{className:"flex-1 min-w-0 overflow-auto p-3 sm:p-4",children:s.jsx(nl,{draft:i,selectedId:l.type==="step"?l.id:null,selectedChildPath:l.type==="step"?l.childPath:null,runStatuses:$,issueCounts:V.byStep,onSelect:Qr,onReorder:(h,_,C)=>a(I=>zn(I,h,_,C)),onMove:(h,_)=>{a(C=>{const I=C.steps.findIndex(q=>q.id===h);return I===-1?C:zn(C,I,I+_)})},onAddChild:Hr,onRemoveChild:(h,_)=>a(C=>Yo(C,h,_)),onDelete:h=>a(_=>Ko(_,h)),onAddFromPalette:Pe,onAddResource:Ne,darkMode:t})}),s.jsx("div",{className:`${B?"absolute inset-3 z-40 flex shadow-2xl":"hidden"} w-auto overflow-y-auto rounded-2xl border xl:static xl:flex xl:w-96 xl:flex-shrink-0 xl:rounded-none xl:border-y-0 xl:border-r-0 xl:border-l ${Ot} ${Tt}`,children:s.jsx(yl,{draft:i,selection:l,resources:m,agentSchemas:X,resourceSchemas:y,resourceContractErrors:E,onChange:a,darkMode:t})})]}),s.jsx("div",{className:"flex-shrink-0 border-t border-gray-200 dark:border-gray-700",children:s.jsx(vl,{issues:c,valid:V.errors===0,validating:u,onSelectStep:Jr,darkMode:t})}),Ae&&s.jsx(Nl,{yaml:Et,applyError:k,onApply:ni,onClose:()=>ae(!1),darkMode:t}),s.jsx(_l,{open:he,pipelineName:i.meta.name,running:ve,result:wt,error:se,inputSchema:at.schema,inputSchemaSource:at.source,initialInput:i.meta.defaults,onClose:()=>ye(!1),onRun:ti,darkMode:t})]})};export{Ll as BuilderView}; diff --git a/src/agentomatic/studio/static/assets/BuilderView-C296ULRo.js b/src/agentomatic/studio/static/assets/BuilderView-C296ULRo.js deleted file mode 100644 index b8ddf955..00000000 --- a/src/agentomatic/studio/static/assets/BuilderView-C296ULRo.js +++ /dev/null @@ -1,46 +0,0 @@ -import{j as s,V as se,p as tt,a as ui,u as pi,A as di,F as Un,g as fi}from"./index-FSSL6O5F.js";import{r as y,R as mi}from"./react-vendor-BHJ3EV8m.js";import{F as gi,R as hi,L as xi,N as bi,B as yi,I as vi,G as Ni,P as ji,a as Si,b as yr,C as vr,c as Nr,T as Ai,d as jr,X as wt,e as vt,f as bn,g as yn,A as Sr}from"./ui-vendor-DIaV1y77.js";import{S as Ci}from"./SchemaForm-DyHc2s7z.js";import"./syntax-vendor-ru7AzRyY.js";function $i({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"}))}const wi=y.forwardRef($i);function _i({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const ki=y.forwardRef(_i);function Ti({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17.25 6.75 22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3-4.5 16.5"}))}const Ei=y.forwardRef(Ti);function Ii({title:e,titleId:t,...n},r){return y.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":t},n),e?y.createElement("title",{id:t},e):null,y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"}))}const Oi=y.forwardRef(Ii),qe={agent:{label:"Agent",description:"Invoke a registered agent",icon:"Bot",badge:"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",accent:"border-blue-500"},plugin:{label:"Plugin",description:"Call an ML plugin predict",icon:"Puzzle",badge:"bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300",accent:"border-purple-500"},endpoint:{label:"Endpoint",description:"Call a custom endpoint",icon:"Globe",badge:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",accent:"border-emerald-500"},ingestion:{label:"Ingestion",description:"Run an ingestor",icon:"Inbox",badge:"bg-teal-100 text-teal-700 dark:bg-teal-900 dark:text-teal-300",accent:"border-teal-500"},transform:{label:"Transform",description:"Python code block",icon:"Braces",badge:"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",accent:"border-amber-500"},parallel:{label:"Parallel",description:"Fan out agent steps",icon:"Network",badge:"bg-pink-100 text-pink-700 dark:bg-pink-900 dark:text-pink-300",accent:"border-pink-500"},map:{label:"Map",description:"Agent over a list of items",icon:"ListTree",badge:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300",accent:"border-indigo-500"},loop:{label:"Loop",description:"Iterate an agent step",icon:"Repeat",badge:"bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300",accent:"border-orange-500"},sub_pipeline:{label:"Sub-pipeline",description:"Nest another pipeline",icon:"FolderTree",badge:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300",accent:"border-cyan-500"}},Bn=[{kind:"agent",label:"Agent step",description:"Invoke a registered agent"},{kind:"endpoint",label:"Endpoint step",description:"Call a custom endpoint"},{kind:"plugin",label:"Plugin step",description:"Call an ML plugin predict"},{kind:"ingestion",label:"Ingestion step",description:"Run an ingestor"},{kind:"transform",label:"Transform step",description:"Python code block"},{kind:"parallel",label:"Parallel container",description:"Fan out agent steps"},{kind:"map",label:"Map step",description:"Agent over a list of items"},{kind:"loop",label:"Loop container",description:"Iterate an agent step"},{kind:"sub_pipeline",label:"Sub-pipeline step",description:"Nest another pipeline"}];function Xt(e,t){switch(e){case"agent":return{name:t,agent:""};case"plugin":return{name:t,plugin:""};case"endpoint":return{name:t,endpoint:""};case"ingestion":return{name:t,ingestion:""};case"transform":return{name:t,transform:""};case"parallel":return{name:t,parallel:{steps:[]}};case"map":return{name:t,map:{agent:"",items:"$.input.items"}};case"loop":return{name:t,loop:{step:{}}};case"sub_pipeline":return{name:t,sub_pipeline:""}}}function Ri(e,t){return e==="parallel"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Xt("agent",`${t}_child_1`),children:[]}]:e==="loop"?[{id:`${t}-child-1`,kind:"agent",name:`${t}_child_1`,config:Xt("agent",`${t}_child_1`),children:[]}]:[]}var L=Symbol("NOT_RESOLVED"),vn=Symbol("MERGE_KEY");function X(e,t){return{tagName:e,nodeKind:"scalar",implicit:t.implicit??!1,matchByTagPrefix:t.matchByTagPrefix??!1,implicitFirstChars:t.implicitFirstChars??null,resolve:t.resolve,identify:t.identify??null,represent:t.represent??(n=>String(n)),representTagName:t.representTagName??null}}function Nn(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"sequence",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addItem:t.addItem,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify??null,represent:t.represent??(r=>r),representTagName:t.representTagName??null}}function _t(e,t){const n=t.finalize===void 0;return{tagName:e,nodeKind:"mapping",implicit:!1,matchByTagPrefix:t.matchByTagPrefix??!1,create:t.create,addPair:t.addPair,has:t.has,keys:t.keys,get:t.get,finalize:t.finalize??(r=>r),carrierIsResult:n,identify:t.identify??null,represent:t.represent??(r=>r),representTagName:t.representTagName??null}}var Li=X("tag:yaml.org,2002:str",{resolve:e=>e,identify:e=>typeof e=="string"}),Fi=["","~","null","Null","NULL"],Pi=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Fi.indexOf(e)!==-1?null:L,identify:e=>e===null,represent:()=>"null"}),Di=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["n"],resolve:(e,t)=>e==="null"||t&&e===""?null:L,identify:e=>e===null,represent:()=>"null"}),Ui=["","~","null","Null","NULL"],Bi=X("tag:yaml.org,2002:null",{implicit:!0,implicitFirstChars:["","~","n","N"],resolve:e=>Ui.indexOf(e)!==-1?null:L,identify:e=>e===null,represent:()=>"null"}),Yi=["true","True","TRUE"],qi=["false","False","FALSE"],Ki=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","T","f","F"],resolve:e=>Yi.indexOf(e)!==-1?!0:qi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Hi=["true"],Vi=["false"],Wi=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["t","f"],resolve:e=>Hi.indexOf(e)!==-1?!0:Vi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Gi=["true","True","TRUE","y","Y","yes","Yes","YES","on","On","ON"],zi=["false","False","FALSE","n","N","no","No","NO","off","Off","OFF"],Ji=X("tag:yaml.org,2002:bool",{implicit:!0,implicitFirstChars:["y","Y","n","N","t","T","f","F","o","O"],resolve:e=>Gi.indexOf(e)!==-1?!0:zi.indexOf(e)!==-1?!1:L,identify:e=>Object.prototype.toString.call(e)==="[object Boolean]",represent:e=>e?"true":"false"}),Qi=new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$"),Xi=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function Mi(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function Zi(e,t){if(t){if(!Xi.test(e))return L}else if(!Qi.test(e))return L;const n=Mi(e);return Number.isFinite(n)?n:L}var Ar=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:Zi,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),ea=new RegExp("^-?(?:0|[1-9][0-9]*)$"),ta=new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");function na(e){let t=e,n=1;return(t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b")?n*parseInt(t.slice(2),2):t.startsWith("0o")?n*parseInt(t.slice(2),8):t.startsWith("0x")?n*parseInt(t.slice(2),16):n*parseInt(t,10)}function ra(e,t){if(t){if(!ta.test(e))return L}else if(!ea.test(e))return L;const n=na(e);return Number.isFinite(n)?n:L}var ia=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:ra,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),aa=new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$");function sa(e){let t=e.replace(/_/g,""),n=1;if((t[0]==="-"||t[0]==="+")&&(t[0]==="-"&&(n=-1),t=t.slice(1)),t.startsWith("0b"))return n*parseInt(t.slice(2),2);if(t.startsWith("0x"))return n*parseInt(t.slice(2),16);if(t.includes(":")){let r=0;for(const i of t.split(":"))r=r*60+Number(i);return n*r}return t!=="0"&&t[0]==="0"?n*parseInt(t,8):n*parseInt(t,10)}function oa(e){if(!aa.test(e))return L;const t=sa(e);return Number.isFinite(t)?t:L}var Mt=X("tag:yaml.org,2002:int",{implicit:!0,implicitFirstChars:["-","+",..."0123456789"],resolve:oa,identify:e=>Number.isInteger(e)&&!Object.is(e,-0)&&e.toString(10).indexOf("e")<0,represent:e=>e.toString(10)}),la=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),ca=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ua(e){if(!la.test(e))return L;let t=e.toLowerCase();const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;const r=n*parseFloat(t);return Number.isFinite(r)||ca.test(e)?r:L}function pa(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var Cr=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:ua,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:pa}),da=new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$"),fa=new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ma(e,t){if(t){if(!fa.test(e))return L;let r=e.toLowerCase();const i=r[0]==="-"?-1:1;if("+-".includes(r[0])&&(r=r.slice(1)),r===".inf")return i===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(r===".nan")return NaN;const a=i*parseFloat(r);return Number.isFinite(a)?a:L}if(!da.test(e))return L;const n=Number(e);return Number.isFinite(n)?n:L}function ga(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var ha=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-",..."0123456789"],resolve:ma,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:ga}),xa=new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),ba=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ya(e){if(!xa.test(e))return L;let t=e.toLowerCase().replace(/_/g,"");const n=t[0]==="-"?-1:1;if("+-".includes(t[0])&&(t=t.slice(1)),t===".inf")return n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;let r=0;if(t.includes(":")){for(const i of t.split(":"))r=r*60+Number(i);r*=n}else r=n*parseFloat(t);return Number.isFinite(r)||ba.test(e)?r:L}function va(e){if(isNaN(e))return".nan";if(e===Number.POSITIVE_INFINITY)return".inf";if(e===Number.NEGATIVE_INFINITY)return"-.inf";if(Object.is(e,-0))return"-0.0";const t=e.toString(10);return/^[-+]?[0-9]+e/.test(t)?t.replace("e",".e"):t}var Zt=X("tag:yaml.org,2002:float",{implicit:!0,implicitFirstChars:["-","+",".",..."0123456789"],resolve:ya,identify:e=>typeof e=="number"&&(!Number.isInteger(e)||Object.is(e,-0)||e.toString(10).indexOf("e")>=0),represent:va}),Na=X("tag:yaml.org,2002:merge",{implicit:!0,implicitFirstChars:["<"],resolve:(e,t)=>e==="<<"||t&&e===""?vn:L}),ja=/^[A-Za-z0-9+/]*={0,2}$/;function Sa(e){const t=e.replace(/\s/g,"");if(t.length%4!==0||!ja.test(t))return L;const n=atob(t),r=new Uint8Array(n.length);for(let i=0;iObject.prototype.toString.call(e)==="[object Uint8Array]",represent:Aa}),$a=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),wa=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function Yn(e,t,n,r=0,i=0,a=0,l=0){const o=new Date(Date.UTC(e,t,n,r,i,a,l));return o.setUTCFullYear(e,t,n),o}function _a(e){let t=$a.exec(e);if(t===null&&(t=wa.exec(e)),t===null)return L;const n=+t[1],r=+t[2]-1,i=+t[3];if(!t[4]){const c=Yn(n,r,i);return c.getUTCFullYear()!==n||c.getUTCMonth()!==r||c.getUTCDate()!==i?L:c}const a=+t[4],l=+t[5],o=+t[6];let u=0;if(a>23||l>59||o>59)return L;if(t[7]){let c=t[7].slice(0,3);for(;c.length<3;)c+="0";u=+c}const p=Yn(n,r,i,a,l,o,u);if(p.getUTCFullYear()!==n||p.getUTCMonth()!==r||p.getUTCDate()!==i)return L;if(t[9]){const c=+t[10],f=+(t[11]||0);if(c>23||f>59)return L;const m=(c*60+f)*6e4;p.setTime(p.getTime()-(t[9]==="-"?-m:m))}return p}var ka=X("tag:yaml.org,2002:timestamp",{implicit:!0,implicitFirstChars:[..."0123456789"],resolve:_a,identify:e=>e instanceof Date,represent:e=>e.toISOString()}),Ta=Nn("tag:yaml.org,2002:seq",{create:()=>[],addItem:(e,t)=>{e.push(t)},identify:Array.isArray});function kt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function en(e,t){const n={};for(const r of t)e[r]!==void 0&&(n[r]=e[r]);return n}var Ea=Nn("tag:yaml.org,2002:omap",{create:()=>({list:[],seen:new Set}),addItem:(e,t)=>{let n;if(t instanceof Map){if(t.size!==1)return"cannot resolve an ordered map item";n=t.keys().next().value}else if(kt(t)){const r=Object.keys(t);if(r.length!==1)return"cannot resolve an ordered map item";n=r[0]}else return"cannot resolve an ordered map item";return e.seen.has(n)?"duplicate key in ordered map":(e.seen.add(n),e.list.push(t),"")},finalize:e=>e.list}),Ia=Nn("tag:yaml.org,2002:pairs",{create:()=>[],addItem:(e,t)=>{if(t instanceof Map)return t.size!==1?"cannot resolve a pairs item":(e.push(t.entries().next().value),"");if(Object.prototype.toString.call(t)!=="[object Object]")return"cannot resolve a pairs item";const n=t,r=Object.keys(n);return r.length!==1?"cannot resolve a pairs item":(e.push([r[0],n[r[0]]]),"")}}),Oa=_t("tag:yaml.org,2002:map",{create:()=>({}),identify:kt,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{if(t!==null&&typeof t=="object")return"object-based map does not support complex keys";const r=String(t);return r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,""},has:(e,t)=>t!==null&&typeof t=="object"?!1:Object.prototype.hasOwnProperty.call(e,String(t)),keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}}),Ra=_t("tag:yaml.org,2002:set",{create:()=>new Set,identify:e=>e instanceof Set,represent:e=>{const t=new Map;for(const n of e)t.set(n,null);return t},addPair:(e,t,n)=>n!==null?"cannot resolve a set item":(e.add(t),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:()=>null});function La(){return{scalar:Object.create(null),sequence:Object.create(null),mapping:Object.create(null)}}function Fa(){return{scalar:[],sequence:[],mapping:[]}}function Pa(e){const t=[];for(const n of e){let r=t.length;for(let i=0;ic.implicitFirstChars===null),o=new Set;for(const c of r)if(c.implicitFirstChars!==null)for(const f of c.implicitFirstChars)o.add(f);const u=new Map;for(const c of o)u.set(c,r.filter(f=>f.implicitFirstChars===null||f.implicitFirstChars.indexOf(c)!==-1));const p=i.scalar["tag:yaml.org,2002:str"];if(!p)throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)");this.tags=n,this.implicitScalarTags=r,this.implicitScalarByFirstChar=u,this.implicitScalarAnyFirstChar=l,this.defaultScalarTag=p,this.defaultSequenceTag=i.sequence["tag:yaml.org,2002:seq"],this.defaultMappingTag=i.mapping["tag:yaml.org,2002:map"],this.exact=i,this.prefix=a}withTags(...t){let n=[];for(const r of t)n=n.concat(r);return new $r([...this.tags,...n])}},jn=new Tt([Li,Ta,Oa]);new Tt([...jn.tags,Di,Wi,ia,ha]);var Da=new Tt([...jn.tags,Pi,Ki,Ar,Cr]),Ua=new Tt([...jn.tags,Bi,Ji,Mt,Zt,ka,Na,Ca,Ea,Ia,Ra]);_t("tag:yaml.org,2002:map",{create:()=>new Map,addPair:(e,t,n)=>(e.set(t,n),""),has:(e,t)=>e.has(t),keys:e=>e.keys(),get:(e,t)=>e.get(t),identify:e=>e instanceof Map||kt(e),represent:e=>{if(e instanceof Map)return e;const t=new Map,n=e;for(const r of Object.keys(n))t.set(r,n[r]);return t}});function qn(e){if(Array.isArray(e)){const t=Array.prototype.slice.call(e);for(let n=0;n({}),identify:kt,represent:e=>{const t=new Map;for(const n of Object.keys(e))t.set(n,e[n]);return t},addPair:(e,t,n)=>{const r=qn(t);return r===null?"nested arrays are not supported inside keys":(r==="__proto__"?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,"")},has:(e,t)=>{const n=qn(t);return n!==null&&Object.prototype.hasOwnProperty.call(e,n)},keys:e=>Object.keys(e),get:(e,t)=>{const n=String(t);return Object.prototype.hasOwnProperty.call(e,n)?e[n]:null}});var Ba={maxLength:79,indent:1,linesBefore:3,linesAfter:2};function Yt(e,t,n,r,i){let a="",l="";const o=Math.floor(i/2)-1;return r-t>o&&(a=" ... ",t=r-o+a.length),n-r>o&&(l=" ...",n=r+o-l.length),{str:a+e.slice(t,n).replace(/\t/g,"→")+l,pos:r-t+a.length}}function qt(e,t){return" ".repeat(Math.max(t-e.length,0))+e}function Ya(e,t){if(!e.buffer)return null;const n={...Ba,...t},r=/\r?\n|\r|\0/g,i=[0],a=[];let l,o=-1;for(;l=r.exec(e.buffer);)a.push(l.index),i.push(l.index+l[0].length),e.position<=l.index&&o<0&&(o=i.length-2);o<0&&(o=i.length-1);let u="";const p=Math.min(e.line+n.linesAfter,a.length).toString().length,c=n.maxLength-(n.indent+p+3);for(let m=1;m<=n.linesBefore&&!(o-m<0);m++){const b=Yt(e.buffer,i[o-m],a[o-m],e.position-(i[o]-i[o-m]),c);u=`${" ".repeat(n.indent)}${qt((e.line-m+1).toString(),p)} | ${b.str} -${u}`}const f=Yt(e.buffer,i[o],a[o],e.position,c);u+=`${" ".repeat(n.indent)}${qt((e.line+1).toString(),p)} | ${f.str} -`,u+=`${"-".repeat(n.indent+p+3+f.pos)}^ -`;for(let m=1;m<=n.linesAfter&&!(o+m>=a.length);m++){const b=Yt(e.buffer,i[o+m],a[o+m],e.position-(i[o]-i[o+m]),c);u+=`${" ".repeat(n.indent)}${qt((e.line+m+1).toString(),p)} | ${b.str} -`}return u.replace(/\n$/,"")}function Kn(e,t){let n="";return e.mark?(e.mark.name&&(n+=`in "${e.mark.name}" `),n+=`(${e.mark.line+1}:${e.mark.column+1})`,!t&&e.mark.snippet&&(n+=` - -${e.mark.snippet}`),`${e.reason} ${n}`):e.reason}var nt=class extends Error{reason;mark;constructor(e,t){super(),this.name="YAMLException",this.reason=e,this.mark=t,this.message=Kn(this,!1),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(e){return`${this.name}: ${Kn(this,e)}`}};function Et(e,t,n,r=""){let i=0,a=0;for(let o=0;o>10)+55296,(e-65536&1023)+56320)}function Ha(e){return e>=48&&e<=57?e-48:(e|32)-97+10}function Va(e){return e===120?2:e===117?4:8}function Nt(e,t,n){let r=0;for(;t0;p--){i++;const f=Ha(e.charCodeAt(i));c=(c<<4)+f}r+=Ka(c),i++}a=l=i}else if(o===10||o===13){r+=e.slice(a,l);const u=Nt(e,i,n);r+=Sn(u.breaks),i=a=l=u.position}else i++,o!==32&&o!==9&&(l=i)}return r+e.slice(a,n)}function Vn(e,t,n,r,i,a){const l=r<0?0:r,o=e.slice(t,n).replace(/\r\n?/g,` -`),u=o===""?[]:(o.endsWith(` -`)?o.slice(0,-1):o).split(` -`);let p="",c=!1,f=0,m=!1;for(const b of u){let g=0;for(;g=b.length){f++;continue}const j=b.slice(l),O=j.charCodeAt(0);a?O===32||O===9?(m=!0,p+=` -`.repeat(c?1+f:f)):m?(m=!1,p+=` -`.repeat(f+1)):f===0?c&&(p+=" "):p+=` -`.repeat(f):p+=` -`.repeat(c?1+f:f),p+=j,c=!0,f=0}return i===3?p+=` -`.repeat(c?1+f:f):i!==2&&c&&(p+=` -`),p}function Ja(e,t){if(t.valueStart===qa)return"";const{valueStart:n,valueEnd:r}=t;if(t.fast)return e.slice(n,r);switch(t.style){case 2:return Ga(e,n,r);case 3:return za(e,n,r);case 4:return Vn(e,n,r,t.indent,t.chomping,!1);case 5:return Vn(e,n,r,t.indent,t.chomping,!0);default:return Wa(e,n,r)}}var Qa=Object.assign(Object.create(null),{"!":"!","!!":"tag:yaml.org,2002:"});function Kt(e){return encodeURI(e).replace(/!/g,"%21")}function kr(e,t){if(e.startsWith("!<")&&e.endsWith(">"))return decodeURIComponent(e.slice(2,-1));const n=e.indexOf("!",1),r=n===-1?"!":e.slice(0,n+1),i=t?.[r]??Qa[r]??r;return decodeURIComponent(i)+decodeURIComponent(e.slice(r.length))}function Tr(e){let t=e;return t.charCodeAt(0)===33?(t=t.slice(1),`!${Kt(t)}`):t.slice(0,18)==="tag:yaml.org,2002:"?`!!${Kt(t.slice(18))}`:`!<${Kt(t)}>`}var De=-1,An={filename:"",schema:Da,json:!1,maxTotalMergeKeys:1e4,maxAliases:-1};function Xa(e){return"tagStart"in e&&e.tagStart!==De?e.tagStart:"anchorStart"in e&&e.anchorStart!==De?e.anchorStart:"valueStart"in e&&e.valueStart!==De?e.valueStart:"start"in e?e.start:0}function ne(e,t){Et(e.source,e.position,t,e.filename)}function Er(e,t,n,r){try{return n.finalize(r)}catch(i){if(i instanceof nt)throw i;Et(e.source,t,i instanceof Error?i.message:String(i),e.filename)}}function xt(e,t,n){const r=e[n];if(r)return r;for(const i of t)if(n.startsWith(i.tagName))return i}function Ma(e,t,n,r,i){const a=xt(t,n,r);if(a)return a;ne(e,`unknown ${i} tag !<${r}>`)}function Za(e,t){const n=Ja(e.source,t),r=t.tagStart===De?"":e.source.slice(t.tagStart,t.tagEnd),i=e.schema.defaultScalarTag;if(r!==""){if(r==="!")return{value:n,tag:i};const a=kr(r,e.tagHandlers),l=xt(e.schema.exact.scalar,e.schema.prefix.scalar,a);if(l){const u=l.resolve(n,!0,a);return u===L&&ne(e,`cannot resolve a node with !<${a}> explicit tag`),{value:u,tag:l}}const o=xt(e.schema.exact.mapping,e.schema.prefix.mapping,a)??xt(e.schema.exact.sequence,e.schema.prefix.sequence,a);if(o){n!==""&&ne(e,`cannot resolve a node with !<${a}> explicit tag`);const u=o.create(a);return{value:o.carrierIsResult?u:Er(e,e.position,o,u),tag:o}}ne(e,`unknown scalar tag !<${a}>`)}if(t.style===1){const a=e.schema.implicitScalarByFirstChar.get(n.charAt(0))??e.schema.implicitScalarAnyFirstChar;for(const l of a){const o=l.resolve(n,!1,l.tagName);if(o!==L)return{value:o,tag:l}}}return{value:i.resolve(n,!1,i.tagName),tag:i}}function Wn(e,t,n,r,i,a){const l=t.tagStart===De?"":e.source.slice(t.tagStart,t.tagEnd),o=l===""||l==="!"?i:kr(l,e.tagHandlers);return{tagName:o,tag:Ma(e,n,r,o,a)}}function Ir(e){return e.nodeKind==="mapping"}function Gn(e,t,n,r){for(const i of r.keys(n)){if(e.maxTotalMergeKeys!==-1&&++e.totalMergeKeys>e.maxTotalMergeKeys&&ne(e,`merge keys exceeded maxTotalMergeKeys (${e.maxTotalMergeKeys})`),t.tag.has(t.value,i))continue;const a=t.tag.addPair(t.value,i,r.get(n,i));a&&ne(e,a),(t.overridable??=new Set).add(i)}}function es(e,t,n,r){if(e.position=t.keyPosition,Ir(r))Gn(e,t,n,r);else if(r.nodeKind==="sequence"&&Array.isArray(n))for(const i of n)Gn(e,t,i,t.tag);else ne(e,"cannot merge mappings; the provided source object is unacceptable")}function ts(e,t,n,r,i){if(e.position=t.keyPosition,n===vn){es(e,t,r,i);return}!e.json&&t.tag.has(t.value,n)&&!t.overridable?.has(n)&&ne(e,"duplicated mapping key");const a=t.tag.addPair(t.value,n,r);a&&ne(e,a),t.overridable?.delete(n)}function Ht(e,t,n){const r=e.frames[e.frames.length-1];if(r.kind==="document")r.value=t,r.hasValue=!0;else if(r.kind==="sequence"){r.merge&&(Ir(n)||ne(e,"cannot merge mappings; the provided source object is unacceptable"));const i=r.tag.addItem(r.value,t,r.index++);i&&ne(e,i)}else if(r.hasKey){const i=r.key;r.key=void 0,r.hasKey=!1,ts(e,r,i,t,n)}else r.key=t,r.keyPosition=e.position,r.hasKey=!0}function Vt(e,t,n,r,i){if(t.anchorStart!==De){const a={value:n,tag:r,isValueFinal:i};return e.anchors.set(e.source.slice(t.anchorStart,t.anchorEnd),a),a}return null}function ns(e,t){const n={...An,...t,events:e,documents:[],eventIndex:0,position:0,frames:[],anchors:new Map,tagHandlers:Object.create(null),totalMergeKeys:0,aliasCount:0};for(;n.eventIndexn.maxAliases&&ne(n,`aliases exceeded maxAliases (${n.maxAliases})`);const i=n.source.slice(r.anchorStart,r.anchorEnd),a=n.anchors.get(i);a||ne(n,`unidentified alias "${i}"`),a.isValueFinal||ne(n,`recursive alias "${i}" is not supported for tag ${a.tag.tagName} because it uses finalize()`),Ht(n,a.value,a.tag);break}case 6:{const i=n.frames.pop();if(i.kind==="mapping"&&i.hasKey&&(n.position=i.keyPosition,ne(n,"incomplete mapping pair in event stream")),i.kind==="document")n.documents.push(i.value);else{const a=i.tag.carrierIsResult?i.value:Er(n,i.position,i.tag,i.value);i.anchor&&(i.anchor.value=a,i.anchor.isValueFinal=!0),Ht(n,a,i.tag)}break}}}return n.documents}var F=-1,Or=Object.prototype.hasOwnProperty,Ke=1,tn=2,Rr=3,jt=4,rs=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,is=/[,\[\]{}]/,Lr=/^(?:!|!!|![0-9A-Za-z-]+!)$/,nn=String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$,_.!~*'()\[\]])`,Fr=String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$.~*'()_])`,as=new RegExp(`^(?:${nn})*$`),ss=new RegExp(`^(?:${Fr})+$`),os=new RegExp(`^(?:!(?:${nn})*|${Fr}(?:${nn})*)$`),Cn={filename:"",maxDepth:100};function ls(e,t,n){e.events.push({type:1,explicitStart:t,explicitEnd:n,directives:e.directives})}function Pr(e,t,n,r,i,a,l){e.events.push({type:2,start:t,anchorStart:n,anchorEnd:r,tagStart:i,tagEnd:a,style:l})}function rn(e,t,n,r,i,a,l){e.events.push({type:3,start:t,anchorStart:n,anchorEnd:r,tagStart:i,tagEnd:a,style:l})}function zn(e,t){e.events.splice(t.eventsLength,0,{type:3,start:t.position,anchorStart:F,anchorEnd:F,tagStart:F,tagEnd:F,style:2})}function We(e,t,n,r,i,a,l,o,u=1,p=-1,c=!1){e.events.push({type:4,valueStart:t,valueEnd:n,anchorStart:r,anchorEnd:i,tagStart:a,tagEnd:l,style:o,chomping:u,indent:p,fast:c})}function cs(e,t,n){e.events.push({type:5,anchorStart:t,anchorEnd:n})}function Ue(e){e.events.push({type:6})}function ee(e){We(e,F,F,F,F,F,F,1)}function Jn(){return{anchorStart:F,anchorEnd:F,tagStart:F,tagEnd:F}}function Ze(e){return{position:e.position,line:e.line,lineStart:e.lineStart,lineIndent:e.lineIndent,firstTabInLine:e.firstTabInLine,eventsLength:e.events.length}}function Be(e,t){e.position=t.position,e.line=t.line,e.lineStart=t.lineStart,e.lineIndent=t.lineIndent,e.firstTabInLine=t.firstTabInLine,e.events.length=t.eventsLength}function $(e,t){Et(e.input.slice(0,e.length),e.position,t,e.filename)}function G(e){return e===10||e===13}function ke(e){return e===9||e===32}function ue(e){return ke(e)||G(e)}function me(e){return e===0||ue(e)}function Te(e){return e===44||e===91||e===93||e===123||e===125}function us(e){return e>=48&&e<=57?e-48:-1}function ps(e){if(e>=48&&e<=57)return e-48;const t=e|32;return t>=97&&t<=102?t-97+10:-1}function ds(e){return e===120?2:e===117?4:e===85?8:0}function fs(e){return e===48||e===97||e===98||e===116||e===9||e===110||e===118||e===102||e===114||e===101||e===32||e===34||e===47||e===92||e===78||e===95||e===76||e===80}function St(e){e.input.charCodeAt(e.position)===10?e.position++:(e.position++,e.input.charCodeAt(e.position)===10&&e.position++),e.line++,e.lineStart=e.position,e.lineIndent=0,e.firstTabInLine=-1}function te(e,t){let n=0,r=e.input.charCodeAt(e.position),i=e.position===e.lineStart||ue(e.input.charCodeAt(e.position-1));for(;r!==0;){for(;ke(r);)i=!0,r===9&&e.firstTabInLine===-1&&(e.firstTabInLine=e.position),r=e.input.charCodeAt(++e.position);if(t&&i&&r===35)do r=e.input.charCodeAt(++e.position);while(!G(r)&&r!==0);if(!G(r))break;for(St(e),n++,i=!0,r=e.input.charCodeAt(e.position);r===32;)e.lineIndent++,r=e.input.charCodeAt(++e.position)}return n}function we(e,t=e.position){const n=e.input.charCodeAt(t);if((n===45||n===46)&&n===e.input.charCodeAt(t+1)&&n===e.input.charCodeAt(t+2)){const r=e.input.charCodeAt(t+3);return r===0||ue(r)}return!1}function Qn(e){let t=e.input.charCodeAt(e.position);for(;t!==0&&!G(t);)t=e.input.charCodeAt(++e.position)}function Dr(e,t,n){rs.test(e.input.slice(t,n))&&$(e,"the stream contains non-printable characters")}function ms(e,t,n){if(e.input.charCodeAt(e.position)!==33)return!1;t.tagStart!==F&&$(e,"duplication of a tag property");const r=e.position;let i=!1,a=!1,l="!",o=e.input.charCodeAt(++e.position);o===60?(i=!0,o=e.input.charCodeAt(++e.position)):o===33&&(a=!0,l="!!",o=e.input.charCodeAt(++e.position));let u=e.position,p;if(i){for(;o!==0&&o!==62;)o=e.input.charCodeAt(++e.position);o!==62&&$(e,"unexpected end of the stream within a verbatim tag"),p=e.input.slice(u,e.position),e.position++}else{for(;o!==0&&!ue(o)&&!(n&&Te(o));)o===33&&(a?$(e,"tag suffix cannot contain exclamation marks"):(l=e.input.slice(u-1,e.position+1),Lr.test(l)||$(e,"named tag handle cannot contain such characters"),a=!0,u=e.position+1)),o=e.input.charCodeAt(++e.position);p=e.input.slice(u,e.position),is.test(p)&&$(e,"tag suffix cannot contain flow indicator characters")}return p&&!(i?as.test(p):ss.test(p))&&$(e,`tag name cannot contain such characters: ${p}`),!i&&l!=="!"&&l!=="!!"&&!Or.call(e.tagHandlers,l)&&$(e,`undeclared tag handle "${l}"`),t.tagStart=r,t.tagEnd=e.position,!0}function gs(e,t){if(e.input.charCodeAt(e.position)!==38)return!1;t.anchorStart!==F&&$(e,"duplication of an anchor property"),e.position++;const n=e.position;for(;e.input.charCodeAt(e.position)!==0&&!ue(e.input.charCodeAt(e.position))&&!Te(e.input.charCodeAt(e.position));)e.position++;return e.position===n&&$(e,"name of an anchor node must contain at least one character"),t.anchorStart=n,t.anchorEnd=e.position,!0}function hs(e,t){if(e.input.charCodeAt(e.position)!==42)return!1;(t.anchorStart!==F||t.tagStart!==F)&&$(e,"alias node should not have any properties"),e.position++;const n=e.position;for(;e.input.charCodeAt(e.position)!==0&&!ue(e.input.charCodeAt(e.position))&&!Te(e.input.charCodeAt(e.position));)e.position++;return e.position===n&&$(e,"name of an alias node must contain at least one character"),cs(e,n,e.position),!0}function an(e,t){te(e,!1),e.lineIndent0;)e.position++,ps(e.input.charCodeAt(e.position))<0&&$(e,"expected hexadecimal character");e.position++}}else G(a)?(i=!1,an(e,t)):e.position===e.lineStart&&we(e)?$(e,"unexpected end of the document within a double quoted scalar"):a!==9&&a<32?$(e,"expected valid JSON character"):e.position++}$(e,"unexpected end of the stream within a double quoted scalar")}function ys(e,t,n){const r=e.input.charCodeAt(e.position);let i=1,a=-1,l=!1;if(r!==124&&r!==62)return!1;const o=r===124?4:5;for(e.position++;e.input.charCodeAt(e.position)!==0;){const b=e.input.charCodeAt(e.position),g=us(b);if(b===43||b===45)i!==1&&$(e,"repeat of a chomping mode identifier"),i=b===43?3:2,e.position++;else if(g>=0)g===0&&$(e,"bad explicit indentation width of a block scalar; it cannot be less than one"),l&&$(e,"repeat of an indentation width identifier"),a=t+g-1,l=!0,e.position++;else break}let u=!1;for(;ke(e.input.charCodeAt(e.position));)u=!0,e.position++;u&&e.input.charCodeAt(e.position)===35&&Qn(e),G(e.input.charCodeAt(e.position))?St(e):e.input.charCodeAt(e.position)!==0&&$(e,"a line break is expected");let p=l?a:-1,c=0;const f=e.position;let m=e.position;for(;e.input.charCodeAt(e.position)!==0;){const b=e.position;let g=0;for(;e.input.charCodeAt(b+g)===32;)g++;const j=e.input.charCodeAt(b+g);if(j===0){p>=0?g>p&&(m=b+g):g>0&&(m=b+g);break}if(b===e.lineStart&&we(e,b))break;if(!l&&p===-1&&G(j)&&(c=Math.max(c,g)),!l&&p===-1&&!G(j)&&(j===9&&g=t){u=!0,l=e.input.charCodeAt(e.position);continue}e.position=p,e.line=c,e.lineStart=f,e.lineIndent=m;break}}ke(l)||(a=e.position+1),l=e.input.charCodeAt(++e.position)}return a===i?!1:(Dr(e,i,a),We(e,i,a,r.anchorStart,r.anchorEnd,r.tagStart,r.tagEnd,1,1,-1,!u),!0)}function ze(e,t){const n=e.line;te(e,!0),(e.line>n&&e.lineIndent0;if(e.firstTabInLine!==-1&&e.input.charCodeAt(e.position)===45&&me(e.input.charCodeAt(e.position+1))&&$(e,"bad indentation of a sequence entry"),i&&e.lineIndent<=t?ee(e):_e(e,t,Rr,!1,!0),te(e,!0),e.lineIndent=e.length)break;e.lineIndent>t&&$(e,"bad indentation of a sequence entry"),e.line===r&&e.input.charCodeAt(e.position)===45&&me(e.input.charCodeAt(e.position+1))&&$(e,"bad indentation of a sequence entry")}return Ue(e),!0}function Wt(e,t,n,r){let i=!1,a=!1,l=!1,o=!1;if(e.firstTabInLine!==-1)return!1;let u=e.input.charCodeAt(e.position);for(;u!==0;){!i&&e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,$(e,"tab characters must not be used in indentation"));const p=e.input.charCodeAt(e.position+1),c=e.line;if((u===63||u===58)&&me(p))l||(rn(e,e.position,r.anchorStart,r.anchorEnd,r.tagStart,r.tagEnd,1),l=!0),u===63?(i&&ee(e),a=!0,i=!0):(i||(ee(e),a=!0),i=!1),e.position+=1,o=!0;else{i&&(ee(e),i=!1);const f=Ze(e);if(!_e(e,n,tn,!1,!0))break;if(e.line===c){for(u=e.input.charCodeAt(e.position);ke(u);)u=e.input.charCodeAt(++e.position);if(u===58){if(u=e.input.charCodeAt(++e.position),me(u)||$(e,"a whitespace character is expected after the key-value separator within a block mapping"),!l){for(Be(e,f),rn(e,f.position,r.anchorStart,r.anchorEnd,r.tagStart,r.tagEnd,1),l=!0,_e(e,n,tn,!1,!0),u=e.input.charCodeAt(e.position);ke(u);)u=e.input.charCodeAt(++e.position);e.position++}a=!0,i=!1,o=!1}else if(a)$(e,"expected ':' after a mapping key");else return r.anchorStart!==F||r.tagStart!==F?(Be(e,f),!1):!0}else if(a)$(e,"can not read a block mapping entry; a multiline key may not be an implicit key");else return r.anchorStart!==F||r.tagStart!==F?(Be(e,f),!1):!0}if(_e(e,t,jt,!0,o)&&(o=!1),i||o&&(ee(e),o=!1),te(e,!0),u=e.input.charCodeAt(e.position),(e.line===c||e.lineIndent>t)&&u!==0)$(e,"bad indentation of a mapping entry");else if(e.lineIndent=e.maxDepth&&$(e,`nesting exceeded maxDepth (${e.maxDepth})`),e.depth++;let l=1,o=!1,u=!1,p=null;const c=Jn();let f=n===jt||n===Rr,m=f;const b=f;if(r&&te(e,!0)&&(o=!0,e.lineIndent>t?l=1:e.lineIndent===t?l=0:l=-1),l===1)for(;;){const g=e.input.charCodeAt(e.position),j=Ze(e);if(o&&l!==1&&(g===33||g===38))break;if(o&&b&&(c.tagStart!==F||c.anchorStart!==F)&&(g===33||g===38)){const O=Ze(e),Y=t+1;if(Wt(e,e.position-e.lineStart,Y,c)&&e.events[O.eventsLength]?.type===3)return e.depth--,!0;Be(e,O)}if(o&&(g===33&&c.tagStart!==F||g===38&&c.anchorStart!==F)||!ms(e,c,n===Ke)&&!gs(e,c))break;p===null&&(p=j),te(e,!0)?(o=!0,m=b,e.lineIndent>t?l=1:e.lineIndent===t?l=0:l=-1):m=!1}if(m&&(m=o||i),l===1||n===jt){const g=n===Ke||n===tn?t:t+1,j=e.position-e.lineStart;if(l===1)if(m&&(Xn(e,j,c)||Wt(e,j,g,c))||js(e,g,c))u=!0;else{const O=e.input.charCodeAt(e.position);if(p!==null&&a&&b&&!m&&O!==124&&O!==62){const Y=Ze(e),D=p.position-p.lineStart;Be(e,p),Wt(e,D,g,Jn())&&e.events[Y.eventsLength]?.type===3?u=!0:Be(e,Y)}!u&&(f&&ys(e,g,c)||xs(e,g,c)||bs(e,g,c)||hs(e,c)||Ns(e,g,n,c))&&(u=!0)}else l===0&&(u=m&&Xn(e,j,c))}return f=f&&!u,!u&&(c.anchorStart!==F||c.tagStart!==F||f)&&(We(e,F,F,c.anchorStart,c.anchorEnd,c.tagStart,c.tagEnd,1),u=!0),e.depth--,u||c.anchorStart!==F||c.tagStart!==F}function Ss(e){if(e.lineIndent>0||e.input.charCodeAt(e.position)!==37)return!1;e.position++;const t=e.position;for(;e.input.charCodeAt(e.position)!==0&&!ue(e.input.charCodeAt(e.position));)e.position++;const n=e.input.slice(t,e.position),r=[];for(n.length===0&&$(e,"directive name must not be less than one character in length");e.input.charCodeAt(e.position)!==0&&!G(e.input.charCodeAt(e.position));){for(;ke(e.input.charCodeAt(e.position));)e.position++;if(e.input.charCodeAt(e.position)===35||G(e.input.charCodeAt(e.position))||e.input.charCodeAt(e.position)===0)break;const i=e.position;for(;e.input.charCodeAt(e.position)!==0&&!ue(e.input.charCodeAt(e.position));)e.position++;r.push(e.input.slice(i,e.position))}if(G(e.input.charCodeAt(e.position))&&St(e),n==="YAML"){e.directives.some(a=>a.kind==="yaml")&&$(e,"duplication of %YAML directive"),r.length!==1&&$(e,"YAML directive accepts exactly one argument");const i=/^([0-9]+)\.([0-9]+)$/.exec(r[0]);i===null&&$(e,"ill-formed argument of the YAML directive"),parseInt(i[1],10)!==1&&$(e,"unacceptable YAML version of the document"),e.directives.push({kind:"yaml",version:r[0]})}else if(n==="TAG"){r.length!==2&&$(e,"TAG directive accepts exactly two arguments");const[i,a]=r;Lr.test(i)||$(e,"ill-formed tag handle (first argument) of the TAG directive"),Or.call(e.tagHandlers,i)&&$(e,`there is a previously declared suffix for "${i}" tag handle`),os.test(a)||$(e,"ill-formed tag prefix (second argument) of the TAG directive"),e.tagHandlers[i]=a,e.directives.push({kind:"tag",handle:i,prefix:a})}return!0}function As(e){e.directives=[],e.tagHandlers=Object.create(null);let t=!1;for(te(e,!0);Ss(e);)t=!0,te(e,!0);let n=!1,r=!1,i=!0;if(e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45&&me(e.input.charCodeAt(e.position+3))){n=!0;const o=e.line;e.position+=3,te(e,!0),i=e.line>o}else t&&$(e,"directives end mark is expected");const a=e.events.length;if(!n&&e.position===e.lineStart&&e.input.charCodeAt(e.position)===46&&we(e)){e.position+=3,te(e,!0);return}if(ls(e,n,!1),_e(e,e.lineIndent-1,jt,!1,i,i)||ee(e),te(e,!0),e.position===e.lineStart&&we(e)&&(r=e.input.charCodeAt(e.position)===46,r)){const o=e.line;e.position+=3,te(e,!0),e.line===o&&e.position=r.length));){const a=r.position;As(r),r.position===a&&$(r,"can not read a document")}return r.events}var $s={...Cn,...An};function ws(e,t={}){const n={...$s,...t},r=String(e),i=Object.keys(Cn),a=Object.keys(An);return ns(Cs(r,en(n,i)),{...en(n,a),source:r})}function _s(e,t){const n=ws(e,t);if(n.length===0)throw new nt("expected a document, but the input is empty");if(n.length===1)return n[0];throw new nt("expected a single document in the stream, but found more")}var dt=class{tagged=!1;flow=!1;singleQuoted=!1;doubleQuoted=!1;literal=!1;folded=!1},$e=Symbol("INVALID");function ks(e){const t=new Set([e.defaultScalarTag,e.defaultSequenceTag,e.defaultMappingTag].filter(a=>a!==void 0)),n=e.implicitScalarTags,r=e.tags.filter(a=>!(a.nodeKind==="scalar"&&a.implicit)&&!t.has(a)),i=e.tags.filter(a=>t.has(a));return[...n.map(a=>({tag:a,implicitTag:!0})),...r.map(a=>({tag:a,implicitTag:!1})),...i.map(a=>({tag:a,implicitTag:!0}))]}function Ts(e,t){for(let n=0,r=e.representTypes.length;n=32&&e<=126||e>=161&&e<=55295&&e!==8232&&e!==8233||e>=57344&&e<=65533&&e!==$n||e>=65536&&e<=1114111}function er(e){return it(e)&&e!==$n&&e!==Br&&e!==Ee}function fn(e,t,n){const r=er(e),i=r&&!He(e);return(n?r:r&&e!==on&&e!==ln&&e!==cn&&e!==un&&e!==pn)&&e!==sn&&!(t===rt&&!i)||er(t)&&!He(t)&&e===sn||t===rt&&i&&(n||e!==on&&e!==ln&&e!==cn&&e!==un&&e!==pn)}function Qs(e){return it(e)&&e!==$n&&!He(e)&&e!==wn&&e!==Kr&&e!==rt&&e!==on&&e!==ln&&e!==cn&&e!==un&&e!==pn&&e!==sn&&e!==Ds&&e!==Us&&e!==Fs&&e!==Hs&&e!==Bs&&e!==Ys&&e!==qr&&e!==Yr&&e!==Ps&&e!==qs&&e!==Ks}function Xs(e,t){const n=Ye(e,0);if(Qs(n))return!0;if(e.length>1&&(n===wn||n===Kr||n===rt)){const r=Ye(e,1);return!He(r)&&fn(r,n,t)}return!1}function Ms(e){return!He(e)&&e!==rt}function Ye(e,t){const n=e.charCodeAt(t);let r;return n>=55296&&n<=56319&&t+1=56320&&r<=57343)?(n-55296)*1024+r-56320+65536:n}function Hr(e){return/^\n* /.test(e)}var at=1,et=2,kn=3,Tn=4,Ne=5;function Zs(e,t,n,r,i,a){const{blockIndent:l,lineWidth:o}=n;let u,p=0,c=-1,f=!1,m=!1;const b=o!==-1;let g=-1,j=!Js(t)&&Xs(t,a)&&Ms(Ye(t,t.length-1));if(r||i)for(u=0;u=65536?u+=2:u++){if(p=Ye(t,u),!it(p))return Ne;j=j&&fn(p,c,a),c=p}else{for(u=0;u=65536?u+=2:u++){if(p=Ye(t,u),p===Ee)f=!0,b&&(m=m||u-g-1>o&&!st(t[g+1]),g=u);else if(!it(p))return Ne;j=j&&fn(p,c,a),c=p}m=m||b&&u-g-1>o&&!st(t[g+1])}return!f&&!m?j&&!i?at:e.quoteStyle==="double"?Ne:et:l>9&&Hr(t)?Ne:m?Tn:kn}function eo(e,t,n){const{indent:r,blockIndent:i,lineWidth:a}=n;switch(t){case at:return nr(e,r);case et:return`'${nr(e,r).replace(/'/g,"''")}'`;case kn:return"|"+tr(e,i)+rr(Mn(e,r));case Tn:return">"+tr(e,i)+rr(Mn(no(e,a),r));case Ne:return`"${ro(e)}"`}}function to(e,t,n,r,i){const a=r||!i;if(t.style.singleQuoted)return et;if(t.style.doubleQuoted)return Ne;if(!a){if(t.style.literal)return kn;if(t.style.folded)return Tn}const l=t.value;if(l.length===0)return t.style.tagged||Zn(e,l)===t.tag?at:e.quoteStyle==="double"?Ne:et;const o=Zs(e,l,n,a,e.forceQuotes&&!r,i);return o===at&&!t.style.tagged&&Zn(e,l)!==t.tag?e.quoteStyle==="double"?Ne:et:o}function tr(e,t){const n=Hr(e)?String(t):"",r=e[e.length-1]===` -`;return`${n}${r&&(e[e.length-2]===` -`||e===` -`)?"+":r?"":"-"} -`}function nr(e,t){let n=e.indexOf(` -`);if(n===-1)return e;const r=" ".repeat(t);let i=e.slice(0,n);const a=/(\n+)([^\n]*)/g;a.lastIndex=n;let l;for(;l=a.exec(e);){const o=l[1].length,u=l[2];i+=` -`.repeat(o+1)+r+u}return i}function rr(e){return e[e.length-1]===` -`?e.slice(0,-1):e}function st(e){return e===" "||e===" "}function no(e,t){const n=/(\n+)([^\n]*)/g;let r=e.indexOf(` -`);r===-1&&(r=e.length),n.lastIndex=r;let i=ir(e.slice(0,r),t),a=e[0]===` -`||st(e[0]),l,o;for(;o=n.exec(e);){const u=o[1],p=o[2];l=p!==""&&st(p[0]),i+=u+(!a&&!l&&p!==""?` -`:"")+ir(p,t),a=l}return i}function ir(e,t){if(e===""||st(e[0]))return e;const n=/ [^ \t]/g;let r,i=0,a,l=0,o=0,u="";for(;r=n.exec(e);)o=r.index,o-i>t&&(a=l>i?l:o,u+=` -${e.slice(i,a)}`,i=a+1),l=o;return u+=` -`,e.length-i>t&&l>i?u+=`${e.slice(i,l)} -${e.slice(l+1)}`:u+=e.slice(i),u.slice(1)}function ro(e){let t="",n=0;for(let r=0;r=65536?r+=2:r++){n=Ye(e,r);const i=M[n];if(i){t+=i;continue}if(it(n)){t+=e[r],n>=65536&&(t+=e[r+1]);continue}t+=Gs(n)}return t}function io(e,t,n){let r="";for(let a=0,l=n.items.length;a1024;c?u+="? ":e.quoteFlowKeys&&(u+='"');const f=ge(e,t,o,{}),m=e.flowSkipColonSpace||f===""?"":" ";u+=`${p}${e.quoteFlowKeys&&!c?'"':""}:${m}${f}`,r+=u}const a=e.flowBracketPadding&&r!==""?" ":"";return`{${a}${r}${a}}`}function ft(e){return e.kind==="scalar"?e.value:e}function Vr(e,t){if(!e.sortKeys)return t;const n=t.slice();if(e.sortKeys===!0)n.sort((r,i)=>{const a=ft(r.key),l=ft(i.key);return al?1:0});else{const r=e.sortKeys;n.sort((i,a)=>r(ft(i.key),ft(a.key)))}return n}function so(e,t,n,r){let i="";const a=Vr(e,n.items);for(let l=0,o=a.length;l1024;g&&(m&&Ee===m.charCodeAt(0)?u+="?":u+="? "),u+=m,g&&(u+=dn(e,t));const j=ge(e,t+1,c,{block:!0,compact:g,isblockseq:g&&!mn(e,c,t+1)}),O=p.kind==="scalar"&&p.value===""&&m!==""&&m.charCodeAt(m.length-1)!==qr&&m.charCodeAt(m.length-1)!==Yr,Y=!g&&(p.kind==="alias"||O)?" ":"";j===""||Ee===j.charCodeAt(0)?u+=`${Y}:`:u+=`${Y}: `,u+=j,i+=u}return i}function mn(e,t,n){return t.style.tagged||t.anchor!==void 0||e.indent<2&&n>0}function ge(e,t,n,r){if(n.kind==="alias")return`*${n.anchor}`;const{block:i=!1,iskey:a=!1,isblockseq:l=!1}=r;let o=r.compact??!1;const u=n.anchor!==void 0;mn(e,n,t)&&(o=!1);let p,c=n.style.tagged;const f=i&&(n.kind==="mapping"||n.kind==="sequence")&&!n.style.flow&&n.items.length!==0;if(n.kind==="mapping")f?p=so(e,t,n,o):p=ao(e,t,n);else if(n.kind==="sequence")f?e.seqNoIndent&&!l&&t>0?p=ar(e,t-1,n,o):p=ar(e,t,n,o):p=io(e,t,n);else{const m=zs(e,t),b=to(e,n,m,a,i);p=eo(n.value,b,m),c=n.style.tagged||b!==at&&n.tag!==e.defaultScalarTagName}if(f&&o&&t>0&&e.indent>2&&(p=`${" ".repeat(e.indent-2)}${p}`),c||u){const m=[],b=c?Vs(n):null,g=u?`&${n.anchor}`:null;e.tagBeforeAnchor?(b!==null&&m.push(b),g!==null&&m.push(g)):(g!==null&&m.push(g),b!==null&&m.push(b));const j=p===""||p.charCodeAt(0)===Ee?"":" ";p=`${m.join(" ")}${j}${p}`}return p}function oo(e){return(e.kind==="sequence"||e.kind==="mapping")&&!e.style.flow&&e.items.length!==0&&!e.style.tagged&&e.anchor===void 0}function lo(e){let t=e;for(;(t.kind==="sequence"||t.kind==="mapping")&&!t.style.flow&&t.items.length!==0;)t=t.kind==="sequence"?t.items[t.items.length-1]:t.items[t.items.length-1].value;if(t.kind!=="scalar"||!(t.style.literal||t.style.folded))return!1;const{value:n}=t;return n.endsWith(` - -`)||n===` -`}function co(e){let t="";for(const n of e.directives){if(n.kind==="yaml"){t+=`%YAML ${n.version} -`;continue}const{handle:r,prefix:i}=n;t+=`%TAG ${r} ${i} -`}return t}function uo(e,t){const n=Ws(t);let r="",i=!1;for(let a=0;a0&&!i;if(r+=o,l.contents===null)p&&(r+=`--- -`);else if(p){const c=ge(n,0,l.contents,{block:!0,compact:!0}),f=c===""?"":u||oo(l.contents)?` -`:" ";r+=`---${f}${c} -`}else r+=ge(n,0,l.contents,{block:!0,compact:!0})+` -`;i=l.explicitEnd||l.contents!==null&&lo(l.contents),i&&(r+=`... -`)}return r}var po=Ua.withTags({...Mt,resolve:(e,t,n)=>{const r=Mt.resolve(e,t,n);return r===L?Ar.resolve(e,t,n):r}},{...Zt,resolve:(e,t,n)=>{const r=Zt.resolve(e,t,n);return r===L?Cr.resolve(e,t,n):r}}),fo={..._n,schema:po,skipInvalid:!1,noRefs:!1,flowLevel:-1,transform:()=>{}};function mo(e,t={}){const n={...fo,...t},r=Es(e,n.schema,{noRefs:n.noRefs,skipInvalid:n.skipInvalid});return n.flowLevel>=0&&Os(r,(i,a)=>{if(!(a.depth= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,go(r)}function yo(){return{name:"my_pipeline",description:"",version:"1.0.0",on_error:"fail_fast",timeout:300,strict_schema:!1,input_schema:{},output_schema:{},defaults:{},metadata:{}}}function Gt(){return{meta:yo(),steps:[]}}function It(e,t){return{id:Wr(),kind:e,name:t,config:Xt(e,t),children:Ri(e,t)}}function Ve(e,t){const n=new Set(t);let r=e,i=2;for(;n.has(r);)r=`${e}_${i}`,i+=1;return r}function vo(e){if(e&&typeof e=="object"){if(typeof e.step_type=="string"&&["agent","plugin","endpoint","ingestion","transform","parallel","map","loop","sub_pipeline"].includes(e.step_type))return e.step_type;if(e.agent!==void 0)return"agent";if(e.plugin!==void 0)return"plugin";if(e.endpoint!==void 0)return"endpoint";if(e.ingestion!==void 0)return"ingestion";if(e.transform!==void 0)return"transform";if(e.parallel!==void 0)return"parallel";if(e.map!==void 0)return"map";if(e.loop!==void 0)return"loop";if(e.sub_pipeline!==void 0)return"sub_pipeline"}return null}function H(e){return!e||typeof e!="object"||Array.isArray(e)?{}:typeof e.mappings=="object"&&e.mappings!==null&&!Array.isArray(e.mappings)?{...e.mappings}:{...e}}function gn(e){const t=vo(e)??"agent",n=typeof e.name=="string"&&e.name?e.name:t,r={...e,name:n};t==="ingestion"&&r.ingestion===void 0&&typeof e.ingestor=="string"&&(r.ingestion=e.ingestor),delete r.ingestor,delete r.step_type;let i=[];if(t==="parallel"&&Array.isArray(e.parallel?.steps))i=e.parallel.steps.map(a=>gn(a));else if(t==="loop"&&e.loop&&typeof e.loop=="object"){const a=e.loop.step&&typeof e.loop.step=="object"?e.loop.step:{};i=[gn(a)]}for(const a of["input","output"])r[a]!==void 0&&(r[a]=H(r[a]));if(t==="map"&&r.map&&typeof r.map=="object")for(const a of["input","output"])r.map[a]!==void 0&&(r.map[a]=H(r.map[a]));return{id:Wr(),kind:t,name:n,config:r,children:i}}function Gr(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(t.steps)?t.steps:[];return{meta:{name:typeof t.name=="string"&&t.name?t.name:"my_pipeline",description:typeof t.description=="string"?t.description:"",version:typeof t.version=="string"?t.version:"1.0.0",on_error:["fail_fast","continue","rollback"].includes(t.on_error)?t.on_error:"fail_fast",timeout:typeof t.timeout=="number"?t.timeout:300,strict_schema:!!t.strict_schema,input_schema:t.input_schema&&typeof t.input_schema=="object"?t.input_schema:{},output_schema:t.output_schema&&typeof t.output_schema=="object"?t.output_schema:{},defaults:t.defaults&&typeof t.defaults=="object"?t.defaults:{},metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{}},steps:n.map(i=>gn(i))}}const Xe={agent:30,plugin:30,endpoint:30,ingestion:300,transform:10,parallel:60,map:120,loop:120,sub_pipeline:120};function At(e){if(!(!e||Object.keys(e).length===0))return{...e}}function zr(e){if(!e||typeof e!="object")return;const t={};return e.max_attempts!==void 0&&(t.max_attempts=e.max_attempts),e.backoff&&(t.backoff=e.backoff),e.base_delay!==void 0&&(t.base_delay=e.base_delay),Object.keys(t).length>0?t:void 0}function sr(e,t){const n=e.kind,r=e.config,i=At(r.input);i&&(t.input=i);const a=At(r.output);a&&(t.output=a),typeof r.condition=="string"&&r.condition.trim()&&(t.condition=r.condition),r.on_error&&r.on_error!=="fail"&&(t.on_error=r.on_error),r.fallback_agent&&(t.fallback_agent=r.fallback_agent),Array.isArray(r.upstreams)&&r.upstreams.length>0&&(t.upstreams=[...r.upstreams]);const l=zr(r.retry);return l&&(t.retry=l),typeof r.timeout=="number"&&r.timeout!==Xe[n]&&(t.timeout=r.timeout),r.metadata&&typeof r.metadata=="object"&&Object.keys(r.metadata).length>0&&(t.metadata={...r.metadata}),typeof r.rollback=="string"&&r.rollback.trim()&&(t.rollback=r.rollback),t}function hn(e){const t=e.kind,n=e.config;if(t==="transform"){const a={name:e.name,transform:n.transform??""};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(a.upstreams=[...n.upstreams]),typeof n.condition=="string"&&n.condition.trim()&&(a.condition=n.condition),n.on_error&&n.on_error!=="fail"&&(a.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Xe.transform&&(a.timeout=n.timeout),a}if(t==="parallel"){const a={steps:e.children.map(o=>hn(o))};n.parallel?.strategy&&n.parallel.strategy!=="all"&&(a.strategy=n.parallel.strategy),typeof n.parallel?.max_concurrency=="number"&&n.parallel.max_concurrency!==5&&(a.max_concurrency=n.parallel.max_concurrency);const l={name:e.name,parallel:a};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(l.upstreams=[...n.upstreams]),n.on_error&&n.on_error!=="fail"&&(l.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Xe.parallel&&(l.timeout=n.timeout),l}if(t==="map"){const a=n.map&&typeof n.map=="object"?n.map:{},l={agent:typeof a.agent=="string"?a.agent:"",items:typeof a.items=="string"?a.items:""};a.item_key&&a.item_key!=="item"&&(l.item_key=a.item_key),a.index_key&&a.index_key!=="index"&&(l.index_key=a.index_key);const o=At(a.input);o&&(l.input=o);const u=At(a.output);u&&(l.output=u),typeof a.max_concurrency=="number"&&a.max_concurrency!==4&&(l.max_concurrency=a.max_concurrency),a.strategy&&a.strategy!=="all"&&(l.strategy=a.strategy);const p=zr(a.retry);p&&(l.retry=p),typeof a.item_timeout=="number"&&a.item_timeout!==60&&(l.item_timeout=a.item_timeout),a.fallback_agent&&(l.fallback_agent=a.fallback_agent);const c={name:e.name,map:l};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(c.upstreams=[...n.upstreams]),typeof n.condition=="string"&&n.condition.trim()&&(c.condition=n.condition),n.on_error&&n.on_error!=="fail"&&(c.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Xe.map&&(c.timeout=n.timeout),n.metadata&&typeof n.metadata=="object"&&Object.keys(n.metadata).length>0&&(c.metadata={...n.metadata}),typeof n.rollback=="string"&&n.rollback.trim()&&(c.rollback=n.rollback),c}if(t==="loop"){const a=e.children[0],l={step:a?hn(a):{name:"",agent:""}};typeof n.loop?.max_iterations=="number"&&n.loop.max_iterations!==10&&(l.max_iterations=n.loop.max_iterations),typeof n.loop?.until=="string"&&n.loop.until.trim()&&(l.until=n.loop.until);const o={name:e.name,loop:l};return Array.isArray(n.upstreams)&&n.upstreams.length>0&&(o.upstreams=[...n.upstreams]),n.on_error&&n.on_error!=="fail"&&(o.on_error=n.on_error),typeof n.timeout=="number"&&n.timeout!==Xe.loop&&(o.timeout=n.timeout),o}if(t==="sub_pipeline"){const a={name:e.name,sub_pipeline:n.sub_pipeline??""};return sr(e,a)}const r={agent:"agent",plugin:"plugin",endpoint:"endpoint",ingestion:"ingestion"},i={name:e.name,[r[t]]:typeof n[r[t]]=="string"?n[r[t]]:""};return sr(e,i)}function yt(e){const t=e.meta,n={name:t.name,steps:e.steps.map(r=>hn(r))};return t.description&&(n.description=t.description),t.version&&t.version!=="1.0.0"&&(n.version=t.version),Object.keys(t.input_schema).length>0&&(n.input_schema=t.input_schema),Object.keys(t.output_schema).length>0&&(n.output_schema=t.output_schema),Object.keys(t.defaults).length>0&&(n.defaults=t.defaults),t.on_error&&t.on_error!=="fail_fast"&&(n.on_error=t.on_error),t.strict_schema&&(n.strict_schema=!0),t.timeout!==300&&(n.timeout=t.timeout),Object.keys(t.metadata).length>0&&(n.metadata=t.metadata),n}function No(e){return mo(yt(e),{noRefs:!0})}function jo(e){let t;try{t=_s(e)}catch(n){throw new Error(`Invalid YAML: ${n?.message??String(n)}`)}if(!t||typeof t!="object"||!Array.isArray(t.steps))throw new Error('YAML must be a pipeline mapping with a "steps" list');return Gr(t)}function So(e,t,n,r){const i=e.steps.map(a=>{if(a.id!==t)return a;if(n.length===0)return{...a,config:{...r,name:a.name}};const l=a.children.map(o=>o.id!==n[0]?o:{...o,config:{...r,name:o.name}});return{...a,children:l}});return{...e,steps:i}}function Ao(e,t,n,r){const i=e.steps.map(l=>l.name),a=e.steps.map(l=>{if(l.id!==t)return l;if(n.length===0){const p=Ve(r||l.name,i.filter(c=>c!==l.name));return{...l,name:p,config:{...l.config,name:p}}}const o=l.children.map(p=>p.name),u=l.children.map(p=>{if(p.id!==n[0])return p;const c=Ve(r||p.name,o.filter(f=>f!==p.name));return{...p,name:c,config:{...p.config,name:c}}});return{...l,children:u}});return{...e,steps:a}}function Jr(e,t){return{...e,meta:t}}function Co(e,t){const n=Ve(t==="sub_pipeline"?"sub":t,e.steps.map(r=>r.name));return{...e,steps:[...e.steps,It(t,n)]}}function or(e,t,n){const r=Ve(n||t,e.steps.map(l=>l.name)),i=It(t,r),a={agent:"agent",plugin:"plugin",endpoint:"endpoint",ingestion:"ingestion",sub_pipeline:"sub_pipeline"};return{...e,steps:[...e.steps,{...i,config:{...i.config,[a[t]]:n}}]}}function $o(e,t){return{...e,steps:e.steps.filter(n=>n.id!==t)}}function lr(e,t,n,r){const i=a=>{const l=[...a],[o]=l.splice(t,1);if(!o)return a;const u=Math.max(0,Math.min(n,l.length));return l.splice(u,0,o),l};return r?{...e,steps:e.steps.map(a=>a.id===r?{...a,children:i(a.children)}:a)}:{...e,steps:i(e.steps)}}function wo(e,t){const n=e.steps.map(r=>{if(r.id!==t)return r;const i="agent",a=Ve("child",r.children.map(o=>o.name)),l=It(i,a);return{...r,children:[...r.children,l]}});return{...e,steps:n}}function _o(e,t,n){const r=e.steps.map(i=>{if(i.id!==t)return i;const a=i.children.filter(l=>l.id!==n);return i.kind==="loop"&&a.length===0?{...i,children:[It("agent",Ve("child",[]))]}:{...i,children:a}});return{...e,steps:r}}const zt=["input","defaults","context","current","steps"];function ko(e,t){const n=[],r=(i,a,l)=>{const o=H(i);Object.keys(o).length>0&&n.push({label:`Step '${e.name}' ${a} mapping`,mapping:o,isInput:l,index:t})};r(e.config.input,"input",!0),r(e.config.output,"output",!1),e.kind==="map"&&e.config.map&&typeof e.config.map=="object"&&(r(e.config.map.input,"input",!0),r(e.config.map.output,"output",!1));for(const i of e.children)r(i.config.input,"input",!0),r(i.config.output,"output",!1);return n}function To(e,t,n,r,i,a,l,o){if(typeof e!="string"||!e.startsWith("$"))return;const u=e.replace(/^\$\.?/,"").split(".").filter(c=>c.length>0);if(!n){u.length>0&&zt.includes(u[0])&&l.push({stepName:o,severity:"warning",message:`${t}: output mapping '${e}' starts with '${u[0]}' — output mappings resolve against this step's own output, not the pipeline context`});return}if(u.length===0){l.push({stepName:o,severity:"warning",message:`${t}: expression '${e}' resolves to nothing — use a path like '$.input.query'`});return}const p=u[0];if(!zt.includes(p)){l.push({stepName:o,severity:"error",message:`${t}: unknown mapping root '${p}' in '${e}' (expected one of: ${zt.join(", ")})`});return}if(p==="steps"&&u.length>=2){const c=u[1].split("[")[0];if(c!=="*"){const f=i.indexOf(c);f===-1?l.push({stepName:o,severity:"error",message:`${t}: '${e}' references step '${c}' which does not exist in the pipeline`}):f>=r&&!a.has(c)&&l.push({stepName:o,severity:"error",message:`${t}: '${e}' references step '${c}' which runs after this step — move it earlier or declare it in upstreams`})}}}function mt(e,t,n,r){const i=e.on_error;i==="skip"?n.push({stepName:r,severity:"warning",message:`${t} uses on_error=skip — failures will be silently ignored`}):i==="retry"&&!e.retry?n.push({stepName:r,severity:"warning",message:`${t} uses on_error=retry but has no retry config`}):i==="fallback"&&!e.fallback_agent&&n.push({stepName:r,severity:"warning",message:`${t} uses on_error=fallback but has no fallback_agent`})}function Eo(e,t,n,r){const i=`Step '${e.name}'`,a=e.config,l=new Set(Me(e));for(const o of Me(e))o===e.name?r.push({stepName:e.name,severity:"error",message:`${i} cannot depend on itself`}):n.includes(o)||r.push({stepName:e.name,severity:"error",message:`${i} references unknown upstream '${o}'`});switch(e.kind){case"agent":a.agent||r.push({stepName:e.name,severity:"error",message:`${i} has no agent selected`});break;case"plugin":a.plugin||r.push({stepName:e.name,severity:"error",message:`${i} has no plugin selected`});break;case"endpoint":a.endpoint||r.push({stepName:e.name,severity:"error",message:`${i} has no endpoint selected`});break;case"ingestion":a.ingestion||r.push({stepName:e.name,severity:"error",message:`${i} has no ingestor selected`});break;case"sub_pipeline":a.sub_pipeline||r.push({stepName:e.name,severity:"error",message:`${i} has no pipeline selected`});break;case"transform":!a.transform||!String(a.transform).trim()?r.push({stepName:e.name,severity:"error",message:`${i} has no transform code`}):String(a.transform).includes("return")||r.push({stepName:e.name,severity:"warning",message:`${i} transform code does not contain a 'return' — the step will produce no output`});break;case"parallel":e.children.length===0&&r.push({stepName:e.name,severity:"error",message:`${i} has no steps — add at least one agent step`});for(const o of e.children)o.config.agent||r.push({stepName:o.name,severity:"error",message:`Step '${o.name}' (inside parallel '${e.name}') has no agent selected`}),Me(o).length>0&&r.push({stepName:o.name,severity:"warning",message:`Step '${o.name}' (inside parallel '${e.name}') declares upstreams — nested steps are not independently scheduled; declare the dependency on the container step instead`}),mt(o.config,`Step '${o.name}' (inside parallel '${e.name}')`,r,o.name);break;case"map":{const o=a.map&&typeof a.map=="object"?a.map:{};o.agent||r.push({stepName:e.name,severity:"error",message:`${i} has no agent selected`}),o.items||r.push({stepName:e.name,severity:"error",message:`${i} has no items expression`}),mt(o,i,r,e.name);break}case"loop":if(e.children.length!==1)r.push({stepName:e.name,severity:"error",message:`${i} must contain exactly one agent step`});else{const o=e.children[0];o.config.agent||r.push({stepName:o.name,severity:"error",message:`Step '${o.name}' (inside loop '${e.name}') has no agent selected`}),Me(o).length>0&&r.push({stepName:o.name,severity:"warning",message:`Step '${o.name}' (inside loop '${e.name}') declares upstreams — nested steps are not independently scheduled; declare the dependency on the container step instead`}),mt(o.config,`Step '${o.name}' (inside loop '${e.name}')`,r,o.name)}break}e.kind!=="parallel"&&e.kind!=="loop"&&mt(a,i,r,e.name);for(const o of ko(e,t))for(const[u,p]of Object.entries(o.mapping))To(p,`${o.label} '${u}'`,o.isInput,o.index,n,l,r,e.name)}function Me(e){const t=e.config.upstreams;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Io(e){const t=e.map(u=>u.name),n=new Map;t.forEach((u,p)=>{n.has(u)||n.set(u,p)});const r=new Array(e.length).fill(0),i=e.map(()=>[]);for(let u=0;u0;){const u=a.shift();l.add(u);for(const p of i[u])r[p]-=1,r[p]===0&&a.push(p)}const o=e.map((u,p)=>p).filter(u=>!l.has(u));return o.length>0?o.map(u=>t[u]):null}function cr(e){const t=[],n=e.meta;if(!n.name||!n.name.trim()?t.push({severity:"error",message:"Pipeline name is required"}):/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(n.name)||t.push({severity:"error",message:"Invalid pipeline name — use letters, digits, '_', '-', '.'"}),e.steps.length===0)return t.push({severity:"error",message:"Add at least one step to the pipeline"}),t;const r=e.steps.map(l=>l.name),i=new Set;for(const l of r)!l||!l.trim()?t.push({severity:"error",message:"Every step needs a name"}):i.has(l)&&t.push({severity:"error",message:`Duplicate step name: '${l}'`}),i.add(l);e.steps.forEach((l,o)=>Eo(l,o,r,t));const a=Io(e.steps);return a&&t.push({severity:"error",message:`Cycle detected in upstream dependencies involving steps: ${a.join(", ")}`}),t}const ur=/Step '([^']+)'/g;function Oo(e,t,n){const r=[...e];for(const[i,a]of[[t,"error"],[n,"warning"]])for(const l of i){const o=ur.exec(l);ur.lastIndex=0,r.push({message:l,severity:a,stepName:o?o[1]:void 0})}return r}function Ro(e){const t={};for(const n of e){if(!n.stepName)continue;const r=t[n.stepName]??{errors:0,warnings:0};n.severity==="error"?r.errors+=1:r.warnings+=1,t[n.stepName]=r}return t}const pr="application/x-agentomatic-step-kind",dr="application/x-agentomatic-resource",Qr={agent:Si,plugin:ji,endpoint:Ni,ingestion:vi,transform:yi,parallel:bi,map:xi,loop:hi,sub_pipeline:gi},Xr={agent:"text-blue-500",plugin:"text-purple-500",endpoint:"text-emerald-500",ingestion:"text-teal-500",transform:"text-amber-500",parallel:"text-pink-500",map:"text-indigo-500",loop:"text-orange-500",sub_pipeline:"text-cyan-500"};function Ct(e,t){const n=e[t];return typeof n=="string"?n:""}function $t(e){return e.map&&typeof e.map=="object"?e.map:{}}function fr(e){if(!e||typeof e!="object"||Array.isArray(e))return 0;const t=e,n=t.mappings;return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).length:Object.keys(t).length}function Lo(e){const t=e.kind==="map"?$t(e.config).input:e.config.input;if(!t||typeof t!="object"||Array.isArray(t))return[];const n=t,r=n.mappings&&typeof n.mappings=="object"&&!Array.isArray(n.mappings)?n.mappings:n;return Object.entries(r).filter(([,i])=>typeof i=="string"&&i.length>0).map(([i,a])=>({target:i==="__root__"?"Request body":i,source:String(a).replace(/^\$\.steps\./,"").replace(/^\$\.input\./,"input · ").replace(/^\$\.defaults\./,"defaults · ")}))}function Fo(e){const{kind:t,config:n,children:r}=e;switch(t){case"agent":case"plugin":case"endpoint":case"ingestion":{const i=n[t];return typeof i=="string"&&i.trim()?i:"—"}case"transform":{const i=n.transform,a=typeof i=="string"?i:"";return a.trim()?a.length>40?`${a.slice(0,40)}…`:a:"—"}case"map":return Ct($t(n),"agent")||"—";case"parallel":return`${r.length} step${r.length===1?"":"s"}`;case"loop":return Ct(r[0]?.config??{},"agent")||"—";case"sub_pipeline":{const i=n.sub_pipeline;return typeof i=="string"&&i.trim()?i:"—"}}}function Po(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${Math.round(e)}ms`}function Jt(e){const t=e.config.upstreams;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}const Mr=({issues:e})=>e?s.jsxs(s.Fragment,{children:[e.errors>0&&s.jsx("span",{title:`${e.errors} error${e.errors===1?"":"s"}`,className:"flex h-4 min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-semibold leading-none text-white",children:e.errors}),e.warnings>0&&s.jsx("span",{title:`${e.warnings} warning${e.warnings===1?"":"s"}`,className:"flex h-4 min-w-[16px] items-center justify-center rounded-full bg-amber-500 px-1 text-[10px] font-semibold leading-none text-white",children:e.warnings})]}):null,Do=({status:e})=>{if(!e||e.status==="pending")return null;const t=e.status==="running"?"bg-blue-500 animate-pulse":e.status==="success"?"bg-green-500":e.status==="failed"?"bg-red-500":"bg-gray-400";return s.jsxs("span",{className:"flex items-center gap-1",title:e.error??e.status,children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${t}`}),e.durationMs!=null&&s.jsx("span",{className:"text-[10px] leading-none text-gray-400 dark:text-gray-500",children:Po(e.durationMs)})]})},Uo=({child:e,parentId:t,selected:n,issues:r,dragState:i,onDragStart:a,onDragEnd:l,onDrop:o,onSelect:u,onRemove:p,darkMode:c})=>{const[f,m]=y.useState(!1),b=Qr[e.kind],g=i!==null&&i.containerId===t,j=f&&g,O=U=>{g&&(U.preventDefault(),U.dataTransfer.dropEffect="move",m(!0))},Y=U=>{U.currentTarget.contains(U.relatedTarget)||m(!1)},D=U=>{g&&(U.preventDefault(),m(!1),o())};return s.jsxs("div",{className:`group flex cursor-pointer select-none items-center gap-1.5 rounded-md border p-1.5 transition-colors ${c?"border-gray-600 text-gray-100":"border-gray-200 text-gray-900"} ${j?"bg-blue-50 dark:bg-blue-900/30":c?"bg-gray-700":"bg-white"} ${j?"ring-2 ring-blue-400":n?"ring-2 ring-blue-500":""}`,onClick:U=>{U.stopPropagation(),u()},onDragOver:O,onDragLeave:Y,onDrop:D,children:[s.jsx("span",{draggable:!0,onDragStart:U=>{U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/plain",e.id),a()},onDragEnd:l,className:`cursor-grab active:cursor-grabbing ${c?"text-gray-500 hover:text-gray-300":"text-gray-400 hover:text-gray-600"}`,title:"Drag to reorder",children:s.jsx(yr,{size:14})}),s.jsx("span",{className:Xr[e.kind],children:s.jsx(b,{size:14})}),s.jsxs("button",{type:"button",onClick:U=>{U.stopPropagation(),u()},className:`min-w-0 flex-1 truncate text-left text-xs font-medium underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-blue-500 ${c?"text-gray-100":"text-gray-900"}`,"aria-label":`Configure ${qe[e.kind].label} step ${e.name}`,title:"Configure this step",children:[s.jsx("span",{children:e.name}),s.jsx("span",{className:`ml-1.5 shrink-0 rounded px-1.5 py-0.5 text-[10px] font-semibold no-underline ${c?"bg-blue-950/60 text-blue-300":"bg-blue-50 text-blue-700"}`,children:"Configure"})]}),s.jsx(Mr,{issues:r}),s.jsx("button",{onClick:U=>{U.stopPropagation(),p()},className:`rounded p-0.5 transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100 ${c?"text-gray-400 hover:bg-gray-600 hover:text-red-400":"text-gray-400 hover:bg-gray-200 hover:text-red-600"}`,title:"Remove child step",children:s.jsx(wt,{size:14})})]})},Bo=({step:e,selected:t,selectedChildId:n,runStatus:r,issueCounts:i,canMoveUp:a,canMoveDown:l,dragState:o,onDragStart:u,onDragEnd:p,onDrop:c,onDropChild:f,onSelect:m,onSelectChild:b,onMove:g,onDelete:j,onAddChild:O,onRemoveChild:Y,darkMode:D})=>{const[U,Q]=y.useState(!1),I=Qr[e.kind],v=qe[e.kind],T=i[e.name],w=Fo(e),z=Lo(e),re=o!==null&&o.containerId===null,Z=U&&re,de=Z?"ring-2 ring-blue-400":r?.status==="running"?"ring-2 ring-blue-500":r?.status==="success"?"ring-2 ring-green-500":r?.status==="failed"?"ring-2 ring-red-500":t?"ring-2 ring-blue-500":"",Ie=Z?"bg-blue-50 dark:bg-blue-900/30":"bg-gray-100 dark:bg-gray-800",je=_=>{re&&(_.preventDefault(),_.dataTransfer.dropEffect="move",Q(!0))},Oe=_=>{_.currentTarget.contains(_.relatedTarget)||Q(!1)},Se=_=>{re&&(_.preventDefault(),Q(!1),c())},ie=`rounded p-0.5 transition-colors disabled:pointer-events-none disabled:opacity-30 ${D?"text-gray-500 hover:bg-gray-700 hover:text-gray-200":"text-gray-400 hover:bg-gray-200 hover:text-gray-700"}`;return s.jsxs("div",{className:`group w-full max-w-2xl cursor-pointer select-none rounded-xl border p-3 transition-colors ${Ie} ${de} ${D?"border-gray-700 text-gray-100":"border-gray-200 text-gray-900"}`,onClick:m,onDragOver:je,onDragLeave:Oe,onDrop:Se,children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{draggable:!0,onDragStart:_=>{_.dataTransfer.effectAllowed="move",_.dataTransfer.setData("text/plain",e.id),u(e.id,null)},onDragEnd:p,className:`cursor-grab active:cursor-grabbing ${D?"text-gray-500 hover:text-gray-300":"text-gray-400 hover:text-gray-600"}`,title:"Drag to reorder",children:s.jsx(yr,{size:16})}),s.jsx("span",{className:Xr[e.kind],children:s.jsx(I,{size:16})}),s.jsxs("button",{type:"button",onClick:_=>{_.stopPropagation(),m()},className:`min-w-0 flex-1 truncate text-left text-sm font-medium underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-blue-500 ${D?"text-gray-100":"text-gray-900"}`,"aria-label":`Configure ${v.label} step ${e.name}`,title:"Configure this step",children:[s.jsx("span",{children:e.name}),s.jsx("span",{className:`ml-1.5 shrink-0 rounded px-1.5 py-0.5 text-[10px] font-semibold no-underline ${D?"bg-blue-950/60 text-blue-300":"bg-blue-50 text-blue-700"}`,children:"Configure"})]}),s.jsx(Mr,{issues:T}),s.jsx(Do,{status:r}),s.jsx("button",{onClick:_=>{_.stopPropagation(),g(-1)},disabled:!a,className:ie,title:"Move up",children:s.jsx(vr,{size:14})}),s.jsx("button",{onClick:_=>{_.stopPropagation(),g(1)},disabled:!l,className:ie,title:"Move down",children:s.jsx(Nr,{size:14})}),s.jsx("button",{onClick:_=>{_.stopPropagation(),j()},className:`${ie} opacity-0 group-hover:opacity-100 focus:opacity-100`,title:"Delete step",children:s.jsx(Ai,{size:14})})]}),s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:s.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${v.badge}`,children:v.label})}),s.jsx("p",{className:"mt-1 truncate text-xs text-gray-500 dark:text-gray-400",title:w,children:w}),s.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2 text-[10px]",children:[s.jsxs("div",{className:"rounded-md bg-white/60 px-2 py-1.5 dark:bg-gray-900/40",children:[s.jsx("span",{className:"block font-semibold uppercase tracking-wide text-gray-400",children:"receives"}),s.jsxs("span",{className:"truncate text-gray-600 dark:text-gray-300",children:[fr(e.config.input)||"default"," input mapping(s)"]})]}),s.jsxs("div",{className:"rounded-md bg-white/60 px-2 py-1.5 dark:bg-gray-900/40",children:[s.jsx("span",{className:"block font-semibold uppercase tracking-wide text-gray-400",children:"emits"}),s.jsxs("span",{className:"truncate text-gray-600 dark:text-gray-300",children:[fr(e.config.output)||"default"," output mapping(s)"]})]})]}),z.length>0&&s.jsxs("div",{className:`mt-2 rounded-md border px-2 py-1.5 text-[10px] ${D?"border-blue-900/70 bg-blue-950/30":"border-blue-100 bg-blue-50/70"}`,children:[s.jsx("span",{className:`block font-semibold uppercase tracking-wide ${D?"text-blue-300":"text-blue-700"}`,children:"field links"}),z.slice(0,3).map(_=>s.jsxs("p",{className:`mt-0.5 truncate font-mono ${D?"text-gray-300":"text-gray-700"}`,title:`${_.source} → ${_.target}`,children:[_.source," → ",_.target]},`${_.target}:${_.source}`)),z.length>3&&s.jsxs("p",{className:`mt-0.5 ${D?"text-gray-400":"text-gray-500"}`,children:["+",z.length-3," more"]})]}),Jt(e).length>0&&s.jsxs("p",{className:"mt-1 truncate text-[10px] font-medium text-indigo-500 dark:text-indigo-400",title:`Runs after: ${Jt(e).join(", ")}`,children:["⤴ ",Jt(e).join(", ")]}),e.kind==="map"&&s.jsxs("div",{className:`mt-2 space-y-1 rounded-lg border border-dashed p-2 text-xs ${D?"border-gray-600 text-gray-400":"border-gray-300 text-gray-500"}`,children:[s.jsxs("p",{className:"truncate",children:[s.jsx("span",{className:"font-medium text-gray-400 dark:text-gray-500",children:"items:"})," ",Ct($t(e.config),"items")||"—"]}),s.jsxs("p",{className:"truncate",children:[s.jsx("span",{className:"font-medium text-gray-400 dark:text-gray-500",children:"strategy:"})," ",Ct($t(e.config),"strategy")||"—"]})]}),(e.kind==="parallel"||e.kind==="loop")&&s.jsxs("div",{className:`mt-2 rounded-lg border-2 border-dashed p-2 ${D?"border-gray-600":"border-gray-300"}`,children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500",children:v.label}),s.jsx("div",{className:"space-y-1.5",children:e.children.map(_=>s.jsx(Uo,{child:_,parentId:e.id,selected:_.id===n,issues:i[_.name],dragState:o,onDragStart:()=>u(_.id,e.id),onDragEnd:p,onDrop:()=>f(_.id),onSelect:()=>b(_.id),onRemove:()=>Y(_.id),darkMode:D},_.id))}),e.kind==="parallel"&&s.jsxs("button",{onClick:O,className:`mt-1.5 flex w-full items-center justify-center gap-1 rounded-md border border-dashed py-1 text-xs transition-colors ${D?"border-gray-600 text-gray-400 hover:bg-gray-700 hover:text-gray-200":"border-gray-300 text-gray-500 hover:bg-gray-200 hover:text-gray-700"}`,title:"Add child agent step",children:[s.jsx(jr,{size:14}),"Add agent"]})]})]})},Yo=({draft:e,selectedId:t,selectedChildPath:n,runStatuses:r,issueCounts:i,onSelect:a,onReorder:l,onMove:o,onAddChild:u,onRemoveChild:p,onDelete:c,onAddFromPalette:f,onAddResource:m,darkMode:b})=>{const[g,j]=y.useState(null),O=I=>Array.from(I.dataTransfer.types).includes(pr),Y=I=>Array.from(I.dataTransfer.types).includes(dr),D=I=>{!O(I)&&!Y(I)||(I.preventDefault(),I.dataTransfer.dropEffect="copy")},U=I=>{if(!O(I)&&!Y(I))return;if(I.preventDefault(),Y(I))try{const T=JSON.parse(I.dataTransfer.getData(dr));if(T&&typeof T.name=="string"&&typeof T.kind=="string"&&["agent","plugin","endpoint","ingestion","sub_pipeline"].includes(T.kind)){m(T.kind,T.name);return}}catch{}const v=I.dataTransfer.getData(pr);qe[v]&&f(v)},Q=(I,v)=>{if(!g||g.containerId!==v)return;const T=v===null?e.steps:e.steps.find(re=>re.id===v)?.children??[],w=T.findIndex(re=>re.id===g.id),z=T.findIndex(re=>re.id===I);w===-1||z===-1||w===z||(l(w,z,v??void 0),j(null))};return s.jsx("div",{className:"flex-1 overflow-auto rounded-2xl border border-dashed border-gray-200 bg-[radial-gradient(circle_at_1px_1px,rgba(148,163,184,0.20)_1px,transparent_0)] bg-[size:18px_18px] dark:border-gray-700 dark:bg-[radial-gradient(circle_at_1px_1px,rgba(148,163,184,0.12)_1px,transparent_0)]",onDragOver:D,onDrop:U,children:e.steps.length===0?s.jsx("div",{className:"flex h-full items-center justify-center p-8",children:s.jsxs("div",{className:"max-w-sm rounded-2xl border border-dashed border-blue-300 bg-white/75 p-6 text-center shadow-sm dark:border-blue-800 dark:bg-gray-800/75",children:[s.jsx("p",{className:"text-sm font-semibold",children:"Build your flow visually"}),s.jsx("p",{className:`mt-1 text-sm ${b?"text-gray-400":"text-gray-500"}`,children:"Drag a step or a discovered resource here, or use the quick-add menu. Connections appear in execution order."})]})}):s.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col items-center p-4",children:e.steps.map((I,v)=>{const T=t===I.id&&n&&n.length>0?n[0]:null;return s.jsxs(mi.Fragment,{children:[s.jsx(Bo,{step:I,selected:t===I.id&&T===null,selectedChildId:T,runStatus:r[I.name],issueCounts:i,canMoveUp:v>0,canMoveDown:vj({id:w,containerId:z}),onDragEnd:()=>j(null),onDrop:()=>Q(I.id,null),onDropChild:w=>Q(w,I.id),onSelect:()=>a(I.id,null),onSelectChild:w=>a(I.id,[w]),onMove:w=>o(I.id,w),onDelete:()=>c(I.id),onAddChild:()=>u(I.id),onRemoveChild:w=>p(I.id,w),darkMode:b}),v{const w=e.steps[v+1];return s.jsxs("button",{type:"button","aria-label":`Configure field links from ${I.name} to ${w.name}`,title:`Configure schema-aware field links into ${w.name}`,onClick:()=>a(w.id,null),className:`group/link flex h-12 shrink-0 flex-col items-center justify-center gap-1 rounded-md px-3 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 ${b?"hover:bg-blue-950/40":"hover:bg-blue-50"}`,children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${b?"bg-blue-500":"bg-blue-400"}`}),s.jsx("span",{className:`h-5 w-px ${b?"bg-blue-700":"bg-blue-300"}`}),s.jsx("span",{className:`text-[10px] leading-none ${b?"text-blue-400":"text-blue-500"}`,children:"Connect fields ↓"})]})})()]},I.id)})})})},qo="w-full px-3 py-2 rounded-lg border text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",Ko=e=>e?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900",ot=e=>`block text-xs font-medium mb-1 ${e?"text-gray-400":"text-gray-600"}`,lt=(e,t=!1)=>`${qo} ${Ko(e)}${t?" font-mono":""}`,pe=({label:e,value:t,onChange:n,placeholder:r,darkMode:i,mono:a,hint:l,list:o})=>s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:ot(i),children:e}),s.jsx("input",{type:"text",value:t,placeholder:r,list:o,onChange:u=>n(u.target.value),className:lt(i,a)}),l&&s.jsx("p",{className:`mt-1 text-xs ${i?"text-gray-500":"text-gray-400"}`,children:l})]}),ye=({label:e,value:t,onChange:n,min:r,max:i,step:a,darkMode:l})=>s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:ot(l),children:e}),s.jsx("input",{type:"number",value:t,min:r,max:i,step:a,onChange:o=>n(Number(o.target.value)),className:lt(l)})]}),ve=({label:e,value:t,options:n,onChange:r,darkMode:i,placeholder:a})=>{const l=a?[{value:"",label:a},...n]:n;return s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:ot(i),children:e}),s.jsx("select",{value:t,onChange:o=>r(o.target.value),className:lt(i),children:l.map(o=>s.jsx("option",{value:o.value,children:o.label},o.value))})]})},Qt=({label:e,value:t,onChange:n,rows:r=3,darkMode:i,mono:a,placeholder:l})=>s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:ot(i),children:e}),s.jsx("textarea",{value:t,rows:r,placeholder:l,onChange:o=>n(o.target.value),className:lt(i,a)})]}),Ho=({label:e,checked:t,onChange:n,darkMode:r})=>s.jsxs("label",{className:`flex items-center gap-2 mb-3 cursor-pointer text-sm ${r?"text-gray-300":"text-gray-700"}`,children:[s.jsx("input",{type:"checkbox",checked:t,onChange:i=>n(i.target.checked),className:"w-4 h-4 rounded accent-blue-500"}),e]}),Je=({label:e,value:t,onChange:n,darkMode:r})=>{const[i,a]=y.useState(()=>JSON.stringify(t,null,2)),[l,o]=y.useState(!1),u=y.useRef(i);u.current=i,y.useEffect(()=>{let c;try{c=JSON.parse(u.current)}catch{return}JSON.stringify(c)!==JSON.stringify(t)&&(a(JSON.stringify(t,null,2)),o(!1))},[t]);const p=c=>{a(c);try{const f=JSON.parse(c);o(!1),n(f)}catch{o(!0)}};return s.jsxs("div",{className:"mb-3",children:[e&&s.jsx("label",{className:ot(r),children:e}),s.jsx("textarea",{value:i,rows:6,spellCheck:!1,onChange:c=>p(c.target.value),className:lt(r,!0)}),l&&s.jsx("p",{className:"mt-1 text-xs text-red-500",children:"Invalid JSON"})]})},q=({title:e,children:t,darkMode:n})=>s.jsxs("div",{className:`p-3 mb-3 rounded-lg border ${n?"border-gray-700 bg-gray-800/30":"border-gray-200 bg-gray-50/50"}`,children:[s.jsx("h3",{className:`text-xs font-semibold uppercase tracking-wide mb-3 ${n?"text-gray-400":"text-gray-500"}`,children:e}),t]}),gt=e=>Object.entries(e??{}).map(([t,n],r)=>({id:r,key:t,value:typeof n=="string"?n:n==null?"":String(n)})),ht=e=>{const t={};for(const n of e)t[n.key]=n.value;return t},mr="application/x-agentomatic-mapping-source",Ot="__root__",gr=e=>e===Ot?"Request body":e,hr=e=>{if(e.startsWith("$.input."))return`Pipeline input · ${e.slice(8)}`;if(e.startsWith("$.steps.")){const[,,t,...n]=e.split(".");return n.length?`${t} · ${n.join(".")}`:`${t} · full result`}return e.startsWith("$.defaults.")?`Pipeline default · ${e.slice(11)}`:e==="$.defaults."?"Pipeline defaults":e==="$.context."?"Shared context":e==="$.current."?"Current item":e},Vo=e=>e.startsWith("$.input.")?"Pipeline input":e.startsWith("$.steps.")?e.split(".")[2]||"Step output":e.startsWith("$.defaults.")?"Pipeline defaults":e.startsWith("$.context.")?"Shared context":e.startsWith("$.current.")?"Current item":"Other source",Wo=(e,t)=>{const n=t.filter(a=>!a.endsWith(".")),r={};let i=!1;for(const a of e){const l=n.findIndex(p=>p.replace(/\[\d+\]/g,"").split(".").at(-1)===a);if(l<0&&i)continue;const o=l>=0?l:0,u=n[o];u&&(r[a]=u,n.splice(o,1),i||=l<0)}return r},Go=(e,t,n)=>{const r=new Set(Object.values(e).filter(l=>typeof l=="string"&&l.length>0)),i=t.filter(l=>!e[l]),a=Wo(i,n.filter(l=>!r.has(l)));return{...e,...a}},xr=({label:e,mappings:t,suggestions:n,targetSuggestions:r=[],onChange:i,darkMode:a})=>{const[l,o]=y.useState(()=>gt(t)),u=n.filter(v=>!v.endsWith(".")),[p,c]=y.useState(r[0]??""),[f,m]=y.useState(u[0]??""),b=y.useRef(l);b.current=l;const g=y.useRef(l.length);y.useEffect(()=>{const v=ht(b.current);JSON.stringify(v)!==JSON.stringify(t??{})&&o(gt(t??{}))},[t]),y.useEffect(()=>{r.includes(p)||c(r[0]??"")},[p,r]),y.useEffect(()=>{u.includes(f)||m(u[0]??"")},[u,f]);const j=v=>{o(v),i(ht(v))},O=()=>{g.current+=1,j([...l,{id:g.current,key:"",value:""}])},Y=()=>{const v=Go(ht(l),r,n);Object.keys(v).length!==0&&(g.current=Object.keys(v).length,j(gt(v)))},D=(v=p,T=f)=>{if(!v||!T)return;const w=ht(l);w[v]=T,g.current=Object.keys(w).length,j(gt(w))},U=u.reduce((v,T)=>{const w=Vo(T);return(v[w]??=[]).push(T),v},{}),Q=(v,T)=>{j(l.map(w=>w.id===v?{...w,...T}:w))},I=v=>{j(l.filter(T=>T.id!==v))};return s.jsxs("div",{className:"mb-3",children:[s.jsx("span",{className:`block text-xs font-medium mb-1 ${a?"text-gray-400":"text-gray-600"}`,children:e==="input"?"Input mappings":"Output mappings"}),s.jsx("datalist",{id:`builder-mapping-${e}`,children:n.map(v=>s.jsx("option",{value:v},v))}),s.jsx("datalist",{id:`builder-mapping-target-${e}`,children:r.map(v=>s.jsx("option",{value:v},v))}),r.length>0&&u.length>0&&s.jsxs("div",{className:`mb-3 rounded-lg border p-2.5 ${a?"border-blue-900/80 bg-blue-950/20":"border-blue-100 bg-blue-50/60"}`,children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-xs font-semibold ${a?"text-blue-200":"text-blue-800"}`,children:e==="input"?"Connect fields visually":"Route output visually"}),s.jsx("span",{className:`text-[10px] ${a?"text-blue-300/70":"text-blue-700/70"}`,children:"Click two fields or drag an output onto an input"})]}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wide ${a?"text-gray-400":"text-gray-600"}`,children:"Available outputs"}),s.jsx("div",{className:"space-y-1.5",children:Object.entries(U).map(([v,T])=>s.jsxs("div",{children:[s.jsx("p",{className:`mb-1 text-[10px] ${a?"text-blue-300/70":"text-blue-700/70"}`,children:v}),s.jsx("div",{className:"flex flex-wrap gap-1",children:T.map(w=>s.jsx("button",{type:"button",draggable:!0,"aria-pressed":f===w,title:"Click to select, or drag onto a target field",onDragStart:z=>{z.dataTransfer.effectAllowed="link",z.dataTransfer.setData(mr,w)},onClick:()=>m(w),className:`max-w-full truncate rounded border px-1.5 py-1 text-left text-[11px] transition-colors ${f===w?"border-blue-600 bg-blue-600 text-white":a?"border-gray-600 bg-gray-800 text-gray-200 hover:border-blue-400":"border-gray-200 bg-white text-gray-700 hover:border-blue-500"}`,children:hr(w)},w))})]},v))})]}),s.jsxs("div",{children:[s.jsx("p",{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wide ${a?"text-gray-400":"text-gray-600"}`,children:e==="input"?"Step inputs":"Pipeline outputs"}),s.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(v=>s.jsx("button",{type:"button","aria-label":e==="input"?`Field to receive a visual connection: ${v}`:`Pipeline output field to receive a visual route: ${v}`,"aria-pressed":p===v,onClick:()=>c(v),onDragOver:T=>T.preventDefault(),onDrop:T=>{T.preventDefault();const w=T.dataTransfer.getData(mr);u.includes(w)&&(m(w),c(v),D(v,w))},className:`rounded-md border px-2 py-1.5 font-mono text-xs transition-colors ${p===v?"border-blue-600 bg-blue-600 text-white":a?"border-dashed border-gray-500 bg-gray-800 text-gray-100 hover:border-blue-400":"border-dashed border-gray-300 bg-white text-gray-800 hover:border-blue-500"}`,title:"Select as the connection target, or drop an output here to link it",children:gr(v)},v))})]})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[p&&f&&s.jsxs("p",{className:`min-w-0 flex-1 truncate text-[11px] ${a?"text-blue-300/80":"text-blue-700/80"}`,children:[hr(f)," → ",s.jsx("span",{className:"font-mono",children:gr(p)})]}),s.jsx("button",{type:"button",onClick:()=>D(),disabled:!p||!f,className:"rounded-md bg-blue-600 px-2.5 py-1.5 text-xs font-semibold text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-400",children:"Link fields"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${a?"text-gray-400":"text-gray-600"}`,children:"Need a custom expression? The editable mapping rows below remain available."})]}),l.length===0&&s.jsx("p",{className:`text-xs mb-2 ${a?"text-gray-500":"text-gray-400"}`,children:"No mappings"}),l.map(v=>s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx(pe,{value:v.key,placeholder:"field",mono:!0,list:`builder-mapping-target-${e}`,onChange:T=>Q(v.id,{key:T}),darkMode:a}),v.key===Ot&&s.jsx("p",{className:`mt-1 text-[10px] ${a?"text-blue-300/80":"text-blue-700/80"}`,children:"Request body"})]}),s.jsx("div",{className:"flex-[1.5]",children:s.jsx(pe,{value:v.value,placeholder:e==="input"?"$.input...":"$",mono:!0,list:`builder-mapping-${e}`,onChange:T=>Q(v.id,{value:T}),darkMode:a})}),s.jsx("button",{onClick:()=>I(v.id),title:"Remove mapping",className:`p-1.5 rounded-lg transition-colors ${a?"hover:bg-gray-600 text-gray-400":"hover:bg-gray-200 text-gray-500"}`,children:s.jsx(wt,{size:14})})]},v.id)),n.length>0&&s.jsxs("div",{className:`mb-2 flex flex-wrap items-center gap-1 text-[11px] ${a?"text-gray-400":"text-gray-500"}`,children:[r.length>0&&s.jsx("button",{type:"button",onClick:Y,title:e==="input"?"Connect compatible upstream outputs to this step's input fields":"Route compatible step outputs to this pipeline's declared outputs",className:`mr-1 rounded border px-1.5 py-0.5 font-medium transition-colors ${a?"border-blue-700 bg-blue-900/30 text-blue-300 hover:bg-blue-900/60":"border-blue-200 bg-blue-50 text-blue-700 hover:bg-blue-100"}`,children:"Auto-connect"}),s.jsx("span",{className:"mr-1",children:"Quick sources"}),n.slice(0,14).map(v=>s.jsx("button",{type:"button",title:`Use ${v} for the current mapping`,onClick:()=>{const T=l.find(w=>!w.value)??l[l.length-1];T?Q(T.id,{value:v}):(g.current+=1,j([{id:g.current,key:r[0]??"",value:v}]))},className:`rounded border px-1.5 py-0.5 font-mono transition-colors ${a?"border-gray-600 hover:border-blue-400 hover:text-blue-300":"border-gray-200 hover:border-blue-500 hover:text-blue-700"}`,children:v},v))]}),s.jsxs("button",{onClick:O,className:`flex items-center gap-1 text-sm font-medium transition-colors ${a?"text-blue-400 hover:text-blue-300":"text-blue-600 hover:text-blue-700"}`,children:[s.jsx(jr,{size:14}),"Add mapping"]})]})},k=e=>typeof e=="string"?e:e==null?"":String(e),Fe=e=>typeof e=="number"?e:0,W=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},zo=(e,t,n)=>{const r=new Set(t),i=new Set(Array.isArray(n)?n.filter(a=>typeof a=="string"):[]);for(const a of Object.values(e)){if(typeof a!="string")continue;const l=/^\$\.steps\.([^.[\]]+)/.exec(a);l?.[1]&&r.has(l[1])&&i.add(l[1])}return Array.from(i)},Jo=[{value:"fail",label:"fail"},{value:"skip",label:"skip"},{value:"retry",label:"retry"},{value:"fallback",label:"fallback"}],Qo=[{value:"fail_fast",label:"fail_fast"},{value:"continue",label:"continue"},{value:"rollback",label:"rollback"}],br=[{value:"all",label:"all"},{value:"first",label:"first"},{value:"majority",label:"majority"}],Xo=[{value:"fixed",label:"fixed"},{value:"linear",label:"linear"},{value:"exponential",label:"exponential"}],Mo=["$","$.response","$.output","$.result","$.text"],Zo={agent:30,plugin:30,endpoint:30,ingestion:300,transform:10,parallel:60,map:120,loop:120,sub_pipeline:120},el=(e,t)=>typeof t=="number"?t:Zo[e],Pe=e=>{const t=W(e),n=W(t.properties);return Object.keys(n).length>0?Object.keys(n):Object.keys(t).filter(r=>!["$schema","$defs","$ref","type","title","description","required","additionalProperties","anyOf","oneOf","allOf","default","examples"].includes(r))},tl=e=>{const t=Pe(e);if(t.length>0)return t;const n=W(e);return n.type&&n.type!=="object"?[Ot]:[]},nl=(e,t)=>{const n=W(e),r=new Set(Array.isArray(n.required)?n.required.filter(l=>typeof l=="string"):[]),i=Object.entries(W(n.properties)).map(([l,o])=>{const u=W(o);return{name:l,type:k(u.type)||(Array.isArray(u.anyOf)?"union":"value"),required:r.has(l),description:k(u.description)}});if(i.length>0)return i;const a=k(n.type);return a&&a!=="object"?[{name:t,type:a,required:!0,description:k(n.description)}]:[]},xn={type:"object",properties:{items:{type:"array",description:"One result for every processed item."},by_key:{type:"object",description:"Results indexed by item position."},count:{type:"integer",description:"Number of input items."},succeeded:{type:"integer",description:"Number of successful item runs."}}},rl=e=>Pe(xn).map(t=>`$.steps.${e}.${t}`),il=({draft:e,selection:t,resources:n,agentSchemas:r,resourceSchemas:i={},resourceContractErrors:a={},onChange:l,darkMode:o})=>{if(t.type==="pipeline"){const d=e.meta,C=h=>l(Jr(e,{...d,...h}));return s.jsx("div",{className:"p-4",children:s.jsxs(q,{title:"Pipeline settings",darkMode:o,children:[s.jsx(pe,{label:"Name",value:d.name,onChange:h=>C({name:h}),darkMode:o}),s.jsx(Qt,{label:"Description",value:d.description,onChange:h=>C({description:h}),darkMode:o}),s.jsx(pe,{label:"Version",value:d.version,onChange:h=>C({version:h}),darkMode:o}),s.jsx(ve,{label:"On error",value:d.on_error,options:Qo,onChange:h=>C({on_error:h}),darkMode:o}),s.jsx(ye,{label:"Timeout (s)",value:d.timeout,onChange:h=>C({timeout:h}),darkMode:o}),s.jsx(Ho,{label:"Strict schema",checked:d.strict_schema,onChange:h=>C({strict_schema:h}),darkMode:o}),s.jsx(Je,{label:"Input schema",value:W(d.input_schema),onChange:h=>C({input_schema:h}),darkMode:o}),s.jsx(Je,{label:"Output schema",value:W(d.output_schema),onChange:h=>C({output_schema:h}),darkMode:o}),s.jsx(Je,{label:"Defaults",value:W(d.defaults),onChange:h=>C({defaults:h}),darkMode:o}),s.jsx(Je,{label:"Metadata",value:W(d.metadata),onChange:h=>C({metadata:h}),darkMode:o})]})})}const u=e.steps.find(d=>d.id===t.id);if(!u)return s.jsx("div",{className:"p-4",children:s.jsx("p",{className:`text-sm ${o?"text-gray-400":"text-gray-500"}`,children:"Select a step or pipeline settings"})});let p=u;if(t.childPath.length>0){const d=u.children.find(C=>C.id===t.childPath[0]);d&&(p=d)}const c=d=>l(So(e,t.id,t.childPath,d)),f={...p.config},m=p.kind,b=t.childPath.length>0,g=qe[m].label,j=n.agents.map(d=>({value:d.name,label:d.name})),O=n.plugins.map(d=>({value:d.name,label:d.name})),Y=n.endpoints.map(d=>({value:d.name,label:d.name})),D=n.ingestors.map(d=>({value:d.name,label:d.name})),U=n.pipelines.filter(d=>d.name!==e.meta.name).map(d=>({value:d.name,label:d.name})),Q=()=>{const d=b||m==="agent"?k(f.agent):m==="map"?k(W(f.map).agent):"";return d?r[d]?.input_schema??null:m==="plugin"?i[`plugin:${k(f.plugin)}`]?.input_schema??null:m==="endpoint"?i[`endpoint:${k(f.endpoint)}`]?.input_schema??null:m==="ingestion"?i[`ingestion:${k(f.ingestion)}`]?.input_schema??null:m==="sub_pipeline"?i[`sub_pipeline:${k(f.sub_pipeline)}`]?.input_schema??null:null},I=()=>{if(m==="map")return xn;const d=b||m==="agent"?k(f.agent):"";return d?r[d]?.output_schema??null:m==="plugin"?i[`plugin:${k(f.plugin)}`]?.output_schema??null:m==="endpoint"?i[`endpoint:${k(f.endpoint)}`]?.output_schema??null:m==="ingestion"?i[`ingestion:${k(f.ingestion)}`]?.output_schema??null:m==="sub_pipeline"?i[`sub_pipeline:${k(f.sub_pipeline)}`]?.output_schema??null:null},v=d=>{if(d.kind==="map")return rl(d.name);const C=d.kind==="agent"?k(d.config.agent):d.kind==="plugin"?k(d.config.plugin):d.kind==="endpoint"?k(d.config.endpoint):d.kind==="ingestion"?k(d.config.ingestion):d.kind==="sub_pipeline"?k(d.config.sub_pipeline):"",h=d.kind==="agent"?r[C]?.output_schema:i[`${d.kind}:${C}`]?.output_schema,P=Pe(h);return P.length?P.map(K=>`$.steps.${d.name}.${K}`):[`$.steps.${d.name}`]},T=e.steps.findIndex(d=>d.id===t.id),w=e.steps.filter((d,C)=>C{if(b)return{};const C=zo(d,e.steps.filter(h=>h.id!==t.id).map(h=>h.name),f.upstreams);return C.length?{upstreams:C}:{}},de=[...z.map(d=>`$.input.${d}`),"$.defaults.","$.context.","$.current.",...w.flatMap(v)],Ie=tl(Q()),je=Pe(I()),Oe=je.length?["$",...je.map(d=>`$.${d}`)]:Mo,Se=d=>s.jsx("p",{className:`text-xs mb-3 ${o?"text-gray-500":"text-gray-400"}`,children:d}),ie=(d,C,h,P,K)=>h.length===0?Se(K):s.jsx(ve,{label:d,value:C,options:h,onChange:P,darkMode:o}),_=(d,C)=>s.jsxs(q,{title:"Execution",darkMode:o,children:[d&&s.jsx(pe,{label:"Condition",value:k(f.condition),placeholder:"e.g. $.input.ok == true",onChange:h=>c({...f,condition:h}),darkMode:o}),s.jsx(ve,{label:"On error",value:k(f.on_error)||"fail",options:Jo,onChange:h=>c({...f,on_error:h}),darkMode:o}),s.jsx(ye,{label:"Timeout (s)",value:el(m,f.timeout),min:.1,step:.1,onChange:h=>c({...f,timeout:h}),darkMode:o}),C&&s.jsx(Qt,{label:"Rollback",value:k(f.rollback),rows:3,mono:!0,onChange:h=>c({...f,rollback:h}),darkMode:o})]}),Ge=(d,C)=>s.jsxs(q,{title:"Retry",darkMode:o,children:[s.jsx(ye,{label:"Max attempts",value:Fe(d.max_attempts)||3,min:1,max:10,onChange:h=>C({...d,max_attempts:h}),darkMode:o}),s.jsx(ve,{label:"Backoff",value:k(d.backoff)||"fixed",options:Xo,onChange:h=>C({...d,backoff:h}),darkMode:o}),s.jsx(ye,{label:"Base delay (s)",value:Fe(d.base_delay)||.5,min:.1,max:60,step:.1,onChange:h=>C({...d,base_delay:h}),darkMode:o})]}),fe=(d,C,h,P)=>s.jsxs(q,{title:"Mappings",darkMode:o,children:[s.jsx(xr,{label:"input",mappings:d,suggestions:de,targetSuggestions:Ie,onChange:h,darkMode:o}),s.jsx(xr,{label:"output",mappings:C,suggestions:Oe,targetSuggestions:re,onChange:P,darkMode:o})]}),he=()=>s.jsx(q,{title:"Metadata",darkMode:o,children:s.jsx(Je,{label:"Metadata",value:W(f.metadata),onChange:d=>c({...f,metadata:d}),darkMode:o})}),xe=s.jsx(pe,{label:"Name",value:p.name,onChange:d=>l(Ao(e,t.id,t.childPath,d)),darkMode:o}),ct=()=>{const d={agent:"agent",plugin:"plugin",endpoint:"endpoint",ingestion:"ingestion",sub_pipeline:"sub_pipeline"},C=d[m]?k(f[d[m]]):g,h=Object.keys(H(f.input)).length,P=Object.keys(H(f.output)).length;return s.jsxs(q,{title:"Step contract",darkMode:o,children:[s.jsxs("p",{className:`mb-2 text-xs ${o?"text-gray-400":"text-gray-500"}`,children:["This ",g.toLowerCase()," runs as ",s.jsx("span",{className:"font-mono font-semibold",children:C||"not configured"}),"."]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[s.jsxs("div",{className:`rounded-md p-2 ${o?"bg-gray-900/50 text-gray-300":"bg-white text-gray-700"}`,children:[s.jsx("span",{className:"block text-[10px] font-semibold uppercase text-gray-400",children:"Input"}),h?`${h} mapping(s)`:"Uses pipeline context"]}),s.jsxs("div",{className:`rounded-md p-2 ${o?"bg-gray-900/50 text-gray-300":"bg-white text-gray-700"}`,children:[s.jsx("span",{className:"block text-[10px] font-semibold uppercase text-gray-400",children:"Output"}),P?`${P} mapping(s)`:"Default step output"]})]})]})},Rt=()=>{const d=b||m==="agent"?k(f.agent):m==="map"?k(W(f.map).agent):"",C=d?"agent":m==="plugin"||m==="endpoint"||m==="ingestion"||m==="sub_pipeline"?m:null,h=d||(C?k(f[C]):"");if(!C||!h)return null;const P=`${C}:${h}`,K=C==="agent"?r[h]:i[P],Ae=a[P],Ce=C==="agent"?"Agent schema":`${qe[C].label} schema`;if(!K)return s.jsx(q,{title:Ce,darkMode:o,children:s.jsxs("p",{role:"alert",className:`rounded-md border px-3 py-2 text-xs ${o?"border-amber-800 bg-amber-950/40 text-amber-200":"border-amber-300 bg-amber-50 text-amber-800"}`,children:[Ae||`Loading or unavailable for '${h}'.`," Retry live resources before relying on inferred mappings or test inputs. You can still configure explicit mappings below."]})});const R=(V,Lt,ut)=>{const Le=nl(V,ut);return Le.length?s.jsx("ul",{className:"space-y-1",children:Le.map(be=>s.jsxs("li",{className:`flex items-center justify-between gap-2 rounded px-2 py-1 text-xs ${o?"bg-gray-900/50 text-gray-300":"bg-white text-gray-700"}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",title:be.description,children:be.name}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[10px] text-gray-400",children:[be.type,be.required?" · required":""]})]},be.name))}):s.jsx("p",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:Lt})};return m==="map"?s.jsxs(q,{title:"Map step contract",darkMode:o,children:[s.jsxs("p",{className:`mb-3 text-xs ${o?"text-gray-400":"text-gray-500"}`,children:["Each item is sent to ",s.jsx("span",{className:"font-mono font-semibold",children:h})," using its live input schema. The map step itself emits an aggregate result for downstream links."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Per-item agent accepts"}),R(K.input_schema??{},"No declared input fields","Item value")]}),s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Map produces"}),R(xn,"No declared output fields","Response body")]})]})]}):s.jsxs(q,{title:Ce,darkMode:o,children:[s.jsxs("p",{className:`mb-3 text-xs ${o?"text-gray-400":"text-gray-500"}`,children:["Live contract for ",s.jsx("span",{className:"font-mono font-semibold",children:h}),". Map inputs to the required fields and route outputs explicitly when needed."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Accepts"}),R(K.input_schema??{},"No declared input fields","Request body")]}),s.jsxs("div",{children:[s.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:"Produces"}),R(K.output_schema??{},"No declared output fields","Response body")]})]})]})},Re=()=>{const d=new Set((Array.isArray(f.upstreams)?f.upstreams:[]).filter(P=>typeof P=="string")),C=e.steps.map(P=>P.name).filter(P=>P!==p.name),h=P=>{const K=new Set(d);K.has(P)?K.delete(P):K.add(P),c({...f,upstreams:Array.from(K)})};return s.jsxs(q,{title:"Upstreams (DAG)",darkMode:o,children:[Se("Steps that must complete before this one runs — makes their output available via $.steps regardless of canvas order."),C.length===0?s.jsx("p",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:"No other steps yet — add more steps to declare dependencies."}):s.jsx("div",{className:"space-y-1",children:C.map(P=>s.jsxs("label",{className:`flex items-center gap-2 text-sm cursor-pointer ${o?"text-gray-300":"text-gray-700"}`,children:[s.jsx("input",{type:"checkbox",checked:d.has(P),onChange:()=>h(P),className:"w-4 h-4 accent-blue-600"}),s.jsx("span",{className:"font-mono text-xs",children:P})]},P))})]})};let ae;if(b)ae=s.jsxs(s.Fragment,{children:[s.jsx(q,{title:g,darkMode:o,children:ie("Agent",k(f.agent),j,d=>c({...f,agent:d}),"No agents registered")}),fe(H(f.input),H(f.output),d=>c({...f,input:d,...Z(d)}),d=>c({...f,output:d})),Ge(W(f.retry),d=>c({...f,retry:d})),_(!0,!0)]});else switch(m){case"agent":ae=s.jsxs(s.Fragment,{children:[s.jsxs(q,{title:g,darkMode:o,children:[ie("Agent",k(f.agent),j,d=>c({...f,agent:d}),"No agents registered"),s.jsx(ve,{label:"Fallback agent",value:k(f.fallback_agent),options:j,placeholder:"None",onChange:d=>c({...f,fallback_agent:d}),darkMode:o})]}),_(!0,!0),Ge(W(f.retry),d=>c({...f,retry:d})),fe(H(f.input),H(f.output),d=>c({...f,input:d,...Z(d)}),d=>c({...f,output:d})),he()]});break;case"plugin":ae=s.jsxs(s.Fragment,{children:[s.jsx(q,{title:g,darkMode:o,children:ie("Plugin",k(f.plugin),O,d=>c({...f,plugin:d}),"No plugins registered")}),_(!0,!0),fe(H(f.input),H(f.output),d=>c({...f,input:d,...Z(d)}),d=>c({...f,output:d})),he()]});break;case"endpoint":ae=s.jsxs(s.Fragment,{children:[s.jsx(q,{title:g,darkMode:o,children:ie("Endpoint",k(f.endpoint),Y,d=>c({...f,endpoint:d}),"No endpoints registered")}),_(!0,!0),fe(H(f.input),H(f.output),d=>c({...f,input:d,...Z(d)}),d=>c({...f,output:d})),he()]});break;case"ingestion":ae=s.jsxs(s.Fragment,{children:[s.jsx(q,{title:g,darkMode:o,children:ie("Ingestor",k(f.ingestion),D,d=>c({...f,ingestion:d}),"No ingestors registered")}),_(!0,!0),fe(H(f.input),H(f.output),d=>c({...f,input:d,...Z(d)}),d=>c({...f,output:d})),he()]});break;case"sub_pipeline":ae=s.jsxs(s.Fragment,{children:[s.jsx(q,{title:g,darkMode:o,children:ie("Pipeline",k(f.sub_pipeline),U,d=>c({...f,sub_pipeline:d}),"No pipelines registered")}),_(!0,!0),fe(H(f.input),H(f.output),d=>c({...f,input:d,...Z(d)}),d=>c({...f,output:d})),he()]});break;case"transform":ae=s.jsxs(s.Fragment,{children:[s.jsx(q,{title:g,darkMode:o,children:s.jsx(Qt,{label:"Code",value:k(f.transform),rows:10,mono:!0,placeholder:`def transform(ctx): - return ctx.input`,onChange:d=>c({...f,transform:d}),darkMode:o})}),_(!0,!1)]});break;case"parallel":{const d=W(f.parallel),C=h=>c({...f,parallel:h});ae=s.jsxs(s.Fragment,{children:[s.jsxs(q,{title:g,darkMode:o,children:[Se("Children are edited on the canvas."),s.jsx(ve,{label:"Strategy",value:k(d.strategy)||"all",options:br,onChange:h=>C({...d,strategy:h}),darkMode:o}),s.jsx(ye,{label:"Max concurrency",value:Fe(d.max_concurrency)||5,min:1,max:20,onChange:h=>C({...d,max_concurrency:h}),darkMode:o})]}),_(!1,!1)]});break}case"map":{const d=W(f.map),C=h=>c({...f,map:h});ae=s.jsxs(s.Fragment,{children:[s.jsxs(q,{title:g,darkMode:o,children:[ie("Agent",k(d.agent),j,h=>C({...d,agent:h}),"No agents registered"),s.jsx(pe,{label:"Items",value:k(d.items),placeholder:"$.input.items",mono:!0,onChange:h=>C({...d,items:h}),darkMode:o}),s.jsx(pe,{label:"Item key",value:k(d.item_key),onChange:h=>C({...d,item_key:h}),darkMode:o}),s.jsx(pe,{label:"Index key",value:k(d.index_key),onChange:h=>C({...d,index_key:h}),darkMode:o}),s.jsx(ye,{label:"Max concurrency",value:Fe(d.max_concurrency)||4,min:1,max:64,onChange:h=>C({...d,max_concurrency:h}),darkMode:o}),s.jsx(ve,{label:"Strategy",value:k(d.strategy)||"all",options:br,onChange:h=>C({...d,strategy:h}),darkMode:o}),s.jsx(ye,{label:"Item timeout (s)",value:Fe(d.item_timeout)||60,min:.1,step:.1,onChange:h=>C({...d,item_timeout:h}),darkMode:o}),s.jsx(ve,{label:"Fallback agent",value:k(d.fallback_agent),options:j,placeholder:"None",onChange:h=>C({...d,fallback_agent:h}),darkMode:o})]}),fe(H(d.input),H(d.output),h=>c({...f,map:{...d,input:h},...Z(h)}),h=>C({...d,output:h})),_(!0,!0)]});break}case"loop":{const d=W(f.loop),C=h=>c({...f,loop:h});ae=s.jsxs(s.Fragment,{children:[s.jsxs(q,{title:g,darkMode:o,children:[s.jsx(ye,{label:"Max iterations",value:Fe(d.max_iterations)||10,min:1,max:100,onChange:h=>C({...d,max_iterations:h}),darkMode:o}),s.jsx(pe,{label:"Until",value:k(d.until),placeholder:"e.g. $.result.done == true",mono:!0,onChange:h=>C({...d,until:h}),darkMode:o})]}),_(!1,!1)]});break}default:ae=null}return s.jsxs("div",{className:"p-4",children:[xe,ct(),Rt(),!b&&Re(),ae]})},al=({issues:e,valid:t,validating:n,onSelectStep:r,darkMode:i})=>{const[a,l]=y.useState(!0),o=e.filter(p=>p.severity==="error"),u=e.filter(p=>p.severity==="warning");return s.jsxs("div",{className:`border-t flex flex-col ${a?"h-40":""} ${i?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[s.jsxs("div",{className:"flex items-center gap-3 px-4 py-2 shrink-0",children:[s.jsx("h3",{className:`text-sm font-semibold ${i?"text-gray-200":"text-gray-800"}`,children:"Problems"}),o.length>0&&s.jsxs("span",{className:`text-xs font-medium ${i?"text-red-400":"text-red-600"}`,children:[o.length," error",o.length!==1?"s":""]}),u.length>0&&s.jsxs("span",{className:`text-xs font-medium ${i?"text-amber-400":"text-amber-600"}`,children:[u.length," warning",u.length!==1?"s":""]}),t&&e.length===0&&s.jsxs("span",{className:`flex items-center gap-1 text-xs font-medium ${i?"text-green-400":"text-green-600"}`,children:[s.jsx(vt,{className:"w-4 h-4"}),"Valid"]}),n&&s.jsxs("span",{className:`flex items-center gap-1 text-xs ${i?"text-gray-400":"text-gray-500"}`,children:[s.jsx(bn,{className:"w-4 h-4 animate-spin"}),"Validating…"]}),s.jsx("button",{onClick:()=>l(!a),className:`ml-auto p-1 rounded transition-colors ${i?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:a?"Collapse":"Expand",children:a?s.jsx(Nr,{className:"w-4 h-4"}):s.jsx(vr,{className:"w-4 h-4"})})]}),a&&s.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-3",children:e.length===0?s.jsxs("div",{className:`flex items-center gap-2 text-sm ${i?"text-gray-400":"text-gray-500"}`,children:[s.jsx(vt,{className:`w-4 h-4 ${i?"text-green-400":"text-green-600"}`}),"No problems — pipeline is valid"]}):[...o,...u].map((p,c)=>s.jsxs("button",{disabled:!p.stepName,onClick:()=>p.stepName&&r(p.stepName),className:`w-full flex items-start gap-2 text-left text-sm py-1 rounded ${p.stepName?"cursor-pointer hover:underline":"cursor-default"} ${p.severity==="error"?i?"text-red-400":"text-red-600":i?"text-amber-400":"text-amber-600"}`,children:[p.severity==="error"?s.jsx(yn,{className:"w-4 h-4 mt-0.5 shrink-0"}):s.jsx(Sr,{className:"w-4 h-4 mt-0.5 shrink-0"}),p.stepName&&s.jsx("span",{className:`shrink-0 font-mono text-[10px] px-1.5 py-0.5 rounded ${i?"bg-gray-700 text-gray-300":"bg-gray-200 text-gray-600"}`,children:p.stepName}),s.jsx("span",{children:p.message})]},`${c}-${p.message}`))})]})},sl=({yaml:e,applyError:t,onApply:n,onClose:r,darkMode:i})=>{const[a,l]=y.useState(e);y.useEffect(()=>{l(e)},[e]);const o=async()=>{try{await navigator.clipboard.writeText(a),se.success("Copied to clipboard")}catch{se.error("Failed to copy")}};return s.jsxs("div",{className:"fixed inset-0 z-40",children:[s.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:r}),s.jsxs("div",{className:`absolute right-0 top-0 h-full w-[480px] max-w-full flex flex-col shadow-2xl ${i?"bg-gray-800 border-l border-gray-700":"bg-white border-l border-gray-200"}`,children:[s.jsxs("div",{className:`flex items-center justify-between px-4 py-3 border-b ${i?"border-gray-700":"border-gray-200"}`,children:[s.jsx("h2",{className:`text-sm font-semibold ${i?"text-white":"text-gray-900"}`,children:"YAML"}),s.jsx("button",{onClick:r,className:`p-1.5 rounded transition-colors ${i?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"Close",children:s.jsx(wt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx("textarea",{value:a,onChange:u=>l(u.target.value),spellCheck:!1,className:`w-full h-full p-4 font-mono text-xs resize-none focus:outline-none ${i?"bg-gray-900 text-gray-200":"bg-gray-50 text-gray-800"}`})}),t&&s.jsx("div",{className:`px-4 py-2 text-xs border-t ${i?"bg-red-900/50 text-red-300 border-red-800":"bg-red-50 text-red-600 border-red-200"}`,children:t}),s.jsxs("div",{className:`flex items-center gap-2 px-4 py-3 border-t ${i?"border-gray-700":"border-gray-200"}`,children:[s.jsx("button",{onClick:o,className:`px-3 py-1.5 text-xs font-medium rounded transition-colors ${i?"bg-gray-700 text-gray-200 hover:bg-gray-600":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:"Copy"}),s.jsx("button",{onClick:()=>n(a),className:`px-3 py-1.5 text-xs font-medium text-white rounded transition-colors ${i?"bg-blue-600 hover:bg-blue-700":"bg-blue-500 hover:bg-blue-600"}`,children:"Apply YAML"})]})]})]})},ol=({status:e,darkMode:t})=>{switch(e){case"success":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${t?"text-green-400":"text-green-600"}`,children:[s.jsx(vt,{className:"w-3.5 h-3.5"}),"Success"]});case"failed":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${t?"text-red-400":"text-red-600"}`,children:[s.jsx(yn,{className:"w-3.5 h-3.5"}),"Failed"]});case"running":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${t?"text-blue-400":"text-blue-600"}`,children:[s.jsx(bn,{className:"w-3.5 h-3.5 animate-spin"}),"Running"]});case"skipped":return s.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Skipped"});default:return s.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Pending"})}},ll=({open:e,pipelineName:t,running:n,result:r,error:i,inputSchema:a,inputSchemaSource:l,initialInput:o,onClose:u,onRun:p,darkMode:c})=>{const f=y.useMemo(()=>tt(a),[a]),[m,b]=y.useState({});if(y.useEffect(()=>{e&&b({...ui(f||void 0),...o})},[e,t,f,o]),!e)return null;const g=(()=>{switch(r?.status){case"success":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${c?"text-green-400":"text-green-600"}`,children:[s.jsx(vt,{className:"w-4 h-4"}),"Success"]});case"failed":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${c?"text-red-400":"text-red-600"}`,children:[s.jsx(yn,{className:"w-4 h-4"}),"Failed"]});case"partial":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${c?"text-amber-400":"text-amber-600"}`,children:[s.jsx(Sr,{className:"w-4 h-4"}),"Partial"]});case"running":return s.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-medium ${c?"text-blue-400":"text-blue-600"}`,children:[s.jsx(bn,{className:"w-4 h-4 animate-spin"}),"Running"]});default:return null}})();return s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:u}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"pipeline-run-title",className:`relative max-w-2xl w-full max-h-[85vh] flex flex-col rounded-xl shadow-2xl ${c?"bg-gray-800 border border-gray-700":"bg-white border border-gray-200"}`,children:[s.jsxs("div",{className:`flex items-center justify-between px-4 py-3 border-b shrink-0 ${c?"border-gray-700":"border-gray-200"}`,children:[s.jsxs("h2",{id:"pipeline-run-title",className:`text-sm font-semibold ${c?"text-white":"text-gray-900"}`,children:["Run pipeline"," ",s.jsx("span",{className:`font-mono text-xs ${c?"text-gray-400":"text-gray-500"}`,children:t})]}),s.jsx("button",{onClick:u,className:`p-1.5 rounded transition-colors ${c?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,title:"Close","aria-label":"Close pipeline run dialog",children:s.jsx(wt,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:`mb-2 text-xs font-medium ${c?"text-gray-300":"text-gray-600"}`,children:"Test input"}),l==="inferred"&&s.jsx("p",{className:`mb-2 text-xs ${c?"text-blue-300":"text-blue-700"}`,children:"Suggested from unconnected fields in the draft's live resource contracts. Declare a pipeline input schema to take full control."}),s.jsx(Ci,{schema:f,value:m,onChange:b,onSubmit:p,submitLabel:n?"Running…":"Run pipeline",disabled:n,darkMode:c}),l==="declared"&&s.jsx("p",{className:`mt-2 text-xs ${c?"text-gray-400":"text-gray-500"}`,children:"The live pipeline schema and defaults are prefilled. Switch Form, Dict, or Raw JSON mode to match the test case."})]}),i&&s.jsx("div",{className:`px-3 py-2 text-xs rounded-lg ${c?"bg-red-900/50 text-red-300":"bg-red-50 text-red-600"}`,children:i}),r&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[g,s.jsxs("span",{className:`text-xs ${c?"text-gray-400":"text-gray-500"}`,children:["Duration: ",r.durationMs," ms"]})]}),r.error&&s.jsx("div",{className:`px-3 py-2 text-xs rounded-lg ${c?"bg-red-900/50 text-red-300":"bg-red-50 text-red-600"}`,children:r.error}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:`block text-xs font-medium ${c?"text-gray-300":"text-gray-600"}`,children:"Output"}),s.jsx("pre",{className:`p-3 font-mono text-xs whitespace-pre-wrap break-all rounded-lg border overflow-auto max-h-64 ${c?"bg-gray-900 text-gray-200 border-gray-600":"bg-gray-50 text-gray-800 border-gray-300"}`,children:JSON.stringify(r.output,null,2)})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:`block text-xs font-medium ${c?"text-gray-300":"text-gray-600"}`,children:"Steps"}),s.jsxs("table",{className:`w-full text-xs border rounded-lg ${c?"border-gray-600":"border-gray-300"}`,children:[s.jsx("thead",{children:s.jsxs("tr",{className:`text-left ${c?"bg-gray-900 text-gray-400":"bg-gray-100 text-gray-500"}`,children:[s.jsx("th",{className:"px-3 py-2 font-medium",children:"Step"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Status"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Duration"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Error"})]})}),s.jsx("tbody",{children:Object.entries(r.steps).map(([j,O])=>s.jsxs("tr",{className:`border-t ${c?"border-gray-700 text-gray-300":"border-gray-200 text-gray-700"}`,children:[s.jsx("td",{className:"px-3 py-2 font-mono",children:j}),s.jsx("td",{className:"px-3 py-2",children:s.jsx(ol,{status:O.status,darkMode:c})}),s.jsx("td",{className:"px-3 py-2",children:O.durationMs!==void 0?`${O.durationMs} ms`:"—"}),s.jsx("td",{className:`px-3 py-2 ${c?"text-red-400":"text-red-600"}`,children:O.error??""})]},j))})]})]})]})]})]})]})},oe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},cl=(e,t,n)=>{const r=e.config;if(e.kind==="agent")return t[typeof r.agent=="string"?r.agent:""]?.input_schema??null;if(e.kind==="map"){const i=oe(r.map);return t[typeof i.agent=="string"?i.agent:""]?.input_schema??null}if(e.kind==="plugin"||e.kind==="endpoint"||e.kind==="ingestion"||e.kind==="sub_pipeline"){const i=typeof r[e.kind]=="string"?r[e.kind]:"";return n[`${e.kind}:${i}`]?.input_schema??null}return null},ul=e=>{const t=e.kind==="map"?oe(oe(e.config.map).input):oe(e.config.input);return oe(t.mappings??t)},Zr=e=>e.flatMap(t=>[t,...Zr(t.children)]),pl=(e,t)=>{const n=oe(t.components),r=oe(n.schemas);Object.keys(r).length>0&&(e.components={...oe(e.components),schemas:{...oe(oe(e.components).schemas),...r}});const i=oe(t.$defs);Object.keys(i).length>0&&(e.$defs={...oe(e.$defs),...i})},dl=(e,t,n)=>{const r=tt(e.meta.input_schema);if(r&&Object.keys(r.properties??{}).length>0)return{schema:r,source:"declared"};const i={title:"Suggested test input",description:"Derived from unbound fields in the live contracts of this draft.",type:"object",properties:{}},a=new Set;for(const l of Zr(e.steps)){const o=cl(l,t,n),u=o?tt(o):null;if(!u)continue;pl(i,u);const p=oe(u.properties),c=new Set(Array.isArray(u.required)?u.required:[]),f=ul(l);if(u.type&&u.type!=="object"&&Object.keys(p).length===0){const b=f[Ot];if(typeof b=="string"&&b.startsWith("$.input.")){const g=b.slice(8);i.properties[g]??=u,a.add(g)}continue}for(const[b,g]of Object.entries(p)){const j=f[b],O=typeof j=="string"&&j.startsWith("$.input.")?j.slice(8):j===void 0?b:"";O&&(i.properties[O]||(i.properties[O]=g),c.has(b)&&a.add(O))}}return Object.keys(i.properties).length===0?{schema:{},source:"unspecified"}:(a.size>0&&(i.required=Array.from(a)),{schema:i,source:"inferred"})},fl=350,yl=()=>{const{config:e,darkMode:t,builderPipelineToLoad:n,setBuilderPipelineToLoad:r}=pi(),[i,a]=y.useState(()=>Gt()),[l,o]=y.useState({type:"pipeline"}),[u,p]=y.useState([]),[c,f]=y.useState(!1),[m,b]=y.useState({agents:[],plugins:[],endpoints:[],ingestors:[],pipelines:[]}),[g,j]=y.useState(!0),[O,Y]=y.useState(null),[D,U]=y.useState(0),[Q,I]=y.useState({}),[v,T]=y.useState({}),[w,z]=y.useState({}),[re,Z]=y.useState([]),[de,Ie]=y.useState(!1),[je,Oe]=y.useState(!1),[Se,ie]=y.useState(!1),[_,Ge]=y.useState(null),[fe,he]=y.useState(!1),[xe,ct]=y.useState(!1),[Rt,Re]=y.useState(null),[ae,d]=y.useState(null),[C,h]=y.useState({}),[P,K]=y.useState(!1),Ae=y.useRef(null),Ce=y.useRef(0),R=y.useMemo(()=>e?.apiUrl?new di(e.apiUrl,e.apiKey||void 0):null,[e?.apiKey,e?.apiUrl]);y.useEffect(()=>{if(!R){j(!1);return}let x=!1;return(async()=>{j(!0);try{const S=await Promise.all([R.listAgents().then(N=>({label:"agents",value:N,error:null})).catch(N=>({label:"agents",value:[],error:N})),R.listPlugins().then(N=>({label:"plugins",value:N,error:null})).catch(N=>({label:"plugins",value:[],error:N})),R.listEndpoints().then(N=>({label:"endpoints",value:N,error:null})).catch(N=>({label:"endpoints",value:[],error:N})),R.listIngestors().then(N=>({label:"ingestors",value:N,error:null})).catch(N=>({label:"ingestors",value:[],error:N})),R.listPipelines().then(N=>({label:"pipelines",value:N,error:null})).catch(N=>({label:"pipelines",value:[],error:N}))]);if(x)return;const[A,E,B,le,Ut]=S,En=A.value,In=E.value,On=B.value,Rn=le.value,Bt=Ut.value,ci={agents:En.map(N=>({name:N.name,description:N.description})),plugins:In.map(N=>({name:N.name,description:N.description})),endpoints:On.map(N=>({name:N.name,description:N.description})),ingestors:Rn.map(N=>({name:N.name,description:N.description})),pipelines:Bt.map(N=>({name:N.name,description:N.description}))},Ln=await Promise.all(En.map(async N=>{try{return{key:`agent:${N.name}`,schema:await R.getSchemas(N.name),error:null}}catch{return{key:`agent:${N.name}`,schema:null,error:`Live agent schema for '${N.name}' is unavailable.`}}})),Fn=await Promise.all([...In.map(async N=>{const ce=`plugin:${N.name}`;try{return{key:ce,contract:await R.getOperationContract(`/api/v1/plugins/${encodeURIComponent(N.name)}/predict`),error:null}}catch{return{key:ce,contract:null,error:`Live plugin schema for '${N.name}' is unavailable.`}}}),...On.map(async N=>{const ce=`endpoint:${N.name}`;try{return{key:ce,contract:await R.getEndpointContract(N),error:null}}catch{return{key:ce,contract:null,error:`Live endpoint schema for '${N.name}' is unavailable.`}}}),...Rn.map(async N=>{const ce=`ingestion:${N.name}`;try{return{key:ce,contract:await R.getOperationContract(`/api/v1/ingestion/${encodeURIComponent(N.name)}/run`),error:null}}catch{return{key:ce,contract:null,error:`Live ingestor schema for '${N.name}' is unavailable.`}}}),...Bt.map(async N=>{const ce=`sub_pipeline:${N.name}`;try{const Dn=await R.getPipelineConfig(N.name);return{key:ce,contract:{input_schema:tt(Dn.input_schema),output_schema:tt(Dn.output_schema)},error:null}}catch{return{key:ce,contract:null,error:`Live sub-pipeline schema for '${N.name}' is unavailable.`}}})]);if(x)return;b(ci),I(Object.fromEntries(Ln.flatMap(N=>N.schema?[[N.key.slice(6),N.schema]]:[]))),T(Object.fromEntries(Fn.flatMap(N=>N.contract?[[N.key,N.contract]]:[]))),z(Object.fromEntries([...Ln,...Fn].flatMap(N=>N.error?[[N.key,N.error]]:[]))),Z(Bt.map(N=>({name:N.name,description:N.description})));const Pn=S.filter(N=>N.error).map(N=>N.label);Y(Pn.length?`Could not load live ${Pn.join(", ")}. Check authentication, rate limits, or connectivity, then retry.`:null)}catch(S){x||Y(S?.message||"Could not load the live Builder palette. Retry after checking connectivity.")}finally{x||j(!1)}})(),()=>{x=!0}},[R,D]),y.useEffect(()=>{if(!R)return;f(!0),Ae.current&&clearTimeout(Ae.current);const x=++Ce.current;return Ae.current=setTimeout(async()=>{try{const S=cr(i),A=await R.validatePipelineDraft({pipeline:yt(i)});if(x!==Ce.current)return;p(Oo(S,A.errors,A.warnings))}catch{if(x!==Ce.current)return;p(cr(i))}finally{x===Ce.current&&f(!1)}},fl),()=>{Ae.current&&clearTimeout(Ae.current)}},[i,R]);const V=y.useMemo(()=>{const x=Ro(u);let S=0,A=0;for(const E of u)E.severity==="error"?S+=1:A+=1;return{byStep:x,errors:S,warnings:A}},[u]),Lt=y.useMemo(()=>No(i),[i]),ut=y.useMemo(()=>dl(i,Q,v),[Q,i,v]),Le=y.useCallback(x=>{a(S=>{const A=x==="agent"?m.agents[0]?.name:x==="plugin"?m.plugins[0]?.name:x==="endpoint"?m.endpoints[0]?.name:x==="ingestion"?m.ingestors[0]?.name:x==="sub_pipeline"?m.pipelines.find(Ut=>Ut.name!==S.meta.name)?.name:void 0,E=["agent","plugin","endpoint","ingestion","sub_pipeline"].includes(x)?x:null,B=A&&E?or(S,E,A):Co(S,x),le=B.steps[B.steps.length-1];return le&&(o({type:"step",id:le.id,childPath:[]}),K(!0)),B})},[m]),be=y.useCallback((x,S)=>{a(A=>{const E=or(A,x,S),B=E.steps[E.steps.length-1];return B&&(o({type:"step",id:B.id,childPath:[]}),K(!0)),E})},[]),ei=y.useCallback(x=>{a(S=>{const A=wo(S,x),E=A.steps.find(le=>le.id===x),B=E?.children[E.children.length-1];return B&&(o({type:"step",id:x,childPath:[B.id]}),K(!0)),A})},[]),ti=y.useCallback((x,S)=>{o(x?{type:"step",id:x,childPath:S??[]}:{type:"pipeline"}),x&&K(!0)},[]),ni=y.useCallback(x=>{const S=i.steps.find(A=>A.name===x);if(S){o({type:"step",id:S.id,childPath:[]});return}for(const A of i.steps){const E=A.children.find(B=>B.name===x);if(E){o({type:"step",id:A.id,childPath:[E.id]});return}}},[i.steps]),ri=y.useCallback(async()=>{if(R){Ie(!0);try{const x=yt(i),S=await R.savePipeline(i.meta.name,{pipeline:x});if(S.valid)se.success(`Saved pipeline '${S.name}'`),Z(A=>A.some(B=>B.name===S.name)?A:[...A,{name:S.name}]);else{const A=S.errors.join(" · ")||"Pipeline validation failed";se.error(A)}}catch(x){let S=x?.message||"Failed to save pipeline";try{const A=JSON.parse(x?.body||"{}")?.detail;A?.message&&(S=A.message),Array.isArray(A?.errors)&&A.errors.length>0&&(S=`${A.message}: ${A.errors.join(" · ")}`)}catch{}se.error(S)}finally{Ie(!1)}}},[R,i]),ii=y.useCallback(async()=>{if(!R)return;const x=i.meta.name;if(window.confirm(`Delete pipeline '${x}'? This removes its YAML file.`)){Oe(!0);try{await R.deletePipeline(x),se.success(`Deleted pipeline '${x}'`),a(Gt()),o({type:"pipeline"}),h({}),Z(S=>S.filter(A=>A.name!==x))}catch(S){let A=S?.message||"Failed to delete pipeline";try{const E=JSON.parse(S?.body||"{}")?.detail;typeof E=="string"?A=E:E?.message&&(A=E.message)}catch{}se.error(A)}finally{Oe(!1)}}},[R,i.meta.name]),Ft=y.useCallback(async x=>{if(R)try{const S=await R.getPipelineConfig(x);a(Gr(S)),o({type:"pipeline"}),h({}),Re(null),d(null),se.success(`Loaded pipeline '${x}'`)}catch(S){se.error(S?.message||`Failed to load pipeline '${x}'`)}},[R]);y.useEffect(()=>{!n||!R||Ft(n).finally(()=>r(null))},[n,R,Ft,r]);const ai=y.useCallback(()=>{a(Gt()),o({type:"pipeline"}),h({}),Re(null),d(null)},[]),si=y.useCallback(async x=>{if(R){ct(!0),d(null),Re(null),h({});try{const S=await R.savePipeline(i.meta.name,{pipeline:yt(i)});if(!S.valid)throw new Error(S.errors.join(" · ")||"Pipeline validation failed");Z(B=>B.some(le=>le.name===S.name)?B:[...B,{name:S.name}]);const A=await R.runPipeline(i.meta.name,{input:x}),E={};for(const[B,le]of Object.entries(A.steps))E[B]={status:le.status,durationMs:le.duration_ms,error:le.error};h(E),Re({status:A.status,output:A.output,steps:E,durationMs:A.duration_ms,error:A.error}),A.status==="success"?se.success(`Pipeline run completed in ${A.duration_ms.toFixed(1)}ms`):se.error(A.error||`Pipeline run finished with status '${A.status}'`)}catch(S){let A=S?.message||"Failed to run pipeline";try{const E=JSON.parse(S?.body||"{}")?.detail;typeof E=="string"?A=E:E?.message?A=E.message:Array.isArray(E?.errors)&&E.errors.length>0&&(A=E.errors.join(" · "))}catch{}d(A),se.error(A)}finally{ct(!1)}}},[R,i]),oi=y.useCallback(x=>{try{const S=jo(x);a(S),o({type:"pipeline"}),Ge(null),se.success("YAML applied — canvas updated")}catch(S){Ge(S?.message||"Invalid YAML")}},[]),li=[{title:"Agents",items:m.agents,color:"blue",kind:"agent"},{title:"Plugins",items:m.plugins,color:"purple",kind:"plugin"},{title:"Endpoints",items:m.endpoints,color:"emerald",kind:"endpoint"},{title:"Ingestors",items:m.ingestors,color:"teal",kind:"ingestion"},{title:"Sub-pipelines",items:m.pipelines.filter(x=>x.name!==i.meta.name),color:"cyan",kind:"sub_pipeline"}],Pt=t?"bg-gray-800 text-white":"bg-white text-gray-900",Dt=t?"border-gray-700":"border-gray-200",pt=t?"text-gray-400":"text-gray-500";return s.jsxs("div",{className:`flex flex-col h-full ${t?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[s.jsxs("div",{className:`flex min-h-14 flex-wrap items-center gap-2 border-b px-3 py-2 sm:px-4 ${Dt} ${Pt} flex-shrink-0`,children:[s.jsx("input",{value:i.meta.name,onChange:x=>a(Jr(i,{...i.meta,name:x.target.value})),placeholder:"pipeline_name","aria-label":"Pipeline name",className:`min-w-0 flex-1 px-3 py-1.5 rounded-lg border text-sm font-medium sm:w-52 sm:flex-none focus:outline-none focus:ring-2 focus:ring-blue-500 ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,title:"Pipeline name"}),s.jsxs("button",{onClick:ai,className:`flex items-center px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${t?"hover:bg-gray-700 text-gray-200":"hover:bg-gray-100 text-gray-700"}`,title:"New pipeline",children:[s.jsx(Un,{className:"w-4 h-4 mr-1.5"}),"New"]}),s.jsxs("select",{defaultValue:"",onChange:x=>{x.target.value&&Le(x.target.value),x.target.value=""},className:`px-3 py-1.5 rounded-lg border text-sm focus:outline-none lg:hidden ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,"aria-label":"Quick add pipeline step",children:[s.jsx("option",{value:"",children:"Add step…"}),Bn.map(x=>s.jsx("option",{value:x.kind,children:x.label},x.kind))]}),s.jsxs("select",{value:"",onChange:x=>x.target.value&&Ft(x.target.value),className:`px-3 py-1.5 rounded-lg border text-sm focus:outline-none ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,"aria-label":"Load existing pipeline",title:"Load existing pipeline",children:[s.jsx("option",{value:"",disabled:!0,children:re.length>0?"Load…":"No saved pipelines"}),re.map(x=>s.jsx("option",{value:x.name,children:x.name},x.name))]}),s.jsx("div",{className:"hidden flex-1 sm:block"}),s.jsx("div",{className:`flex items-center text-xs font-medium px-3 py-1.5 rounded-full ${V.errors>0?t?"bg-red-900 text-red-200":"bg-red-100 text-red-700":V.warnings>0?t?"bg-amber-900 text-amber-200":"bg-amber-100 text-amber-700":t?"bg-green-900 text-green-200":"bg-green-100 text-green-700"}`,children:c?s.jsx("span",{children:"Validating…"}):V.errors>0?s.jsxs("span",{children:[V.errors," error",V.errors!==1?"s":""]}):V.warnings>0?s.jsxs("span",{children:[V.warnings," warning",V.warnings!==1?"s":""]}):s.jsxs("span",{className:"flex items-center",children:[s.jsx(ki,{className:"w-4 h-4 mr-1"})," Valid"]})}),s.jsxs("button",{onClick:()=>ie(!0),className:`flex items-center px-3 py-1.5 rounded-lg text-sm font-medium ${t?"bg-gray-700 text-gray-200 hover:bg-gray-600":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,title:"YAML view",children:[s.jsx(Ei,{className:"w-4 h-4 mr-1.5"}),"YAML"]}),s.jsxs("button",{onClick:ri,disabled:de||xe||V.errors>0,className:`flex items-center px-4 py-1.5 rounded-lg text-sm font-medium text-white transition-colors ${de||xe||V.errors>0?"bg-gray-400 cursor-not-allowed":"bg-blue-600 hover:bg-blue-700"}`,title:V.errors>0?"Fix validation errors before saving":"Save pipeline",children:[s.jsx(wi,{className:"w-4 h-4 mr-1.5"}),de?"Saving…":"Save"]}),s.jsxs("button",{onClick:()=>he(!0),disabled:de||xe||V.errors>0,className:`flex items-center px-4 py-1.5 rounded-lg text-sm font-medium text-white transition-colors ${de||xe||V.errors>0?"bg-gray-400 cursor-not-allowed":"bg-green-600 hover:bg-green-700"}`,title:V.errors>0?"Fix validation errors before running":"Save this draft, then run it with test input",children:[s.jsx(Oi,{className:"w-4 h-4 mr-1.5"}),xe?"Running…":"Save & Run"]}),s.jsxs("button",{onClick:ii,disabled:je,className:`flex items-center px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${t?"text-red-300 hover:bg-red-900/40":"text-red-600 hover:bg-red-50"}`,title:"Delete pipeline",children:[s.jsx(fi,{className:"w-4 h-4 mr-1.5"}),je?"…":"Delete"]}),s.jsx("button",{type:"button",onClick:()=>K(x=>!x),className:`rounded-lg px-3 py-1.5 text-sm font-medium xl:hidden ${t?"bg-gray-700 text-gray-200":"bg-gray-100 text-gray-700"}`,"aria-expanded":P,children:"Inspector"})]}),(g||O)&&s.jsxs("div",{role:"status",className:`flex flex-wrap items-center justify-between gap-2 border-b px-3 py-2 text-xs sm:px-4 ${O?t?"border-amber-900 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800":t?"border-gray-700 bg-gray-800 text-gray-300":"border-gray-200 bg-gray-50 text-gray-600"}`,children:[s.jsx("span",{children:O||"Refreshing live Builder resources and contracts…"}),O&&s.jsx("button",{type:"button",onClick:()=>U(x=>x+1),className:`rounded-md border px-2 py-1 font-medium ${t?"border-amber-700 hover:bg-amber-900/60":"border-amber-300 hover:bg-amber-100"}`,children:"Retry live resources"})]}),s.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden",children:[s.jsxs("div",{className:`hidden w-56 flex-shrink-0 overflow-y-auto border-r lg:block ${Dt} ${Pt} p-3`,children:[s.jsx("h3",{className:`text-xs font-semibold uppercase tracking-wider mb-2 ${pt}`,children:"Step types"}),s.jsx("div",{className:"space-y-1.5 mb-4",children:Bn.map(x=>{const S=qe[x.kind];return s.jsx("button",{onClick:()=>Le(x.kind),draggable:!0,onDragStart:A=>{A.dataTransfer.effectAllowed="copy",A.dataTransfer.setData("application/x-agentomatic-step-kind",x.kind)},className:`w-full text-left px-3 py-2 rounded-lg border transition-colors ${t?"hover:bg-gray-700 border-gray-700":"hover:bg-gray-50 border-gray-200"}`,title:x.description,children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("span",{className:`text-[10px] font-semibold px-1.5 py-0.5 rounded ${S.badge}`,children:S.label}),s.jsx(Un,{className:`w-3.5 h-3.5 ml-auto ${pt}`})]})},x.kind)})}),li.map(x=>s.jsxs("div",{className:"mb-3",children:[s.jsxs("h3",{className:`text-xs font-semibold uppercase tracking-wider mb-1.5 ${pt}`,children:[x.title," (",x.items.length,")"]}),x.items.length===0?s.jsx("p",{className:`text-xs italic ${pt}`,children:"none"}):s.jsx("div",{className:"flex flex-wrap gap-1",children:x.items.map(S=>s.jsxs("button",{type:"button",draggable:!0,onClick:()=>be(x.kind,S.name),onDragStart:A=>{A.dataTransfer.effectAllowed="copy",A.dataTransfer.setData("application/x-agentomatic-resource",JSON.stringify({kind:x.kind,name:S.name}))},title:`Add configured ${x.kind.replace("_"," ")} step for ${S.name}`,className:`rounded px-1.5 py-0.5 text-left text-xs transition-colors ${t?"bg-gray-700 text-gray-300 hover:bg-gray-600 hover:text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200 hover:text-gray-900"}`,children:["+ ",S.name]},S.name))})]},x.title))]}),s.jsx("div",{className:"flex-1 min-w-0 overflow-auto p-3 sm:p-4",children:s.jsx(Yo,{draft:i,selectedId:l.type==="step"?l.id:null,selectedChildPath:l.type==="step"?l.childPath:null,runStatuses:C,issueCounts:V.byStep,onSelect:ti,onReorder:(x,S,A)=>a(E=>lr(E,x,S,A)),onMove:(x,S)=>{a(A=>{const E=A.steps.findIndex(B=>B.id===x);return E===-1?A:lr(A,E,E+S)})},onAddChild:ei,onRemoveChild:(x,S)=>a(A=>_o(A,x,S)),onDelete:x=>a(S=>$o(S,x)),onAddFromPalette:Le,onAddResource:be,darkMode:t})}),s.jsx("div",{className:`${P?"absolute inset-3 z-40 flex shadow-2xl":"hidden"} w-auto overflow-y-auto rounded-2xl border xl:static xl:flex xl:w-96 xl:flex-shrink-0 xl:rounded-none xl:border-y-0 xl:border-r-0 xl:border-l ${Dt} ${Pt}`,children:s.jsx(il,{draft:i,selection:l,resources:m,agentSchemas:Q,resourceSchemas:v,resourceContractErrors:w,onChange:a,darkMode:t})})]}),s.jsx("div",{className:"flex-shrink-0 border-t border-gray-200 dark:border-gray-700",children:s.jsx(al,{issues:u,valid:V.errors===0,validating:c,onSelectStep:ni,darkMode:t})}),Se&&s.jsx(sl,{yaml:Lt,applyError:_,onApply:oi,onClose:()=>ie(!1),darkMode:t}),s.jsx(ll,{open:fe,pipelineName:i.meta.name,running:xe,result:Rt,error:ae,inputSchema:ut.schema,inputSchemaSource:ut.source,initialInput:i.meta.defaults,onClose:()=>he(!1),onRun:si,darkMode:t})]})};export{yl as BuilderView}; diff --git a/src/agentomatic/studio/static/assets/ChatView-C7_FNxo9.js b/src/agentomatic/studio/static/assets/ChatView-Bc4TZ9mm.js similarity index 99% rename from src/agentomatic/studio/static/assets/ChatView-C7_FNxo9.js rename to src/agentomatic/studio/static/assets/ChatView-Bc4TZ9mm.js index 5361c217..311814f1 100644 --- a/src/agentomatic/studio/static/assets/ChatView-C7_FNxo9.js +++ b/src/agentomatic/studio/static/assets/ChatView-Bc4TZ9mm.js @@ -1,4 +1,4 @@ -import{u as qe,i as dr,d as mr,b as Ge,c as gr,j as d,V as Ve,f as xr,e as yr}from"./index-FSSL6O5F.js";import{r as M,g as Re,R as Ne}from"./react-vendor-BHJ3EV8m.js";import{S as br}from"./SchemaForm-DyHc2s7z.js";import{O as _n}from"./OutputSchemaSummary-C65WaRqI.js";import{d as En,s as wr,b as kr}from"./syntax-vendor-ru7AzRyY.js";import{F as Sr}from"./ClipboardDocumentIcon-Cnz7XqGa.js";function vr({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M11.35 3.836c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75 2.25 2.25 0 0 0-.1-.664m-5.8 0A2.251 2.251 0 0 1 13.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m8.9-4.414c.376.023.75.05 1.124.08 1.131.094 1.976 1.057 1.976 2.192V16.5A2.25 2.25 0 0 1 18 18.75h-2.25m-7.5-10.5H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V18.75m-7.5-10.5h6.375c.621 0 1.125.504 1.125 1.125v9.375m-8.25-3 1.5 1.5 3-3.75"}))}const Cr=M.forwardRef(vr);function Er({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.98 8.223A10.477 10.477 0 0 0 1.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.451 10.451 0 0 1 12 4.5c4.756 0 8.773 3.162 10.065 7.498a10.522 10.522 0 0 1-4.293 5.774M6.228 6.228 3 3m3.228 3.228 3.65 3.65m7.894 7.894L21 21m-3.228-3.228-3.65-3.65m0 0a3 3 0 1 0-4.243-4.243m4.242 4.242L9.88 9.88"}))}const jr=M.forwardRef(Er);function Nr({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"}),M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const Ar=M.forwardRef(Nr);function Fr({title:e,titleId:n,...t},r){return M.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:r,"aria-labelledby":n},t),e?M.createElement("title",{id:n},e):null,M.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 12 3.269 3.125A59.769 59.769 0 0 1 21.485 12 59.768 59.768 0 0 1 3.27 20.875L5.999 12Zm0 0h7.5"}))}const Tr=M.forwardRef(Fr),$n=["http","https","mailto","tel"];function Ir(e){const n=(e||"").trim(),t=n.charAt(0);if(t==="#"||t==="/")return n;const r=n.indexOf(":");if(r===-1)return n;let i=-1;for(;++i<$n.length;){const l=$n[i];if(r===l.length&&n.slice(0,l.length).toLowerCase()===l)return n}return i=n.indexOf("?"),i!==-1&&r>i||(i=n.indexOf("#"),i!==-1&&r>i)?n:"javascript:void(0)"}var Je,Mn;function Lr(){return Mn||(Mn=1,Je=function(n){return n!=null&&n.constructor!=null&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}),Je}var Pr=Lr();const Et=Re(Pr);function De(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Hn(e.position):"start"in e||"end"in e?Hn(e):"line"in e||"column"in e?gn(e):""}function gn(e){return Un(e&&e.line)+":"+Un(e&&e.column)}function Hn(e){return gn(e&&e.start)+"-"+gn(e&&e.end)}function Un(e){return e&&typeof e=="number"?e:1}class he extends Error{constructor(n,t,r){const i=[null,null];let l={start:{line:null,column:null},end:{line:null,column:null}};if(super(),typeof t=="string"&&(r=t,t=void 0),typeof r=="string"){const a=r.indexOf(":");a===-1?i[1]=r:(i[0]=r.slice(0,a),i[1]=r.slice(a+1))}t&&("type"in t||"position"in t?t.position&&(l=t.position):"start"in t||"end"in t?l=t:("line"in t||"column"in t)&&(l.start=t)),this.name=De(t)||"1:1",this.message=typeof n=="object"?n.message:n,this.stack="",typeof n=="object"&&n.stack&&(this.stack=n.stack),this.reason=this.message,this.fatal,this.line=l.start.line,this.column=l.start.column,this.position=l,this.source=i[0],this.ruleId=i[1],this.file,this.actual,this.expected,this.url,this.note}}he.prototype.file="";he.prototype.name="";he.prototype.reason="";he.prototype.message="";he.prototype.stack="";he.prototype.fatal=null;he.prototype.column=null;he.prototype.line=null;he.prototype.source=null;he.prototype.ruleId=null;he.prototype.position=null;const ge={basename:Or,dirname:Dr,extname:zr,join:Rr,sep:"/"};function Or(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Be(e);let t=0,r=-1,i=e.length,l;if(n===void 0||n.length===0||n.length>e.length){for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else r<0&&(l=!0,r=i+1);return r<0?"":e.slice(t,r)}if(n===e)return"";let a=-1,o=n.length-1;for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else a<0&&(l=!0,a=i+1),o>-1&&(e.charCodeAt(i)===n.charCodeAt(o--)?o<0&&(r=i):(o=-1,r=a));return t===r?r=a:r<0&&(r=e.length),e.slice(t,r)}function Dr(e){if(Be(e),e.length===0)return".";let n=-1,t=e.length,r;for(;--t;)if(e.charCodeAt(t)===47){if(r){n=t;break}}else r||(r=!0);return n<0?e.charCodeAt(0)===47?"/":".":n===1&&e.charCodeAt(0)===47?"//":e.slice(0,n)}function zr(e){Be(e);let n=e.length,t=-1,r=0,i=-1,l=0,a;for(;n--;){const o=e.charCodeAt(n);if(o===47){if(a){r=n+1;break}continue}t<0&&(a=!0,t=n+1),o===46?i<0?i=n:l!==1&&(l=1):i>-1&&(l=-1)}return i<0||t<0||l===0||l===1&&i===t-1&&i===r+1?"":e.slice(i,t)}function Rr(...e){let n=-1,t;for(;++n0&&e.charCodeAt(e.length-1)===47&&(t+="/"),n?"/"+t:t}function _r(e,n){let t="",r=0,i=-1,l=0,a=-1,o,c;for(;++a<=e.length;){if(a2){if(c=t.lastIndexOf("/"),c!==t.length-1){c<0?(t="",r=0):(t=t.slice(0,c),r=t.length-1-t.lastIndexOf("/")),i=a,l=0;continue}}else if(t.length>0){t="",r=0,i=a,l=0;continue}}n&&(t=t.length>0?t+"/..":"..",r=2)}else t.length>0?t+="/"+e.slice(i+1,a):t=e.slice(i+1,a),r=a-i-1;i=a,l=0}else o===46&&l>-1?l++:l=-1}return t}function Be(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const $r={cwd:Mr};function Mr(){return"/"}function xn(e){return e!==null&&typeof e=="object"&&e.href&&e.origin}function Hr(e){if(typeof e=="string")e=new URL(e);else if(!xn(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return Ur(e)}function Ur(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const n=e.pathname;let t=-1;for(;++t"u"||e.call(s,g)},a=function(s,u){t&&u.name==="__proto__"?t(s,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):s[u.name]=u.newValue},o=function(s,u){if(u==="__proto__")if(e.call(s,u)){if(r)return r(s,u).value}else return;return s[u]};return tn=function c(){var s,u,h,g,f,j,b=arguments[0],x=1,k=arguments.length,S=!1;for(typeof b=="boolean"&&(S=b,b=arguments[1]||{},x=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});xa.length;let c;o&&a.push(i);try{c=e.apply(this,a)}catch(s){const u=s;if(o&&t)throw u;return i(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(l,i):c instanceof Error?i(c):l(c))}function i(a,...o){t||(t=!0,n(a,...o))}function l(a){i(null,a)}}const Yr=At().freeze(),Nt={}.hasOwnProperty;function At(){const e=Qr(),n=[];let t={},r,i=-1;return l.data=a,l.Parser=void 0,l.Compiler=void 0,l.freeze=o,l.attachers=n,l.use=c,l.parse=s,l.stringify=u,l.run=h,l.runSync=g,l.process=f,l.processSync=j,l;function l(){const b=At();let x=-1;for(;++x{if(y||!L||!B)$(y);else{const H=l.stringify(L,B);H==null||(Jr(H)?B.value=H:B.result=H),$(y,B)}});function $(y,L){y||!L?C(y):S?S(L):x(null,L)}}}function j(b){let x;l.freeze(),rn("processSync",l.Parser),ln("processSync",l.Compiler);const k=Oe(b);return l.process(k,S),Kn("processSync","process",x),k;function S(C){x=!0,Vn(C)}}}function Xn(e,n){return typeof e=="function"&&e.prototype&&(Kr(e.prototype)||n in e.prototype)}function Kr(e){let n;for(n in e)if(Nt.call(e,n))return!0;return!1}function rn(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Parser`")}function ln(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Compiler`")}function an(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Yn(e){if(!yn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Kn(e,n,t){if(!t)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Oe(e){return Gr(e)?e:new jt(e)}function Gr(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Jr(e){return typeof e=="string"||Et(e)}const Zr={};function ei(e,n){const t=Zr,r=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return Ft(e,r,i)}function Ft(e,n,t){if(ni(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Gn(e.children,n,t)}return Array.isArray(e)?Gn(e,n,t):""}function Gn(e,n,t){const r=[];let i=-1;for(;++ii?0:i+n:n=n>i?i:n,t=t>0?t:0,r.length<1e4)a=Array.from(r),a.unshift(n,t),e.splice(...a);else for(t&&e.splice(n,t);l0?(ye(e,e.length,0,n),e):n}const Jn={}.hasOwnProperty;function ti(e){const n={};let t=-1;for(;++ta))return;const L=n.events.length;let B=L,H,K;for(;B--;)if(n.events[B][0]==="exit"&&n.events[B][1].type==="chunkFlow"){if(H){K=n.events[B][1].end;break}H=!0}for(k(r),y=L;yC;){const $=t[F];n.containerState=$[1],$[0].exit.call(n,e)}t.length=C}function S(){i.write([null]),l=void 0,i=void 0,n.containerState._closeFlow=void 0}}function mi(e,n,t){return X(e,e.attempt(this.parser.constructs.document,n,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function et(e){if(e===null||re(e)||ci(e))return 1;if(ui(e))return 2}function jn(e,n,t){const r=[];let i=-1;for(;++i1&&e[t][1].end.offset-e[t][1].start.offset>1?2:1;const h=Object.assign({},e[r][1].end),g=Object.assign({},e[t][1].start);nt(h,-c),nt(g,c),a={type:c>1?"strongSequence":"emphasisSequence",start:h,end:Object.assign({},e[r][1].end)},o={type:c>1?"strongSequence":"emphasisSequence",start:Object.assign({},e[t][1].start),end:g},l={type:c>1?"strongText":"emphasisText",start:Object.assign({},e[r][1].end),end:Object.assign({},e[t][1].start)},i={type:c>1?"strong":"emphasis",start:Object.assign({},a.start),end:Object.assign({},o.end)},e[r][1].end=Object.assign({},a.start),e[t][1].start=Object.assign({},o.end),s=[],e[r][1].end.offset-e[r][1].start.offset&&(s=pe(s,[["enter",e[r][1],n],["exit",e[r][1],n]])),s=pe(s,[["enter",i,n],["enter",a,n],["exit",a,n],["enter",l,n]]),s=pe(s,jn(n.parser.constructs.insideSpan.null,e.slice(r+1,t),n)),s=pe(s,[["exit",l,n],["enter",o,n],["exit",o,n],["exit",i,n]]),e[t][1].end.offset-e[t][1].start.offset?(u=2,s=pe(s,[["enter",e[t][1],n],["exit",e[t][1],n]])):u=0,ye(e,r-1,t-r+3,s),t=r+s.length-u-2;break}}for(t=-1;++t0&&U(y)?X(e,S,"linePrefix",l+1)(y):S(y)}function S(y){return y===null||D(y)?e.check(tt,b,F)(y):(e.enter("codeFlowValue"),C(y))}function C(y){return y===null||D(y)?(e.exit("codeFlowValue"),S(y)):(e.consume(y),C)}function F(y){return e.exit("codeFenced"),n(y)}function $(y,L,B){let H=0;return K;function K(P){return y.enter("lineEnding"),y.consume(P),y.exit("lineEnding"),T}function T(P){return y.enter("codeFencedFence"),U(P)?X(y,A,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):A(P)}function A(P){return P===o?(y.enter("codeFencedFenceSequence"),N(P)):B(P)}function N(P){return P===o?(H++,y.consume(P),N):H>=a?(y.exit("codeFencedFenceSequence"),U(P)?X(y,I,"whitespace")(P):I(P)):B(P)}function I(P){return P===null||D(P)?(y.exit("codeFencedFence"),L(P)):B(P)}}}function Ni(e,n,t){const r=this;return i;function i(a){return a===null?t(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}const on={name:"codeIndented",tokenize:Fi},Ai={tokenize:Ti,partial:!0};function Fi(e,n,t){const r=this;return i;function i(s){return e.enter("codeIndented"),X(e,l,"linePrefix",5)(s)}function l(s){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?a(s):t(s)}function a(s){return s===null?c(s):D(s)?e.attempt(Ai,a,c)(s):(e.enter("codeFlowValue"),o(s))}function o(s){return s===null||D(s)?(e.exit("codeFlowValue"),a(s)):(e.consume(s),o)}function c(s){return e.exit("codeIndented"),n(s)}}function Ti(e,n,t){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?t(a):D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):X(e,l,"linePrefix",5)(a)}function l(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?n(a):D(a)?i(a):t(a)}}const Ii={name:"codeText",tokenize:Oi,resolve:Li,previous:Pi};function Li(e){let n=e.length-4,t=3,r,i;if((e[t][1].type==="lineEnding"||e[t][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(r=t;++r=4?n(a):e.interrupt(r.parser.constructs.flow,t,n)(a)}}function Ot(e,n,t,r,i,l,a,o,c){const s=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(k){return k===60?(e.enter(r),e.enter(i),e.enter(l),e.consume(k),e.exit(l),g):k===null||k===32||k===41||bn(k)?t(k):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),b(k))}function g(k){return k===62?(e.enter(l),e.consume(k),e.exit(l),e.exit(i),e.exit(r),n):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(k))}function f(k){return k===62?(e.exit("chunkString"),e.exit(o),g(k)):k===null||k===60||D(k)?t(k):(e.consume(k),k===92?j:f)}function j(k){return k===60||k===62||k===92?(e.consume(k),f):f(k)}function b(k){return!u&&(k===null||k===41||re(k))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),n(k)):u999||f===null||f===91||f===93&&!c||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?t(f):f===93?(e.exit(l),e.enter(i),e.consume(f),e.exit(i),e.exit(r),n):D(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||D(f)||o++>999?(e.exit("chunkString"),u(f)):(e.consume(f),c||(c=!U(f)),f===92?g:h)}function g(f){return f===91||f===92||f===93?(e.consume(f),o++,h):h(f)}}function zt(e,n,t,r,i,l){let a;return o;function o(g){return g===34||g===39||g===40?(e.enter(r),e.enter(i),e.consume(g),e.exit(i),a=g===40?41:g,c):t(g)}function c(g){return g===a?(e.enter(i),e.consume(g),e.exit(i),e.exit(r),n):(e.enter(l),s(g))}function s(g){return g===a?(e.exit(l),c(a)):g===null?t(g):D(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),X(e,s,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(g))}function u(g){return g===a||g===null||D(g)?(e.exit("chunkString"),s(g)):(e.consume(g),g===92?h:u)}function h(g){return g===a||g===92?(e.consume(g),u):u(g)}}function ze(e,n){let t;return r;function r(i){return D(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t=!0,r):U(i)?X(e,r,t?"linePrefix":"lineSuffix")(i):n(i)}}function Ae(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Mi={name:"definition",tokenize:Ui},Hi={tokenize:qi,partial:!0};function Ui(e,n,t){const r=this;let i;return l;function l(f){return e.enter("definition"),a(f)}function a(f){return Dt.call(r,e,o,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return i=Ae(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),c):t(f)}function c(f){return re(f)?ze(e,s)(f):s(f)}function s(f){return Ot(e,u,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return e.attempt(Hi,h,h)(f)}function h(f){return U(f)?X(e,g,"whitespace")(f):g(f)}function g(f){return f===null||D(f)?(e.exit("definition"),r.parser.defined.push(i),n(f)):t(f)}}function qi(e,n,t){return r;function r(o){return re(o)?ze(e,i)(o):t(o)}function i(o){return zt(e,l,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function l(o){return U(o)?X(e,a,"whitespace")(o):a(o)}function a(o){return o===null||D(o)?n(o):t(o)}}const Vi={name:"hardBreakEscape",tokenize:Wi};function Wi(e,n,t){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),i}function i(l){return D(l)?(e.exit("hardBreakEscape"),n(l)):t(l)}}const Qi={name:"headingAtx",tokenize:Yi,resolve:Xi};function Xi(e,n){let t=e.length-2,r=3,i,l;return e[r][1].type==="whitespace"&&(r+=2),t-2>r&&e[t][1].type==="whitespace"&&(t-=2),e[t][1].type==="atxHeadingSequence"&&(r===t-1||t-4>r&&e[t-2][1].type==="whitespace")&&(t-=r+1===t?2:4),t>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[t][1].end},l={type:"chunkText",start:e[r][1].start,end:e[t][1].end,contentType:"text"},ye(e,r,t-r+1,[["enter",i,n],["enter",l,n],["exit",l,n],["exit",i,n]])),e}function Yi(e,n,t){let r=0;return i;function i(u){return e.enter("atxHeading"),l(u)}function l(u){return e.enter("atxHeadingSequence"),a(u)}function a(u){return u===35&&r++<6?(e.consume(u),a):u===null||re(u)?(e.exit("atxHeadingSequence"),o(u)):t(u)}function o(u){return u===35?(e.enter("atxHeadingSequence"),c(u)):u===null||D(u)?(e.exit("atxHeading"),n(u)):U(u)?X(e,o,"whitespace")(u):(e.enter("atxHeadingText"),s(u))}function c(u){return u===35?(e.consume(u),c):(e.exit("atxHeadingSequence"),o(u))}function s(u){return u===null||u===35||re(u)?(e.exit("atxHeadingText"),o(u)):(e.consume(u),s)}}const Ki=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],it=["pre","script","style","textarea"],Gi={name:"htmlFlow",tokenize:nl,resolveTo:el,concrete:!0},Ji={tokenize:rl,partial:!0},Zi={tokenize:tl,partial:!0};function el(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function nl(e,n,t){const r=this;let i,l,a,o,c;return s;function s(p){return u(p)}function u(p){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(p),h}function h(p){return p===33?(e.consume(p),g):p===47?(e.consume(p),l=!0,b):p===63?(e.consume(p),i=3,r.interrupt?n:m):xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function g(p){return p===45?(e.consume(p),i=2,f):p===91?(e.consume(p),i=5,o=0,j):xe(p)?(e.consume(p),i=4,r.interrupt?n:m):t(p)}function f(p){return p===45?(e.consume(p),r.interrupt?n:m):t(p)}function j(p){const _="CDATA[";return p===_.charCodeAt(o++)?(e.consume(p),o===_.length?r.interrupt?n:A:j):t(p)}function b(p){return xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function x(p){if(p===null||p===47||p===62||re(p)){const _=p===47,se=a.toLowerCase();return!_&&!l&&it.includes(se)?(i=1,r.interrupt?n(p):A(p)):Ki.includes(a.toLowerCase())?(i=6,_?(e.consume(p),k):r.interrupt?n(p):A(p)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?t(p):l?S(p):C(p))}return p===45||oe(p)?(e.consume(p),a+=String.fromCharCode(p),x):t(p)}function k(p){return p===62?(e.consume(p),r.interrupt?n:A):t(p)}function S(p){return U(p)?(e.consume(p),S):K(p)}function C(p){return p===47?(e.consume(p),K):p===58||p===95||xe(p)?(e.consume(p),F):U(p)?(e.consume(p),C):K(p)}function F(p){return p===45||p===46||p===58||p===95||oe(p)?(e.consume(p),F):$(p)}function $(p){return p===61?(e.consume(p),y):U(p)?(e.consume(p),$):C(p)}function y(p){return p===null||p===60||p===61||p===62||p===96?t(p):p===34||p===39?(e.consume(p),c=p,L):U(p)?(e.consume(p),y):B(p)}function L(p){return p===c?(e.consume(p),c=null,H):p===null||D(p)?t(p):(e.consume(p),L)}function B(p){return p===null||p===34||p===39||p===47||p===60||p===61||p===62||p===96||re(p)?$(p):(e.consume(p),B)}function H(p){return p===47||p===62||U(p)?C(p):t(p)}function K(p){return p===62?(e.consume(p),T):t(p)}function T(p){return p===null||D(p)?A(p):U(p)?(e.consume(p),T):t(p)}function A(p){return p===45&&i===2?(e.consume(p),J):p===60&&i===1?(e.consume(p),Z):p===62&&i===4?(e.consume(p),ie):p===63&&i===3?(e.consume(p),m):p===93&&i===5?(e.consume(p),de):D(p)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Ji,le,N)(p)):p===null||D(p)?(e.exit("htmlFlowData"),N(p)):(e.consume(p),A)}function N(p){return e.check(Zi,I,le)(p)}function I(p){return e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),P}function P(p){return p===null||D(p)?N(p):(e.enter("htmlFlowData"),A(p))}function J(p){return p===45?(e.consume(p),m):A(p)}function Z(p){return p===47?(e.consume(p),a="",ne):A(p)}function ne(p){if(p===62){const _=a.toLowerCase();return it.includes(_)?(e.consume(p),ie):A(p)}return xe(p)&&a.length<8?(e.consume(p),a+=String.fromCharCode(p),ne):A(p)}function de(p){return p===93?(e.consume(p),m):A(p)}function m(p){return p===62?(e.consume(p),ie):p===45&&i===2?(e.consume(p),m):A(p)}function ie(p){return p===null||D(p)?(e.exit("htmlFlowData"),le(p)):(e.consume(p),ie)}function le(p){return e.exit("htmlFlow"),n(p)}}function tl(e,n,t){const r=this;return i;function i(a){return D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l):t(a)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}function rl(e,n,t){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Qe,n,t)}}const il={name:"htmlText",tokenize:ll};function ll(e,n,t){const r=this;let i,l,a;return o;function o(m){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(m),c}function c(m){return m===33?(e.consume(m),s):m===47?(e.consume(m),$):m===63?(e.consume(m),C):xe(m)?(e.consume(m),B):t(m)}function s(m){return m===45?(e.consume(m),u):m===91?(e.consume(m),l=0,j):xe(m)?(e.consume(m),S):t(m)}function u(m){return m===45?(e.consume(m),f):t(m)}function h(m){return m===null?t(m):m===45?(e.consume(m),g):D(m)?(a=h,Z(m)):(e.consume(m),h)}function g(m){return m===45?(e.consume(m),f):h(m)}function f(m){return m===62?J(m):m===45?g(m):h(m)}function j(m){const ie="CDATA[";return m===ie.charCodeAt(l++)?(e.consume(m),l===ie.length?b:j):t(m)}function b(m){return m===null?t(m):m===93?(e.consume(m),x):D(m)?(a=b,Z(m)):(e.consume(m),b)}function x(m){return m===93?(e.consume(m),k):b(m)}function k(m){return m===62?J(m):m===93?(e.consume(m),k):b(m)}function S(m){return m===null||m===62?J(m):D(m)?(a=S,Z(m)):(e.consume(m),S)}function C(m){return m===null?t(m):m===63?(e.consume(m),F):D(m)?(a=C,Z(m)):(e.consume(m),C)}function F(m){return m===62?J(m):C(m)}function $(m){return xe(m)?(e.consume(m),y):t(m)}function y(m){return m===45||oe(m)?(e.consume(m),y):L(m)}function L(m){return D(m)?(a=L,Z(m)):U(m)?(e.consume(m),L):J(m)}function B(m){return m===45||oe(m)?(e.consume(m),B):m===47||m===62||re(m)?H(m):t(m)}function H(m){return m===47?(e.consume(m),J):m===58||m===95||xe(m)?(e.consume(m),K):D(m)?(a=H,Z(m)):U(m)?(e.consume(m),H):J(m)}function K(m){return m===45||m===46||m===58||m===95||oe(m)?(e.consume(m),K):T(m)}function T(m){return m===61?(e.consume(m),A):D(m)?(a=T,Z(m)):U(m)?(e.consume(m),T):H(m)}function A(m){return m===null||m===60||m===61||m===62||m===96?t(m):m===34||m===39?(e.consume(m),i=m,N):D(m)?(a=A,Z(m)):U(m)?(e.consume(m),A):(e.consume(m),I)}function N(m){return m===i?(e.consume(m),i=void 0,P):m===null?t(m):D(m)?(a=N,Z(m)):(e.consume(m),N)}function I(m){return m===null||m===34||m===39||m===60||m===61||m===96?t(m):m===47||m===62||re(m)?H(m):(e.consume(m),I)}function P(m){return m===47||m===62||re(m)?H(m):t(m)}function J(m){return m===62?(e.consume(m),e.exit("htmlTextData"),e.exit("htmlText"),n):t(m)}function Z(m){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),ne}function ne(m){return U(m)?X(e,de,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(m):de(m)}function de(m){return e.enter("htmlTextData"),a(m)}}const Nn={name:"labelEnd",tokenize:pl,resolveTo:cl,resolveAll:ul},al={tokenize:hl},ol={tokenize:fl},sl={tokenize:dl};function ul(e){let n=-1;for(;++n=3&&(s===null||D(s))?(e.exit("thematicBreak"),n(s)):t(s)}function c(s){return s===i?(e.consume(s),r++,c):(e.exit("thematicBreakSequence"),U(s)?X(e,o,"whitespace")(s):o(s))}}const te={name:"list",tokenize:vl,continuation:{tokenize:Cl},exit:jl},kl={tokenize:Nl,partial:!0},Sl={tokenize:El,partial:!0};function vl(e,n,t){const r=this,i=r.events[r.events.length-1];let l=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(f){const j=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(j==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:wn(f)){if(r.containerState.type||(r.containerState.type=j,e.enter(j,{_container:!0})),j==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Ue,t,s)(f):s(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(f)}return t(f)}function c(f){return wn(f)&&++a<10?(e.consume(f),c):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),s(f)):t(f)}function s(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(Qe,r.interrupt?t:u,e.attempt(kl,g,h))}function u(f){return r.containerState.initialBlankLine=!0,l++,g(f)}function h(f){return U(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),g):t(f)}function g(f){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(f)}}function Cl(e,n,t){const r=this;return r.containerState._closeFlow=void 0,e.check(Qe,i,l);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,X(e,n,"listItemIndent",r.containerState.size+1)(o)}function l(o){return r.containerState.furtherBlankLines||!U(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Sl,n,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(te,n,t),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function El(e,n,t){const r=this;return X(e,i,"listItemIndent",r.containerState.size+1);function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?n(l):t(l)}}function jl(e){e.exit(this.containerState.type)}function Nl(e,n,t){const r=this;return X(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(l){const a=r.events[r.events.length-1];return!U(l)&&a&&a[1].type==="listItemPrefixWhitespace"?n(l):t(l)}}const lt={name:"setextUnderline",tokenize:Fl,resolveTo:Al};function Al(e,n){let t=e.length,r,i,l;for(;t--;)if(e[t][0]==="enter"){if(e[t][1].type==="content"){r=t;break}e[t][1].type==="paragraph"&&(i=t)}else e[t][1].type==="content"&&e.splice(t,1),!l&&e[t][1].type==="definition"&&(l=t);const a={type:"setextHeading",start:Object.assign({},e[i][1].start),end:Object.assign({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",l?(e.splice(i,0,["enter",a,n]),e.splice(l+1,0,["exit",e[r][1],n]),e[r][1].end=Object.assign({},e[l][1].end)):e[r][1]=a,e.push(["exit",a,n]),e}function Fl(e,n,t){const r=this;let i;return l;function l(s){let u=r.events.length,h;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){h=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(e.enter("setextHeadingLine"),i=s,a(s)):t(s)}function a(s){return e.enter("setextHeadingLineSequence"),o(s)}function o(s){return s===i?(e.consume(s),o):(e.exit("setextHeadingLineSequence"),U(s)?X(e,c,"lineSuffix")(s):c(s))}function c(s){return s===null||D(s)?(e.exit("setextHeadingLine"),n(s)):t(s)}}const Tl={tokenize:Il};function Il(e){const n=this,t=e.attempt(Qe,r,e.attempt(this.parser.constructs.flowInitial,i,X(e,e.attempt(this.parser.constructs.flow,i,e.attempt(zi,i)),"linePrefix")));return t;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),n.currentConstruct=void 0,t}function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),n.currentConstruct=void 0,t}}const Ll={resolveAll:Bt()},Pl=Rt("string"),Ol=Rt("text");function Rt(e){return{tokenize:n,resolveAll:Bt(e==="text"?Dl:void 0)};function n(t){const r=this,i=this.parser.constructs[e],l=t.attempt(i,a,o);return a;function a(u){return s(u)?l(u):o(u)}function o(u){if(u===null){t.consume(u);return}return t.enter("data"),t.consume(u),c}function c(u){return s(u)?(t.exit("data"),l(u)):(t.consume(u),c)}function s(u){if(u===null)return!0;const h=i[u];let g=-1;if(h)for(;++g-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}l>0&&a.push(e[i].slice(0,l))}return a}function Bl(e,n){let t=-1;const r=[];let i;for(;++ti||(i=n.indexOf("#"),i!==-1&&r>i)?n:"javascript:void(0)"}var Je,Mn;function Lr(){return Mn||(Mn=1,Je=function(n){return n!=null&&n.constructor!=null&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}),Je}var Pr=Lr();const Et=Re(Pr);function De(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Hn(e.position):"start"in e||"end"in e?Hn(e):"line"in e||"column"in e?gn(e):""}function gn(e){return Un(e&&e.line)+":"+Un(e&&e.column)}function Hn(e){return gn(e&&e.start)+"-"+gn(e&&e.end)}function Un(e){return e&&typeof e=="number"?e:1}class he extends Error{constructor(n,t,r){const i=[null,null];let l={start:{line:null,column:null},end:{line:null,column:null}};if(super(),typeof t=="string"&&(r=t,t=void 0),typeof r=="string"){const a=r.indexOf(":");a===-1?i[1]=r:(i[0]=r.slice(0,a),i[1]=r.slice(a+1))}t&&("type"in t||"position"in t?t.position&&(l=t.position):"start"in t||"end"in t?l=t:("line"in t||"column"in t)&&(l.start=t)),this.name=De(t)||"1:1",this.message=typeof n=="object"?n.message:n,this.stack="",typeof n=="object"&&n.stack&&(this.stack=n.stack),this.reason=this.message,this.fatal,this.line=l.start.line,this.column=l.start.column,this.position=l,this.source=i[0],this.ruleId=i[1],this.file,this.actual,this.expected,this.url,this.note}}he.prototype.file="";he.prototype.name="";he.prototype.reason="";he.prototype.message="";he.prototype.stack="";he.prototype.fatal=null;he.prototype.column=null;he.prototype.line=null;he.prototype.source=null;he.prototype.ruleId=null;he.prototype.position=null;const ge={basename:Or,dirname:Dr,extname:zr,join:Rr,sep:"/"};function Or(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Be(e);let t=0,r=-1,i=e.length,l;if(n===void 0||n.length===0||n.length>e.length){for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else r<0&&(l=!0,r=i+1);return r<0?"":e.slice(t,r)}if(n===e)return"";let a=-1,o=n.length-1;for(;i--;)if(e.charCodeAt(i)===47){if(l){t=i+1;break}}else a<0&&(l=!0,a=i+1),o>-1&&(e.charCodeAt(i)===n.charCodeAt(o--)?o<0&&(r=i):(o=-1,r=a));return t===r?r=a:r<0&&(r=e.length),e.slice(t,r)}function Dr(e){if(Be(e),e.length===0)return".";let n=-1,t=e.length,r;for(;--t;)if(e.charCodeAt(t)===47){if(r){n=t;break}}else r||(r=!0);return n<0?e.charCodeAt(0)===47?"/":".":n===1&&e.charCodeAt(0)===47?"//":e.slice(0,n)}function zr(e){Be(e);let n=e.length,t=-1,r=0,i=-1,l=0,a;for(;n--;){const o=e.charCodeAt(n);if(o===47){if(a){r=n+1;break}continue}t<0&&(a=!0,t=n+1),o===46?i<0?i=n:l!==1&&(l=1):i>-1&&(l=-1)}return i<0||t<0||l===0||l===1&&i===t-1&&i===r+1?"":e.slice(i,t)}function Rr(...e){let n=-1,t;for(;++n0&&e.charCodeAt(e.length-1)===47&&(t+="/"),n?"/"+t:t}function _r(e,n){let t="",r=0,i=-1,l=0,a=-1,o,c;for(;++a<=e.length;){if(a2){if(c=t.lastIndexOf("/"),c!==t.length-1){c<0?(t="",r=0):(t=t.slice(0,c),r=t.length-1-t.lastIndexOf("/")),i=a,l=0;continue}}else if(t.length>0){t="",r=0,i=a,l=0;continue}}n&&(t=t.length>0?t+"/..":"..",r=2)}else t.length>0?t+="/"+e.slice(i+1,a):t=e.slice(i+1,a),r=a-i-1;i=a,l=0}else o===46&&l>-1?l++:l=-1}return t}function Be(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const $r={cwd:Mr};function Mr(){return"/"}function xn(e){return e!==null&&typeof e=="object"&&e.href&&e.origin}function Hr(e){if(typeof e=="string")e=new URL(e);else if(!xn(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return Ur(e)}function Ur(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const n=e.pathname;let t=-1;for(;++t"u"||e.call(s,g)},a=function(s,u){t&&u.name==="__proto__"?t(s,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):s[u.name]=u.newValue},o=function(s,u){if(u==="__proto__")if(e.call(s,u)){if(r)return r(s,u).value}else return;return s[u]};return tn=function c(){var s,u,h,g,f,j,b=arguments[0],x=1,k=arguments.length,S=!1;for(typeof b=="boolean"&&(S=b,b=arguments[1]||{},x=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});xa.length;let c;o&&a.push(i);try{c=e.apply(this,a)}catch(s){const u=s;if(o&&t)throw u;return i(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(l,i):c instanceof Error?i(c):l(c))}function i(a,...o){t||(t=!0,n(a,...o))}function l(a){i(null,a)}}const Yr=At().freeze(),Nt={}.hasOwnProperty;function At(){const e=Qr(),n=[];let t={},r,i=-1;return l.data=a,l.Parser=void 0,l.Compiler=void 0,l.freeze=o,l.attachers=n,l.use=c,l.parse=s,l.stringify=u,l.run=h,l.runSync=g,l.process=f,l.processSync=j,l;function l(){const b=At();let x=-1;for(;++x{if(y||!L||!B)$(y);else{const H=l.stringify(L,B);H==null||(Jr(H)?B.value=H:B.result=H),$(y,B)}});function $(y,L){y||!L?C(y):S?S(L):x(null,L)}}}function j(b){let x;l.freeze(),rn("processSync",l.Parser),ln("processSync",l.Compiler);const k=Oe(b);return l.process(k,S),Kn("processSync","process",x),k;function S(C){x=!0,Vn(C)}}}function Xn(e,n){return typeof e=="function"&&e.prototype&&(Kr(e.prototype)||n in e.prototype)}function Kr(e){let n;for(n in e)if(Nt.call(e,n))return!0;return!1}function rn(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Parser`")}function ln(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `Compiler`")}function an(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Yn(e){if(!yn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Kn(e,n,t){if(!t)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Oe(e){return Gr(e)?e:new jt(e)}function Gr(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Jr(e){return typeof e=="string"||Et(e)}const Zr={};function ei(e,n){const t=Zr,r=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return Ft(e,r,i)}function Ft(e,n,t){if(ni(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Gn(e.children,n,t)}return Array.isArray(e)?Gn(e,n,t):""}function Gn(e,n,t){const r=[];let i=-1;for(;++ii?0:i+n:n=n>i?i:n,t=t>0?t:0,r.length<1e4)a=Array.from(r),a.unshift(n,t),e.splice(...a);else for(t&&e.splice(n,t);l0?(ye(e,e.length,0,n),e):n}const Jn={}.hasOwnProperty;function ti(e){const n={};let t=-1;for(;++ta))return;const L=n.events.length;let B=L,H,K;for(;B--;)if(n.events[B][0]==="exit"&&n.events[B][1].type==="chunkFlow"){if(H){K=n.events[B][1].end;break}H=!0}for(k(r),y=L;yC;){const $=t[F];n.containerState=$[1],$[0].exit.call(n,e)}t.length=C}function S(){i.write([null]),l=void 0,i=void 0,n.containerState._closeFlow=void 0}}function mi(e,n,t){return X(e,e.attempt(this.parser.constructs.document,n,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function et(e){if(e===null||re(e)||ci(e))return 1;if(ui(e))return 2}function jn(e,n,t){const r=[];let i=-1;for(;++i1&&e[t][1].end.offset-e[t][1].start.offset>1?2:1;const h=Object.assign({},e[r][1].end),g=Object.assign({},e[t][1].start);nt(h,-c),nt(g,c),a={type:c>1?"strongSequence":"emphasisSequence",start:h,end:Object.assign({},e[r][1].end)},o={type:c>1?"strongSequence":"emphasisSequence",start:Object.assign({},e[t][1].start),end:g},l={type:c>1?"strongText":"emphasisText",start:Object.assign({},e[r][1].end),end:Object.assign({},e[t][1].start)},i={type:c>1?"strong":"emphasis",start:Object.assign({},a.start),end:Object.assign({},o.end)},e[r][1].end=Object.assign({},a.start),e[t][1].start=Object.assign({},o.end),s=[],e[r][1].end.offset-e[r][1].start.offset&&(s=pe(s,[["enter",e[r][1],n],["exit",e[r][1],n]])),s=pe(s,[["enter",i,n],["enter",a,n],["exit",a,n],["enter",l,n]]),s=pe(s,jn(n.parser.constructs.insideSpan.null,e.slice(r+1,t),n)),s=pe(s,[["exit",l,n],["enter",o,n],["exit",o,n],["exit",i,n]]),e[t][1].end.offset-e[t][1].start.offset?(u=2,s=pe(s,[["enter",e[t][1],n],["exit",e[t][1],n]])):u=0,ye(e,r-1,t-r+3,s),t=r+s.length-u-2;break}}for(t=-1;++t0&&U(y)?X(e,S,"linePrefix",l+1)(y):S(y)}function S(y){return y===null||D(y)?e.check(tt,b,F)(y):(e.enter("codeFlowValue"),C(y))}function C(y){return y===null||D(y)?(e.exit("codeFlowValue"),S(y)):(e.consume(y),C)}function F(y){return e.exit("codeFenced"),n(y)}function $(y,L,B){let H=0;return K;function K(P){return y.enter("lineEnding"),y.consume(P),y.exit("lineEnding"),T}function T(P){return y.enter("codeFencedFence"),U(P)?X(y,A,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):A(P)}function A(P){return P===o?(y.enter("codeFencedFenceSequence"),N(P)):B(P)}function N(P){return P===o?(H++,y.consume(P),N):H>=a?(y.exit("codeFencedFenceSequence"),U(P)?X(y,I,"whitespace")(P):I(P)):B(P)}function I(P){return P===null||D(P)?(y.exit("codeFencedFence"),L(P)):B(P)}}}function Ni(e,n,t){const r=this;return i;function i(a){return a===null?t(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}const on={name:"codeIndented",tokenize:Fi},Ai={tokenize:Ti,partial:!0};function Fi(e,n,t){const r=this;return i;function i(s){return e.enter("codeIndented"),X(e,l,"linePrefix",5)(s)}function l(s){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?a(s):t(s)}function a(s){return s===null?c(s):D(s)?e.attempt(Ai,a,c)(s):(e.enter("codeFlowValue"),o(s))}function o(s){return s===null||D(s)?(e.exit("codeFlowValue"),a(s)):(e.consume(s),o)}function c(s){return e.exit("codeIndented"),n(s)}}function Ti(e,n,t){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?t(a):D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):X(e,l,"linePrefix",5)(a)}function l(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?n(a):D(a)?i(a):t(a)}}const Ii={name:"codeText",tokenize:Oi,resolve:Li,previous:Pi};function Li(e){let n=e.length-4,t=3,r,i;if((e[t][1].type==="lineEnding"||e[t][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(r=t;++r=4?n(a):e.interrupt(r.parser.constructs.flow,t,n)(a)}}function Ot(e,n,t,r,i,l,a,o,c){const s=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(k){return k===60?(e.enter(r),e.enter(i),e.enter(l),e.consume(k),e.exit(l),g):k===null||k===32||k===41||bn(k)?t(k):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),b(k))}function g(k){return k===62?(e.enter(l),e.consume(k),e.exit(l),e.exit(i),e.exit(r),n):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(k))}function f(k){return k===62?(e.exit("chunkString"),e.exit(o),g(k)):k===null||k===60||D(k)?t(k):(e.consume(k),k===92?j:f)}function j(k){return k===60||k===62||k===92?(e.consume(k),f):f(k)}function b(k){return!u&&(k===null||k===41||re(k))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),n(k)):u999||f===null||f===91||f===93&&!c||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?t(f):f===93?(e.exit(l),e.enter(i),e.consume(f),e.exit(i),e.exit(r),n):D(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||D(f)||o++>999?(e.exit("chunkString"),u(f)):(e.consume(f),c||(c=!U(f)),f===92?g:h)}function g(f){return f===91||f===92||f===93?(e.consume(f),o++,h):h(f)}}function zt(e,n,t,r,i,l){let a;return o;function o(g){return g===34||g===39||g===40?(e.enter(r),e.enter(i),e.consume(g),e.exit(i),a=g===40?41:g,c):t(g)}function c(g){return g===a?(e.enter(i),e.consume(g),e.exit(i),e.exit(r),n):(e.enter(l),s(g))}function s(g){return g===a?(e.exit(l),c(a)):g===null?t(g):D(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),X(e,s,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(g))}function u(g){return g===a||g===null||D(g)?(e.exit("chunkString"),s(g)):(e.consume(g),g===92?h:u)}function h(g){return g===a||g===92?(e.consume(g),u):u(g)}}function ze(e,n){let t;return r;function r(i){return D(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t=!0,r):U(i)?X(e,r,t?"linePrefix":"lineSuffix")(i):n(i)}}function Ae(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Mi={name:"definition",tokenize:Ui},Hi={tokenize:qi,partial:!0};function Ui(e,n,t){const r=this;let i;return l;function l(f){return e.enter("definition"),a(f)}function a(f){return Dt.call(r,e,o,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return i=Ae(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),c):t(f)}function c(f){return re(f)?ze(e,s)(f):s(f)}function s(f){return Ot(e,u,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return e.attempt(Hi,h,h)(f)}function h(f){return U(f)?X(e,g,"whitespace")(f):g(f)}function g(f){return f===null||D(f)?(e.exit("definition"),r.parser.defined.push(i),n(f)):t(f)}}function qi(e,n,t){return r;function r(o){return re(o)?ze(e,i)(o):t(o)}function i(o){return zt(e,l,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function l(o){return U(o)?X(e,a,"whitespace")(o):a(o)}function a(o){return o===null||D(o)?n(o):t(o)}}const Vi={name:"hardBreakEscape",tokenize:Wi};function Wi(e,n,t){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),i}function i(l){return D(l)?(e.exit("hardBreakEscape"),n(l)):t(l)}}const Qi={name:"headingAtx",tokenize:Yi,resolve:Xi};function Xi(e,n){let t=e.length-2,r=3,i,l;return e[r][1].type==="whitespace"&&(r+=2),t-2>r&&e[t][1].type==="whitespace"&&(t-=2),e[t][1].type==="atxHeadingSequence"&&(r===t-1||t-4>r&&e[t-2][1].type==="whitespace")&&(t-=r+1===t?2:4),t>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[t][1].end},l={type:"chunkText",start:e[r][1].start,end:e[t][1].end,contentType:"text"},ye(e,r,t-r+1,[["enter",i,n],["enter",l,n],["exit",l,n],["exit",i,n]])),e}function Yi(e,n,t){let r=0;return i;function i(u){return e.enter("atxHeading"),l(u)}function l(u){return e.enter("atxHeadingSequence"),a(u)}function a(u){return u===35&&r++<6?(e.consume(u),a):u===null||re(u)?(e.exit("atxHeadingSequence"),o(u)):t(u)}function o(u){return u===35?(e.enter("atxHeadingSequence"),c(u)):u===null||D(u)?(e.exit("atxHeading"),n(u)):U(u)?X(e,o,"whitespace")(u):(e.enter("atxHeadingText"),s(u))}function c(u){return u===35?(e.consume(u),c):(e.exit("atxHeadingSequence"),o(u))}function s(u){return u===null||u===35||re(u)?(e.exit("atxHeadingText"),o(u)):(e.consume(u),s)}}const Ki=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],it=["pre","script","style","textarea"],Gi={name:"htmlFlow",tokenize:nl,resolveTo:el,concrete:!0},Ji={tokenize:rl,partial:!0},Zi={tokenize:tl,partial:!0};function el(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function nl(e,n,t){const r=this;let i,l,a,o,c;return s;function s(p){return u(p)}function u(p){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(p),h}function h(p){return p===33?(e.consume(p),g):p===47?(e.consume(p),l=!0,b):p===63?(e.consume(p),i=3,r.interrupt?n:m):xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function g(p){return p===45?(e.consume(p),i=2,f):p===91?(e.consume(p),i=5,o=0,j):xe(p)?(e.consume(p),i=4,r.interrupt?n:m):t(p)}function f(p){return p===45?(e.consume(p),r.interrupt?n:m):t(p)}function j(p){const _="CDATA[";return p===_.charCodeAt(o++)?(e.consume(p),o===_.length?r.interrupt?n:A:j):t(p)}function b(p){return xe(p)?(e.consume(p),a=String.fromCharCode(p),x):t(p)}function x(p){if(p===null||p===47||p===62||re(p)){const _=p===47,se=a.toLowerCase();return!_&&!l&&it.includes(se)?(i=1,r.interrupt?n(p):A(p)):Ki.includes(a.toLowerCase())?(i=6,_?(e.consume(p),k):r.interrupt?n(p):A(p)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?t(p):l?S(p):C(p))}return p===45||oe(p)?(e.consume(p),a+=String.fromCharCode(p),x):t(p)}function k(p){return p===62?(e.consume(p),r.interrupt?n:A):t(p)}function S(p){return U(p)?(e.consume(p),S):K(p)}function C(p){return p===47?(e.consume(p),K):p===58||p===95||xe(p)?(e.consume(p),F):U(p)?(e.consume(p),C):K(p)}function F(p){return p===45||p===46||p===58||p===95||oe(p)?(e.consume(p),F):$(p)}function $(p){return p===61?(e.consume(p),y):U(p)?(e.consume(p),$):C(p)}function y(p){return p===null||p===60||p===61||p===62||p===96?t(p):p===34||p===39?(e.consume(p),c=p,L):U(p)?(e.consume(p),y):B(p)}function L(p){return p===c?(e.consume(p),c=null,H):p===null||D(p)?t(p):(e.consume(p),L)}function B(p){return p===null||p===34||p===39||p===47||p===60||p===61||p===62||p===96||re(p)?$(p):(e.consume(p),B)}function H(p){return p===47||p===62||U(p)?C(p):t(p)}function K(p){return p===62?(e.consume(p),T):t(p)}function T(p){return p===null||D(p)?A(p):U(p)?(e.consume(p),T):t(p)}function A(p){return p===45&&i===2?(e.consume(p),J):p===60&&i===1?(e.consume(p),Z):p===62&&i===4?(e.consume(p),ie):p===63&&i===3?(e.consume(p),m):p===93&&i===5?(e.consume(p),de):D(p)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Ji,le,N)(p)):p===null||D(p)?(e.exit("htmlFlowData"),N(p)):(e.consume(p),A)}function N(p){return e.check(Zi,I,le)(p)}function I(p){return e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),P}function P(p){return p===null||D(p)?N(p):(e.enter("htmlFlowData"),A(p))}function J(p){return p===45?(e.consume(p),m):A(p)}function Z(p){return p===47?(e.consume(p),a="",ne):A(p)}function ne(p){if(p===62){const _=a.toLowerCase();return it.includes(_)?(e.consume(p),ie):A(p)}return xe(p)&&a.length<8?(e.consume(p),a+=String.fromCharCode(p),ne):A(p)}function de(p){return p===93?(e.consume(p),m):A(p)}function m(p){return p===62?(e.consume(p),ie):p===45&&i===2?(e.consume(p),m):A(p)}function ie(p){return p===null||D(p)?(e.exit("htmlFlowData"),le(p)):(e.consume(p),ie)}function le(p){return e.exit("htmlFlow"),n(p)}}function tl(e,n,t){const r=this;return i;function i(a){return D(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),l):t(a)}function l(a){return r.parser.lazy[r.now().line]?t(a):n(a)}}function rl(e,n,t){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Qe,n,t)}}const il={name:"htmlText",tokenize:ll};function ll(e,n,t){const r=this;let i,l,a;return o;function o(m){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(m),c}function c(m){return m===33?(e.consume(m),s):m===47?(e.consume(m),$):m===63?(e.consume(m),C):xe(m)?(e.consume(m),B):t(m)}function s(m){return m===45?(e.consume(m),u):m===91?(e.consume(m),l=0,j):xe(m)?(e.consume(m),S):t(m)}function u(m){return m===45?(e.consume(m),f):t(m)}function h(m){return m===null?t(m):m===45?(e.consume(m),g):D(m)?(a=h,Z(m)):(e.consume(m),h)}function g(m){return m===45?(e.consume(m),f):h(m)}function f(m){return m===62?J(m):m===45?g(m):h(m)}function j(m){const ie="CDATA[";return m===ie.charCodeAt(l++)?(e.consume(m),l===ie.length?b:j):t(m)}function b(m){return m===null?t(m):m===93?(e.consume(m),x):D(m)?(a=b,Z(m)):(e.consume(m),b)}function x(m){return m===93?(e.consume(m),k):b(m)}function k(m){return m===62?J(m):m===93?(e.consume(m),k):b(m)}function S(m){return m===null||m===62?J(m):D(m)?(a=S,Z(m)):(e.consume(m),S)}function C(m){return m===null?t(m):m===63?(e.consume(m),F):D(m)?(a=C,Z(m)):(e.consume(m),C)}function F(m){return m===62?J(m):C(m)}function $(m){return xe(m)?(e.consume(m),y):t(m)}function y(m){return m===45||oe(m)?(e.consume(m),y):L(m)}function L(m){return D(m)?(a=L,Z(m)):U(m)?(e.consume(m),L):J(m)}function B(m){return m===45||oe(m)?(e.consume(m),B):m===47||m===62||re(m)?H(m):t(m)}function H(m){return m===47?(e.consume(m),J):m===58||m===95||xe(m)?(e.consume(m),K):D(m)?(a=H,Z(m)):U(m)?(e.consume(m),H):J(m)}function K(m){return m===45||m===46||m===58||m===95||oe(m)?(e.consume(m),K):T(m)}function T(m){return m===61?(e.consume(m),A):D(m)?(a=T,Z(m)):U(m)?(e.consume(m),T):H(m)}function A(m){return m===null||m===60||m===61||m===62||m===96?t(m):m===34||m===39?(e.consume(m),i=m,N):D(m)?(a=A,Z(m)):U(m)?(e.consume(m),A):(e.consume(m),I)}function N(m){return m===i?(e.consume(m),i=void 0,P):m===null?t(m):D(m)?(a=N,Z(m)):(e.consume(m),N)}function I(m){return m===null||m===34||m===39||m===60||m===61||m===96?t(m):m===47||m===62||re(m)?H(m):(e.consume(m),I)}function P(m){return m===47||m===62||re(m)?H(m):t(m)}function J(m){return m===62?(e.consume(m),e.exit("htmlTextData"),e.exit("htmlText"),n):t(m)}function Z(m){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),ne}function ne(m){return U(m)?X(e,de,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(m):de(m)}function de(m){return e.enter("htmlTextData"),a(m)}}const Nn={name:"labelEnd",tokenize:pl,resolveTo:cl,resolveAll:ul},al={tokenize:hl},ol={tokenize:fl},sl={tokenize:dl};function ul(e){let n=-1;for(;++n=3&&(s===null||D(s))?(e.exit("thematicBreak"),n(s)):t(s)}function c(s){return s===i?(e.consume(s),r++,c):(e.exit("thematicBreakSequence"),U(s)?X(e,o,"whitespace")(s):o(s))}}const te={name:"list",tokenize:vl,continuation:{tokenize:Cl},exit:jl},kl={tokenize:Nl,partial:!0},Sl={tokenize:El,partial:!0};function vl(e,n,t){const r=this,i=r.events[r.events.length-1];let l=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(f){const j=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(j==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:wn(f)){if(r.containerState.type||(r.containerState.type=j,e.enter(j,{_container:!0})),j==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Ue,t,s)(f):s(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(f)}return t(f)}function c(f){return wn(f)&&++a<10?(e.consume(f),c):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),s(f)):t(f)}function s(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(Qe,r.interrupt?t:u,e.attempt(kl,g,h))}function u(f){return r.containerState.initialBlankLine=!0,l++,g(f)}function h(f){return U(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),g):t(f)}function g(f){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(f)}}function Cl(e,n,t){const r=this;return r.containerState._closeFlow=void 0,e.check(Qe,i,l);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,X(e,n,"listItemIndent",r.containerState.size+1)(o)}function l(o){return r.containerState.furtherBlankLines||!U(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Sl,n,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(te,n,t),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function El(e,n,t){const r=this;return X(e,i,"listItemIndent",r.containerState.size+1);function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?n(l):t(l)}}function jl(e){e.exit(this.containerState.type)}function Nl(e,n,t){const r=this;return X(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(l){const a=r.events[r.events.length-1];return!U(l)&&a&&a[1].type==="listItemPrefixWhitespace"?n(l):t(l)}}const lt={name:"setextUnderline",tokenize:Fl,resolveTo:Al};function Al(e,n){let t=e.length,r,i,l;for(;t--;)if(e[t][0]==="enter"){if(e[t][1].type==="content"){r=t;break}e[t][1].type==="paragraph"&&(i=t)}else e[t][1].type==="content"&&e.splice(t,1),!l&&e[t][1].type==="definition"&&(l=t);const a={type:"setextHeading",start:Object.assign({},e[i][1].start),end:Object.assign({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",l?(e.splice(i,0,["enter",a,n]),e.splice(l+1,0,["exit",e[r][1],n]),e[r][1].end=Object.assign({},e[l][1].end)):e[r][1]=a,e.push(["exit",a,n]),e}function Fl(e,n,t){const r=this;let i;return l;function l(s){let u=r.events.length,h;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){h=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(e.enter("setextHeadingLine"),i=s,a(s)):t(s)}function a(s){return e.enter("setextHeadingLineSequence"),o(s)}function o(s){return s===i?(e.consume(s),o):(e.exit("setextHeadingLineSequence"),U(s)?X(e,c,"lineSuffix")(s):c(s))}function c(s){return s===null||D(s)?(e.exit("setextHeadingLine"),n(s)):t(s)}}const Tl={tokenize:Il};function Il(e){const n=this,t=e.attempt(Qe,r,e.attempt(this.parser.constructs.flowInitial,i,X(e,e.attempt(this.parser.constructs.flow,i,e.attempt(zi,i)),"linePrefix")));return t;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),n.currentConstruct=void 0,t}function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),n.currentConstruct=void 0,t}}const Ll={resolveAll:Bt()},Pl=Rt("string"),Ol=Rt("text");function Rt(e){return{tokenize:n,resolveAll:Bt(e==="text"?Dl:void 0)};function n(t){const r=this,i=this.parser.constructs[e],l=t.attempt(i,a,o);return a;function a(u){return s(u)?l(u):o(u)}function o(u){if(u===null){t.consume(u);return}return t.enter("data"),t.consume(u),c}function c(u){return s(u)?(t.exit("data"),l(u)):(t.consume(u),c)}function s(u){if(u===null)return!0;const h=i[u];let g=-1;if(h)for(;++g-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}l>0&&a.push(e[i].slice(0,l))}return a}function Bl(e,n){let t=-1;const r=[];let i;for(;++t13&&t<32||t>126&&t<160||t>55295&&t<57344||t>64975&&t<65008||(t&65535)===65535||(t&65535)===65534||t>1114111?"�":String.fromCharCode(t)}const Jl=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Zl(e){return e.replace(Jl,ea)}function ea(e,n,t){if(n)return n;if(t.charCodeAt(0)===35){const i=t.charCodeAt(1),l=i===120||i===88;return _t(t.slice(l?2:1),l?16:10)}return En(t)||e}const $t={}.hasOwnProperty,na=function(e,n,t){return typeof n!="string"&&(t=n,n=void 0),ta(t)(Gl(Yl(t).document().write(Kl()(e,n,!0))))};function ta(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Rn),autolinkProtocol:T,autolinkEmail:T,atxHeading:o(On),blockQuote:o(Ye),characterEscape:T,characterReference:T,codeFenced:o(Pn),codeFencedFenceInfo:c,codeFencedFenceMeta:c,codeIndented:o(Pn,c),codeText:o(lr,c),codeTextData:T,data:T,codeFlowValue:T,definition:o(ar),definitionDestinationString:c,definitionLabelString:c,definitionTitleString:c,emphasis:o(or),hardBreakEscape:o(Dn),hardBreakTrailing:o(Dn),htmlFlow:o(zn,c),htmlFlowData:T,htmlText:o(zn,c),htmlTextData:T,image:o(sr),label:c,link:o(Rn),listItem:o(ur),listItemValue:j,listOrdered:o(Bn,f),listUnordered:o(Bn),paragraph:o(cr),reference:se,referenceString:c,resourceDestinationString:c,resourceTitleString:c,setextHeading:o(On),strong:o(pr),thematicBreak:o(fr)},exit:{atxHeading:u(),atxHeadingSequence:L,autolink:u(),autolinkEmail:Se,autolinkProtocol:ke,blockQuote:u(),characterEscapeValue:A,characterReferenceMarkerHexadecimal:ue,characterReferenceMarkerNumeric:ue,characterReferenceValue:ce,codeFenced:u(S),codeFencedFence:k,codeFencedFenceInfo:b,codeFencedFenceMeta:x,codeFlowValue:A,codeIndented:u(C),codeText:u(Z),codeTextData:A,data:A,definition:u(),definitionDestinationString:y,definitionLabelString:F,definitionTitleString:$,emphasis:u(),hardBreakEscape:u(I),hardBreakTrailing:u(I),htmlFlow:u(P),htmlFlowData:A,htmlText:u(J),htmlTextData:A,image:u(de),label:ie,labelText:m,lineEnding:N,link:u(ne),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:Y,resourceDestinationString:le,resourceTitleString:p,resource:_,setextHeading:u(K),setextHeadingLineSequence:H,setextHeadingText:B,strong:u(),thematicBreak:u()}};Mt(n,(e||{}).mdastExtensions||[]);const t={};return r;function r(w){let E={type:"root",children:[]};const O={stack:[E],tokenStack:[],config:n,enter:s,exit:h,buffer:c,resume:g,setData:l,getData:a},V=[];let W=-1;for(;++W0){const me=O.tokenStack[O.tokenStack.length-1];(me[1]||ot).call(O,void 0,me[0])}for(E.position={start:Ce(w.length>0?w[0][1].start:{line:1,column:1,offset:0}),end:Ce(w.length>0?w[w.length-2][1].end:{line:1,column:1,offset:0})},W=-1;++W{const r=this.data("settings");return na(t,Object.assign({},r,e,{extensions:this.data("micromarkExtensions")||[],mdastExtensions:this.data("fromMarkdownExtensions")||[]}))}})}function la(e,n){const t={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,t),e.applyData(n,t)}function aa(e,n){const t={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,t),[e.applyData(n,t),{type:"text",value:` `}]}function oa(e,n){const t=n.value?n.value+` diff --git a/src/agentomatic/studio/static/assets/ConnectionsView-Dvq88oBW.js b/src/agentomatic/studio/static/assets/ConnectionsView-CD79PtTG.js similarity index 97% rename from src/agentomatic/studio/static/assets/ConnectionsView-Dvq88oBW.js rename to src/agentomatic/studio/static/assets/ConnectionsView-CD79PtTG.js index 33638a0e..9d8004cb 100644 --- a/src/agentomatic/studio/static/assets/ConnectionsView-Dvq88oBW.js +++ b/src/agentomatic/studio/static/assets/ConnectionsView-CD79PtTG.js @@ -1 +1 @@ -import{u as U,A as j,j as e}from"./index-FSSL6O5F.js";import{r as a}from"./react-vendor-BHJ3EV8m.js";import{O as K}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const f=o=>{switch(o){case"healthy":case"ok":case"configured":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},A=()=>{const{config:o,darkMode:n}=U(),[d,N]=a.useState([]),[g,w]=a.useState(!0),[x,u]=a.useState(null),[b,h]=a.useState(null),[$,C]=a.useState({}),[k,S]=a.useState(null),[y,v]=a.useState(null),m=a.useCallback(async()=>{try{if(!o?.apiUrl)return;const s=new j(o.apiUrl,o.apiKey||void 0),[r,c]=await Promise.all([s.listControlConnections(),s.getOperationContract("/api/v1/control/connections/{scope}/{name}","get").catch(t=>(v(t?.message||"Could not load the connection probe contract"),null))]);N(r),S(c),c&&v(null),u(null)}catch(s){u(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch connections")}finally{w(!1)}},[o?.apiUrl,o?.apiKey]);a.useEffect(()=>{m()},[m]);const E=async(s,r)=>{if(!o?.apiUrl)return;const c=`${s}:${r}`;h(c);try{const p=await new j(o.apiUrl,o.apiKey||void 0).probeControlConnection(s,r);C(i=>({...i,[c]:p})),u(null)}catch(t){u(t?.message||`Failed to test connection '${r}'`)}finally{h(null)}},O=n?"bg-gray-800 border-gray-700":"bg-white border-gray-200",l=n?"text-gray-400":"text-gray-600",P=d.reduce((s,r)=>s+Object.keys(r.connections||{}).length,0);return e.jsxs("div",{className:`p-6 h-full overflow-y-auto ${n?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Connections"}),e.jsx("button",{onClick:m,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]}),e.jsxs("p",{className:`text-sm mb-6 ${l}`,children:["Platform persistence plus per-agent databases, vector stores & services — ",P," connection(s) across ",d.length," scope(s). Each test runs the selected live probe only."]}),g&&e.jsx("div",{className:l,children:"Loading connections…"}),x&&e.jsx("div",{className:`p-4 rounded-lg border mb-4 ${n?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:x}),!g&&!x&&d.length===0&&e.jsx("div",{className:l,children:"No connections registered."}),e.jsx("div",{className:"space-y-6",children:d.map(s=>e.jsxs("div",{className:`rounded-xl border ${O}`,children:[e.jsxs("div",{className:`px-5 py-3 border-b flex items-center gap-2 ${n?"border-gray-700":"border-gray-200"}`,children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${n?"bg-gray-700":"bg-gray-100"}`,children:"scope"}),e.jsx("span",{className:"font-semibold",children:s.scope})]}),e.jsxs("div",{className:"p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[Object.entries(s.connections||{}).map(([r,c])=>{const t=c||{},p=`${s.scope}:${r}`,i=$[p];return e.jsxs("div",{className:`p-4 rounded-lg border ${n?"border-gray-700 bg-gray-900/40":"border-gray-200 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-medium",children:r}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${f(t.status)}`}),t.status||"unknown"]})]}),e.jsxs("div",{className:`text-xs space-y-0.5 ${l}`,children:[t.kind&&e.jsxs("div",{children:["kind: ",t.kind]}),t.purpose&&e.jsxs("div",{children:["purpose: ",t.purpose]}),t.backend&&e.jsxs("div",{children:["backend: ",t.backend]}),t.provider&&e.jsxs("div",{children:["provider: ",t.provider]}),t.detail&&e.jsx("div",{className:n?"text-amber-300":"text-amber-700",children:String(t.detail)}),t.error&&e.jsxs("div",{className:"text-red-400",children:["error: ",String(t.error)]})]}),e.jsx("button",{type:"button",onClick:()=>{E(s.scope,r)},disabled:b!==null,className:"mt-3 rounded-md bg-violet-600 px-2.5 py-1.5 text-xs font-medium text-white hover:bg-violet-700 disabled:opacity-50",children:b===p?"Testing…":"Test connection"}),y?e.jsxs("p",{role:"status",className:`mt-2 text-[10px] ${n?"text-amber-300":"text-amber-700"}`,children:["Live output contract unavailable: ",y]}):e.jsx(K,{schema:k?.output_schema,darkMode:n,className:"mt-3"}),i&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("div",{className:`mb-1 flex items-center gap-1.5 text-[10px] font-medium ${l}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f(i.status)}`}),"Last live probe: ",i.status||"unknown"]}),e.jsx("pre",{className:`max-h-36 overflow-auto rounded p-2 text-[10px] ${n?"bg-gray-950 text-gray-300":"bg-white text-gray-700"}`,children:JSON.stringify(i,null,2)})]})]},r)}),Object.keys(s.connections||{}).length===0&&e.jsx("div",{className:`text-sm ${l}`,children:"No connections in this scope."})]})]},s.scope))})]})};export{A as ConnectionsView}; +import{u as U,A as j,j as e}from"./index-BMj1jeBL.js";import{r as a}from"./react-vendor-BHJ3EV8m.js";import{O as K}from"./OutputSchemaSummary-CiE3pU-0.js";import"./syntax-vendor-ru7AzRyY.js";const f=o=>{switch(o){case"healthy":case"ok":case"configured":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},A=()=>{const{config:o,darkMode:n}=U(),[d,N]=a.useState([]),[g,w]=a.useState(!0),[x,u]=a.useState(null),[b,h]=a.useState(null),[$,C]=a.useState({}),[k,S]=a.useState(null),[y,v]=a.useState(null),m=a.useCallback(async()=>{try{if(!o?.apiUrl)return;const s=new j(o.apiUrl,o.apiKey||void 0),[r,c]=await Promise.all([s.listControlConnections(),s.getOperationContract("/api/v1/control/connections/{scope}/{name}","get").catch(t=>(v(t?.message||"Could not load the connection probe contract"),null))]);N(r),S(c),c&&v(null),u(null)}catch(s){u(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch connections")}finally{w(!1)}},[o?.apiUrl,o?.apiKey]);a.useEffect(()=>{m()},[m]);const E=async(s,r)=>{if(!o?.apiUrl)return;const c=`${s}:${r}`;h(c);try{const p=await new j(o.apiUrl,o.apiKey||void 0).probeControlConnection(s,r);C(i=>({...i,[c]:p})),u(null)}catch(t){u(t?.message||`Failed to test connection '${r}'`)}finally{h(null)}},O=n?"bg-gray-800 border-gray-700":"bg-white border-gray-200",l=n?"text-gray-400":"text-gray-600",P=d.reduce((s,r)=>s+Object.keys(r.connections||{}).length,0);return e.jsxs("div",{className:`p-6 h-full overflow-y-auto ${n?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Connections"}),e.jsx("button",{onClick:m,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]}),e.jsxs("p",{className:`text-sm mb-6 ${l}`,children:["Platform persistence plus per-agent databases, vector stores & services — ",P," connection(s) across ",d.length," scope(s). Each test runs the selected live probe only."]}),g&&e.jsx("div",{className:l,children:"Loading connections…"}),x&&e.jsx("div",{className:`p-4 rounded-lg border mb-4 ${n?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:x}),!g&&!x&&d.length===0&&e.jsx("div",{className:l,children:"No connections registered."}),e.jsx("div",{className:"space-y-6",children:d.map(s=>e.jsxs("div",{className:`rounded-xl border ${O}`,children:[e.jsxs("div",{className:`px-5 py-3 border-b flex items-center gap-2 ${n?"border-gray-700":"border-gray-200"}`,children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${n?"bg-gray-700":"bg-gray-100"}`,children:"scope"}),e.jsx("span",{className:"font-semibold",children:s.scope})]}),e.jsxs("div",{className:"p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[Object.entries(s.connections||{}).map(([r,c])=>{const t=c||{},p=`${s.scope}:${r}`,i=$[p];return e.jsxs("div",{className:`p-4 rounded-lg border ${n?"border-gray-700 bg-gray-900/40":"border-gray-200 bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-medium",children:r}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${f(t.status)}`}),t.status||"unknown"]})]}),e.jsxs("div",{className:`text-xs space-y-0.5 ${l}`,children:[t.kind&&e.jsxs("div",{children:["kind: ",t.kind]}),t.purpose&&e.jsxs("div",{children:["purpose: ",t.purpose]}),t.backend&&e.jsxs("div",{children:["backend: ",t.backend]}),t.provider&&e.jsxs("div",{children:["provider: ",t.provider]}),t.detail&&e.jsx("div",{className:n?"text-amber-300":"text-amber-700",children:String(t.detail)}),t.error&&e.jsxs("div",{className:"text-red-400",children:["error: ",String(t.error)]})]}),e.jsx("button",{type:"button",onClick:()=>{E(s.scope,r)},disabled:b!==null,className:"mt-3 rounded-md bg-violet-600 px-2.5 py-1.5 text-xs font-medium text-white hover:bg-violet-700 disabled:opacity-50",children:b===p?"Testing…":"Test connection"}),y?e.jsxs("p",{role:"status",className:`mt-2 text-[10px] ${n?"text-amber-300":"text-amber-700"}`,children:["Live output contract unavailable: ",y]}):e.jsx(K,{schema:k?.output_schema,darkMode:n,className:"mt-3"}),i&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("div",{className:`mb-1 flex items-center gap-1.5 text-[10px] font-medium ${l}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f(i.status)}`}),"Last live probe: ",i.status||"unknown"]}),e.jsx("pre",{className:`max-h-36 overflow-auto rounded p-2 text-[10px] ${n?"bg-gray-950 text-gray-300":"bg-white text-gray-700"}`,children:JSON.stringify(i,null,2)})]})]},r)}),Object.keys(s.connections||{}).length===0&&e.jsx("div",{className:`text-sm ${l}`,children:"No connections in this scope."})]})]},s.scope))})]})};export{A as ConnectionsView}; diff --git a/src/agentomatic/studio/static/assets/ControlPlaneView-CC__Od52.js b/src/agentomatic/studio/static/assets/ControlPlaneView-Vj8HdZgI.js similarity index 99% rename from src/agentomatic/studio/static/assets/ControlPlaneView-CC__Od52.js rename to src/agentomatic/studio/static/assets/ControlPlaneView-Vj8HdZgI.js index 73eb90a5..da7abc35 100644 --- a/src/agentomatic/studio/static/assets/ControlPlaneView-CC__Od52.js +++ b/src/agentomatic/studio/static/assets/ControlPlaneView-Vj8HdZgI.js @@ -1,2 +1,2 @@ -import{u as P,A as q,j as e,V as h}from"./index-FSSL6O5F.js";import{r as l,R as F}from"./react-vendor-BHJ3EV8m.js";import"./syntax-vendor-ru7AzRyY.js";const f="agentomatic_control_token",K=r=>{switch(r){case"healthy":case"ok":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},D=()=>{const{config:r,darkMode:o}=P(),[t,w]=l.useState(null),[p,_]=l.useState(null),[y,$]=l.useState([]),[j,k]=l.useState({}),[C,A]=l.useState(!0),[g,N]=l.useState(null),[d,m]=l.useState(null),[x,S]=l.useState(()=>sessionStorage.getItem(f)||""),n=F.useMemo(()=>r?.apiUrl?new q(r.apiUrl,r.apiKey||void 0):null,[r?.apiUrl,r?.apiKey]),i=l.useCallback(async()=>{if(n)try{const[s,c,T,M]=await Promise.all([n.getControlInfo(),n.getControlMetricsSummary(),n.listControlAgents(),n.getControlConfig()]);w(s),_(c),$(T),k(M.features||{}),N(null)}catch(s){const c=s?.status===404?"Control plane is not enabled on this platform (start with enable_control_plane=True).":s?.message||"Failed to load control plane";N(c)}finally{A(!1)}},[n]);l.useEffect(()=>{i();const s=setInterval(i,5e3);return()=>clearInterval(s)},[i]);const E=s=>{S(s),s?sessionStorage.setItem(f,s):sessionStorage.removeItem(f)},R=async s=>{if(n){m(`agent:${s.name}`);try{await n.setAgentEnabled(s.name,!s.enabled,x||void 0),h.success(`${s.name} ${s.enabled?"disabled":"enabled"}`),i()}catch(c){h.error(c?.status===401?"Invalid control token":c?.message||"Action failed")}finally{m(null)}}},I=async()=>{if(!(!n||!t)){m("maintenance");try{await n.setMaintenance(!t.maintenance_mode,x||void 0),h.success(`Maintenance mode ${t.maintenance_mode?"disabled":"enabled"}`),i()}catch(s){h.error(s?.status===401?"Invalid control token":s?.message||"Action failed")}finally{m(null)}}},b=o?"bg-gray-800 border-gray-700":"bg-white border-gray-200",a=o?"text-gray-400":"text-gray-500",v=!!t?.control_token_required,u=v&&!x||d!==null;return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${o?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Control Plane"}),e.jsx("p",{className:`text-sm ${a}`,children:"Runtime operations & health"})]}),e.jsxs("div",{className:"flex w-full items-center gap-2 sm:w-auto",children:[e.jsx("input",{type:"password","aria-label":"X-Control-Token (optional)",value:x,onChange:s=>E(s.target.value),placeholder:"X-Control-Token (optional)",className:`min-w-0 flex-1 px-3 py-2 rounded-lg text-sm border sm:w-56 sm:flex-none ${o?"bg-gray-800 border-gray-700 text-white":"bg-white border-gray-300"}`}),e.jsx("button",{type:"button",onClick:i,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]})]}),C&&e.jsx("div",{className:a,children:"Loading control plane…"}),g&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${o?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:g}),!g&&t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 mb-6",children:[{label:"Agents",value:t.agent_count},{label:"Endpoints",value:t.endpoint_count},{label:"Plugins",value:t.plugin_count},{label:"Pipelines",value:t.pipeline_count},{label:"Conn. scopes",value:t.connection_scopes},{label:"Uptime (s)",value:Math.round(t.uptime_seconds)}].map(s=>e.jsxs("div",{className:`p-4 rounded-xl border ${b}`,children:[e.jsx("div",{className:"text-2xl font-bold",children:s.value}),e.jsx("div",{className:`text-xs ${a}`,children:s.label})]},s.label))}),e.jsxs("div",{className:`mb-6 flex flex-col gap-3 rounded-xl border p-4 sm:flex-row sm:items-center sm:justify-between ${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`w-3 h-3 rounded-full ${t.maintenance_mode?"bg-yellow-500 animate-pulse":"bg-green-500"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold",children:[t.platform," · v",t.version]}),e.jsxs("div",{className:`text-xs ${a}`,children:[t.maintenance_mode?"Maintenance mode is ON":"Serving traffic",p?` · ${p.disabled_agents} disabled · metrics ${p.prometheus_available?"on":"off"}`:"",v?" · control token required for mutations":""]})]})]}),e.jsx("button",{onClick:I,disabled:u,title:d?"Another control-plane change is in progress":u?"Enter X-Control-Token to change maintenance mode":void 0,className:`px-4 py-2 rounded-lg text-sm font-medium ${t.maintenance_mode?"bg-green-600 text-white hover:bg-green-700":"bg-yellow-600 text-white hover:bg-yellow-700"} disabled:cursor-not-allowed disabled:opacity-50`,children:d==="maintenance"?t.maintenance_mode?"Resuming traffic…":"Entering maintenance…":t.maintenance_mode?"Resume traffic":"Enter maintenance"})]}),e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Agents"}),e.jsx("div",{className:`overflow-x-auto rounded-xl border ${b}`,children:e.jsxs("table",{className:"min-w-[44rem] w-full text-sm",children:[e.jsx("thead",{className:o?"bg-gray-700/50":"bg-gray-100",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3",children:"Agent"}),e.jsx("th",{className:"px-4 py-3",children:"Framework"}),e.jsx("th",{className:"px-4 py-3",children:"Health"}),e.jsx("th",{className:"px-4 py-3",children:"Agent policy"}),e.jsx("th",{className:"px-4 py-3",children:"Connections"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Action"})]})}),e.jsxs("tbody",{children:[y.map(s=>e.jsxs("tr",{className:`border-t ${o?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium",children:s.name}),e.jsx("div",{className:`text-xs ${a}`,children:s.description||s.slug})]}),e.jsx("td",{className:"px-4 py-3",children:s.framework||"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${K(s.health?.status)}`}),s.health?.status||"unknown"]})}),e.jsx("td",{className:"px-4 py-3",children:s.requires_auth?e.jsxs("span",{className:"text-xs",title:`roles: ${s.allowed_roles.join(", ")||"—"} +import{u as P,A as q,j as e,V as h}from"./index-BMj1jeBL.js";import{r as l,R as F}from"./react-vendor-BHJ3EV8m.js";import"./syntax-vendor-ru7AzRyY.js";const f="agentomatic_control_token",K=r=>{switch(r){case"healthy":case"ok":return"bg-green-500";case"degraded":return"bg-yellow-500";case"error":case"unhealthy":return"bg-red-500";default:return"bg-gray-400"}},D=()=>{const{config:r,darkMode:o}=P(),[t,w]=l.useState(null),[p,_]=l.useState(null),[y,$]=l.useState([]),[j,k]=l.useState({}),[C,A]=l.useState(!0),[g,N]=l.useState(null),[d,m]=l.useState(null),[x,S]=l.useState(()=>sessionStorage.getItem(f)||""),n=F.useMemo(()=>r?.apiUrl?new q(r.apiUrl,r.apiKey||void 0):null,[r?.apiUrl,r?.apiKey]),i=l.useCallback(async()=>{if(n)try{const[s,c,T,M]=await Promise.all([n.getControlInfo(),n.getControlMetricsSummary(),n.listControlAgents(),n.getControlConfig()]);w(s),_(c),$(T),k(M.features||{}),N(null)}catch(s){const c=s?.status===404?"Control plane is not enabled on this platform (start with enable_control_plane=True).":s?.message||"Failed to load control plane";N(c)}finally{A(!1)}},[n]);l.useEffect(()=>{i();const s=setInterval(i,5e3);return()=>clearInterval(s)},[i]);const E=s=>{S(s),s?sessionStorage.setItem(f,s):sessionStorage.removeItem(f)},R=async s=>{if(n){m(`agent:${s.name}`);try{await n.setAgentEnabled(s.name,!s.enabled,x||void 0),h.success(`${s.name} ${s.enabled?"disabled":"enabled"}`),i()}catch(c){h.error(c?.status===401?"Invalid control token":c?.message||"Action failed")}finally{m(null)}}},I=async()=>{if(!(!n||!t)){m("maintenance");try{await n.setMaintenance(!t.maintenance_mode,x||void 0),h.success(`Maintenance mode ${t.maintenance_mode?"disabled":"enabled"}`),i()}catch(s){h.error(s?.status===401?"Invalid control token":s?.message||"Action failed")}finally{m(null)}}},b=o?"bg-gray-800 border-gray-700":"bg-white border-gray-200",a=o?"text-gray-400":"text-gray-500",v=!!t?.control_token_required,u=v&&!x||d!==null;return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${o?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Control Plane"}),e.jsx("p",{className:`text-sm ${a}`,children:"Runtime operations & health"})]}),e.jsxs("div",{className:"flex w-full items-center gap-2 sm:w-auto",children:[e.jsx("input",{type:"password","aria-label":"X-Control-Token (optional)",value:x,onChange:s=>E(s.target.value),placeholder:"X-Control-Token (optional)",className:`min-w-0 flex-1 px-3 py-2 rounded-lg text-sm border sm:w-56 sm:flex-none ${o?"bg-gray-800 border-gray-700 text-white":"bg-white border-gray-300"}`}),e.jsx("button",{type:"button",onClick:i,className:"px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700",children:"Refresh"})]})]}),C&&e.jsx("div",{className:a,children:"Loading control plane…"}),g&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${o?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:g}),!g&&t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 mb-6",children:[{label:"Agents",value:t.agent_count},{label:"Endpoints",value:t.endpoint_count},{label:"Plugins",value:t.plugin_count},{label:"Pipelines",value:t.pipeline_count},{label:"Conn. scopes",value:t.connection_scopes},{label:"Uptime (s)",value:Math.round(t.uptime_seconds)}].map(s=>e.jsxs("div",{className:`p-4 rounded-xl border ${b}`,children:[e.jsx("div",{className:"text-2xl font-bold",children:s.value}),e.jsx("div",{className:`text-xs ${a}`,children:s.label})]},s.label))}),e.jsxs("div",{className:`mb-6 flex flex-col gap-3 rounded-xl border p-4 sm:flex-row sm:items-center sm:justify-between ${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`w-3 h-3 rounded-full ${t.maintenance_mode?"bg-yellow-500 animate-pulse":"bg-green-500"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold",children:[t.platform," · v",t.version]}),e.jsxs("div",{className:`text-xs ${a}`,children:[t.maintenance_mode?"Maintenance mode is ON":"Serving traffic",p?` · ${p.disabled_agents} disabled · metrics ${p.prometheus_available?"on":"off"}`:"",v?" · control token required for mutations":""]})]})]}),e.jsx("button",{onClick:I,disabled:u,title:d?"Another control-plane change is in progress":u?"Enter X-Control-Token to change maintenance mode":void 0,className:`px-4 py-2 rounded-lg text-sm font-medium ${t.maintenance_mode?"bg-green-600 text-white hover:bg-green-700":"bg-yellow-600 text-white hover:bg-yellow-700"} disabled:cursor-not-allowed disabled:opacity-50`,children:d==="maintenance"?t.maintenance_mode?"Resuming traffic…":"Entering maintenance…":t.maintenance_mode?"Resume traffic":"Enter maintenance"})]}),e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Agents"}),e.jsx("div",{className:`overflow-x-auto rounded-xl border ${b}`,children:e.jsxs("table",{className:"min-w-[44rem] w-full text-sm",children:[e.jsx("thead",{className:o?"bg-gray-700/50":"bg-gray-100",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3",children:"Agent"}),e.jsx("th",{className:"px-4 py-3",children:"Framework"}),e.jsx("th",{className:"px-4 py-3",children:"Health"}),e.jsx("th",{className:"px-4 py-3",children:"Agent policy"}),e.jsx("th",{className:"px-4 py-3",children:"Connections"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Action"})]})}),e.jsxs("tbody",{children:[y.map(s=>e.jsxs("tr",{className:`border-t ${o?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium",children:s.name}),e.jsx("div",{className:`text-xs ${a}`,children:s.description||s.slug})]}),e.jsx("td",{className:"px-4 py-3",children:s.framework||"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${K(s.health?.status)}`}),s.health?.status||"unknown"]})}),e.jsx("td",{className:"px-4 py-3",children:s.requires_auth?e.jsxs("span",{className:"text-xs",title:`roles: ${s.allowed_roles.join(", ")||"—"} scopes: ${s.allowed_scopes.join(", ")||"—"}`,children:["🔒 ",s.allowed_roles.length+s.allowed_scopes.length," rule(s)"]}):e.jsx("span",{className:`text-xs ${a}`,title:j.auth?"No per-agent rules; platform API-key authentication is still required.":"No platform or per-agent authentication rules.",children:j.auth?"policy open · API key":"open"})}),e.jsx("td",{className:"px-4 py-3",children:s.connections.length?e.jsx("span",{className:"text-xs",children:s.connections.join(", ")}):e.jsx("span",{className:`text-xs ${a}`,children:"—"})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx("button",{onClick:()=>R(s),disabled:u,title:d?"Another control-plane change is in progress":u?"Enter X-Control-Token to change agent routing":void 0,className:`px-3 py-1.5 rounded-lg text-xs font-medium ${s.enabled?"bg-red-600 text-white hover:bg-red-700":"bg-green-600 text-white hover:bg-green-700"} disabled:cursor-not-allowed disabled:opacity-50`,children:d===`agent:${s.name}`?s.enabled?"Draining…":"Enabling…":s.enabled?"Drain":"Enable"})})]},s.name)),y.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:`px-4 py-6 text-center ${a}`,children:"No agents registered."})})]})]})})]})]})};export{D as ControlPlaneView}; diff --git a/src/agentomatic/studio/static/assets/DebugView-Bwa7sy_c.js b/src/agentomatic/studio/static/assets/DebugView-BXWYXNI6.js similarity index 99% rename from src/agentomatic/studio/static/assets/DebugView-Bwa7sy_c.js rename to src/agentomatic/studio/static/assets/DebugView-BXWYXNI6.js index 6bb76ac6..12d2211a 100644 --- a/src/agentomatic/studio/static/assets/DebugView-Bwa7sy_c.js +++ b/src/agentomatic/studio/static/assets/DebugView-BXWYXNI6.js @@ -1 +1 @@ -import{u as T,j as e,A as O,f as W,V as f}from"./index-FSSL6O5F.js";import{r as o,R as F}from"./react-vendor-BHJ3EV8m.js";import{F as I}from"./ClipboardDocumentIcon-Cnz7XqGa.js";import"./syntax-vendor-ru7AzRyY.js";function V({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.75 19.5 8.25 12l7.5-7.5"}))}const P=o.forwardRef(V);function H({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m8.25 4.5 7.5 7.5-7.5 7.5"}))}const z=o.forwardRef(H),ee=()=>{const{graphState:l,selectedThread:t,darkMode:s,executionContext:n,selectedAgent:x,config:m}=T(),[d,r]=o.useState("state"),[c,u]=o.useState(""),[p,v]=o.useState("ALL"),[N,_]=o.useState(0),[j,w]=o.useState(null),[$,h]=o.useState([]),[b,S]=o.useState(!1),[R,L]=o.useState(void 0);o.useEffect(()=>{let a=!0;return(async()=>{if(!x?.id||!t?.id||!m?.apiUrl){w(null),h([]),L(void 0),S(!1);return}S(!0);try{const y=await new O(m.apiUrl,m.apiKey).getState(x.id,t.id);a&&(w(y),L(void 0))}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load real state, using execution context",y),a&&L(y)}try{const y=await new O(m.apiUrl,m.apiKey).getHistory(x.id,t.id);a&&h(y)}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load history",y),a&&L(E=>E||y)}a&&S(!1)})(),()=>{a=!1}},[x?.id,t?.id,m?.apiUrl,m?.apiKey]);const D=n.isExecuting&&n.currentState&&Object.keys(n.currentState).length>0?{...j?.state||{},...n.currentState}:void 0,A=j?{messages:t?.messages||[],current_node:l?.currentNode||j.state?.current_node||"agent",execution_path:l?.executionPath||[],variables:D||j.state||n.currentState||{},metadata:{agent_name:j.agent_name||x?.name||"unknown",thread_id:j.thread_id||t?.id||"unknown",checkpoint_id:j.checkpoint_id||null,timestamp:j.timestamp||new Date().toISOString()}}:{messages:t?.messages||[],current_node:l?.currentNode||"agent",execution_path:l?.executionPath||[],variables:D||n.currentState||{},metadata:{agent_name:x?.name||"unknown",thread_id:t?.id||"unknown",timestamp:new Date().toISOString()}},C=n.logs.filter(a=>a.type==="input"||a.type==="output").reduce((a,i,g)=>{const y=a.find(E=>E.node===i.nodeId);return y?i.type==="output"&&(y.status="completed",y.output=i.data?.output||i.data,y.duration=i.duration||null):a.push({id:i.id||`step_${g}`,node:i.nodeId,status:i.type==="output"?"completed":i.type==="error"?"error":"running",input:i.type==="input"?i.data?.input||i.data:null,output:i.type==="output"?i.data?.output||i.data:null,timestamp:i.timestamp,duration:i.duration||null,tokens_used:0}),a},[]),B=n.logs.map(a=>({level:a.type==="error"?"ERROR":a.type==="debug"?"DEBUG":(a.type==="info","INFO"),message:a.message,timestamp:a.timestamp,node:a.nodeId,details:a.data||{}})),J={total_execution_time:n.startTime&&n.endTime?n.endTime.getTime()-n.startTime.getTime():n.startTime?Date.now()-n.startTime.getTime():0,node_performance:Object.entries(n.logs.reduce((a,i)=>(i.duration!==void 0&&(a[i.nodeId]||(a[i.nodeId]={total:0,count:0}),a[i.nodeId].total+=i.duration,a[i.nodeId].count+=1),a),{})).map(([a,i])=>({node:a,avg_duration:Number((i.total/i.count).toFixed(2)),calls:i.count,total_time:Number(i.total.toFixed(2))})),memory_usage:{current:"N/A",peak:"N/A",average:"N/A"},token_usage:n.logs.reduce((a,i)=>{const g=i.data?.output?.metadata?.tokens_used||i.data?.metadata?.tokens_used||0;return g&&(a.total+=g),a},{total:0,input:0,output:0,cost_estimate:"$0.00"})},U=B.filter(a=>{const i=a.message.toLowerCase().includes(c.toLowerCase())||a.node.toLowerCase().includes(c.toLowerCase()),g=p==="ALL"||a.level===p;return i&&g});return e.jsxs("div",{className:`h-full flex flex-col transition-all duration-300 ${s?"bg-gray-900":"bg-gray-50"}`,children:[R&&e.jsxs("div",{className:`px-4 py-3 text-sm border-b ${s?"bg-red-900/40 border-red-700 text-red-200":"bg-red-50 border-red-200 text-red-800"}`,role:"alert",children:[e.jsx("strong",{children:"Debug load error:"})," ",R]}),e.jsxs("div",{className:`relative overflow-hidden ${s?"bg-gradient-to-r from-gray-800 via-gray-700 to-gray-800":"bg-gradient-to-r from-blue-50 via-white to-purple-50"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),e.jsx("div",{className:"relative border-b border-gray-200 p-4 sm:p-6 dark:border-gray-700",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center space-x-3 sm:space-x-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${s?"bg-blue-600/20 text-blue-400":"bg-blue-100 text-blue-600"}`,children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}),e.jsxs("div",{children:[e.jsx("h2",{className:`text-xl font-bold sm:text-2xl ${s?"text-white":"text-gray-900"}`,children:"Debug Console"}),e.jsx("p",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:"Real-time graph execution monitoring and analysis"})]})]}),e.jsxs("div",{className:"hidden items-center space-x-3 sm:flex",children:[e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full animate-pulse ${b?"bg-amber-500":"bg-green-500"}`}),e.jsx("span",{className:`text-sm font-medium ${s?"text-gray-300":"text-gray-700"}`,children:b?"Loading state…":"Live"})]}),e.jsx("div",{className:`px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:e.jsxs("span",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:[C.filter(a=>a.status==="completed").length,"/",C.length," Steps"]})})]})]})})]}),e.jsx("div",{className:`border-b ${s?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsx("div",{className:"overflow-x-auto px-3 sm:px-6",children:e.jsx("nav",{className:"flex min-w-max space-x-5 sm:space-x-8",children:[{id:"state",label:"State",icon:"🔍",count:Object.keys(A.variables).length},{id:"history",label:"Time Travel",icon:"⏪",count:$.length},{id:"steps",label:"Steps",icon:"📋",count:C.length},{id:"logs",label:"Logs",icon:"📝",count:U.length},{id:"performance",label:"Performance",icon:"⚡",count:J.node_performance.length}].map(a=>e.jsx("button",{onClick:()=>r(a.id),className:`relative py-4 px-1 font-medium text-sm transition-all duration-200 ${d===a.id?s?"text-blue-400 border-b-2 border-blue-400":"text-blue-600 border-b-2 border-blue-500":s?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{children:a.icon}),e.jsx("span",{children:a.label}),e.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${d===a.id?s?"bg-blue-600 text-white":"bg-blue-100 text-blue-600":s?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-600"}`,children:a.count})]})},a.id))})})}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[d==="state"&&e.jsx(G,{state:A,darkMode:s,isExecuting:n.isExecuting,onStateUpdated:w}),d==="history"&&e.jsx(X,{history:$,darkMode:s,checkpointIndex:N,setCheckpointIndex:_}),d==="steps"&&e.jsx(K,{steps:C,darkMode:s}),d==="logs"&&e.jsx(q,{logs:U,darkMode:s,searchTerm:c,setSearchTerm:u,logLevel:p,setLogLevel:v}),d==="performance"&&e.jsx(Q,{performance:J,darkMode:s})]})]})},G=({state:l,darkMode:t,isExecuting:s,onStateUpdated:n})=>{const[x,m]=o.useState(new Set(["variables"])),[d,r]=o.useState(!1),[c,u]=o.useState(""),{selectedAgent:p,selectedThread:v,config:N}=T(),_=async()=>{try{await navigator.clipboard.writeText(JSON.stringify(l.variables,null,2)),f.success("State JSON copied to clipboard")}catch{f.error("Failed to copy to clipboard")}},j=()=>{u(JSON.stringify(l.variables,null,2)),r(!0)},w=async()=>{let h;try{h=JSON.parse(c)}catch{f.error("State must be valid JSON");return}if(!p||!v||!N?.apiUrl){f.error("Select an agent and thread before editing state");return}try{const S=await new O(N.apiUrl,N.apiKey).updateState(p.id,v.id,h);n(S),r(!1),f.success("State updated")}catch(b){f.error(b instanceof Error?b.message:"Failed to update state")}},$=h=>{const b=new Set(x);b.has(h)?b.delete(h):b.add(h),m(b)};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("h3",{className:`text-lg font-semibold mb-4 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("svg",{className:"w-5 h-5 mr-2 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Execution Overview",s&&e.jsxs("span",{className:"ml-3 flex items-center space-x-2",children:[e.jsxs("span",{className:"relative flex h-3 w-3",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-green-500"})]}),e.jsx("span",{className:`text-xs font-normal ${t?"text-green-400":"text-green-600"}`,children:"Live updating"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Current Node"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:l.current_node})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Steps Completed"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.execution_path?.length||0})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Messages"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.messages?.length||0})]})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Execution Path"}),e.jsx("div",{className:"flex items-center space-x-2 flex-wrap gap-2",children:l.execution_path?.map((h,b)=>e.jsxs(F.Fragment,{children:[e.jsxs("div",{className:`flex items-center px-4 py-2 rounded-lg border-2 ${t?"bg-blue-600 border-blue-500 text-white":"bg-blue-50 border-blue-200 text-blue-700"}`,children:[e.jsx("span",{className:`w-6 h-6 rounded-full flex items-center justify-center mr-2 text-xs font-bold ${t?"bg-blue-500":"bg-blue-200"}`,children:b+1}),h]}),br(!1),className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Cancel"})]}):e.jsx("button",{onClick:j,className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Edit State"})]}),e.jsx("button",{onClick:()=>$("variables"),children:e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("variables")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]}),x.has("variables")&&e.jsx("div",{className:`mx-6 mb-6 p-4 rounded-lg overflow-x-auto ${t?"bg-gray-900":"bg-gray-50"}`,children:d?e.jsx("textarea",{"aria-label":"Edit state JSON",className:`w-full h-64 p-2 font-mono text-sm rounded ${t?"bg-gray-800 text-green-400":"bg-white text-green-600"}`,value:c,onChange:h=>u(h.target.value)}):e.jsx("pre",{className:`text-sm font-mono ${t?"text-green-400":"text-green-600"}`,children:JSON.stringify(l.variables,null,2)})})]}),e.jsxs("div",{className:`rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("button",{onClick:()=>$("metadata"),className:`w-full p-6 text-left flex items-center justify-between ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Metadata"}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("metadata")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),x.has("metadata")&&e.jsx("div",{className:"px-6 pb-6",children:e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(l.metadata,null,2)})})})]})]})})},K=({steps:l,darkMode:t})=>{const[s,n]=o.useState(new Set),x=r=>{const c=new Set(s);c.has(r)?c.delete(r):c.add(r),n(c)},m=r=>{switch(r){case"completed":return"text-green-600 bg-green-100 border-green-200";case"running":return"text-blue-600 bg-blue-100 border-blue-200";case"error":return"text-red-600 bg-red-100 border-red-200";default:return"text-gray-600 bg-gray-100 border-gray-200"}},d=r=>{switch(r){case"completed":return"text-green-400 bg-green-900/30 border-green-700";case"running":return"text-blue-400 bg-blue-900/30 border-blue-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsx("div",{className:"max-w-4xl mx-auto space-y-4",children:l.map((r,c)=>{const u=s.has(r.id),p=t?d(r.status):m(r.status);return e.jsxs("div",{className:`rounded-xl border transition-all duration-200 ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"} hover:shadow-lg`,children:[e.jsx("button",{onClick:()=>x(r.id),className:`w-full p-6 text-left ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`flex items-center justify-center w-10 h-10 rounded-full font-bold ${t?"bg-blue-600 text-white":"bg-blue-100 text-blue-600"}`,children:c+1}),e.jsxs("div",{children:[e.jsx("h4",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:r.node}),e.jsxs("p",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:["Step ID: ",r.id]})]})]}),e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`px-3 py-1 rounded-full text-sm font-medium border ${p}`,children:r.status}),r.duration&&e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:[r.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${u?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}),u&&e.jsxs("div",{className:`px-6 pb-6 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6",children:[r.input&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Input Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.input,null,2)})})]}),r.output&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Output Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.output,null,2)})})]})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Timestamp"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.timestamp?W(r.timestamp,"HH:mm:ss.SSS"):"Pending"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Duration"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.duration?`${r.duration}ms`:"N/A"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Tokens Used"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.tokens_used||0})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Status"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.status})]})]})]})]},r.id)})})})},q=({logs:l,darkMode:t,searchTerm:s,setSearchTerm:n,logLevel:x,setLogLevel:m})=>{const d=r=>{switch(r){case"ERROR":return t?"text-red-400 bg-red-900/30":"text-red-700 bg-red-50";case"WARN":return t?"text-yellow-400 bg-yellow-900/30":"text-yellow-700 bg-yellow-50";case"INFO":return t?"text-blue-400 bg-blue-900/30":"text-blue-700 bg-blue-50";case"DEBUG":return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100";default:return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100"}};return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:`p-4 border-b ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx("svg",{className:`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),e.jsx("input",{type:"text",placeholder:"Search logs...",value:s,onChange:r=>n(r.target.value),className:`w-full pl-10 pr-4 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`})]}),e.jsxs("select",{value:x,onChange:r=>m(r.target.value),className:`px-3 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`,children:[e.jsx("option",{value:"ALL",children:"All Levels"}),e.jsx("option",{value:"ERROR",children:"Error"}),e.jsx("option",{value:"WARN",children:"Warning"}),e.jsx("option",{value:"INFO",children:"Info"}),e.jsx("option",{value:"DEBUG",children:"Debug"})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 custom-scrollbar",children:e.jsx("div",{className:"space-y-3",children:l.map((r,c)=>e.jsx("div",{className:`rounded-lg border p-4 transition-all duration-200 hover:shadow-md ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx("div",{className:`px-2 py-1 rounded text-xs font-bold ${d(r.level)}`,children:r.level}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.message}),e.jsxs("div",{className:"flex items-center space-x-4 mt-2",children:[e.jsx("span",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:W(r.timestamp,"HH:mm:ss.SSS")}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:r.node})]}),r.details&&e.jsx("div",{className:`mt-3 p-3 rounded ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.details,null,2)})})]})]})},c))})})]})},Q=({performance:l,darkMode:t})=>e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Execution"}),e.jsxs("div",{className:`text-2xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:[l.total_execution_time,"ms"]})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Memory Usage"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.memory_usage.current})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Tokens"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.token_usage.total})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Cost Estimate"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-yellow-400":"text-yellow-600"}`,children:l.token_usage.cost_estimate})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Node Performance"}),e.jsx("div",{className:"space-y-4",children:l.node_performance.map(s=>e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:`font-medium ${t?"text-white":"text-gray-900"}`,children:s.node}),e.jsxs("span",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[s.calls," calls"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Avg Duration"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.avg_duration,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Total Time"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.total_time,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Efficiency"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[Math.round(s.total_time/l.total_execution_time*100),"%"]})]})]})]},s.node))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Memory Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.memory_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Token Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.token_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]})]})]})}),X=({history:l,darkMode:t,checkpointIndex:s,setCheckpointIndex:n})=>{const{startGlobalExecution:x}=T(),m=u=>{x("graph",{checkpoint_id:u})},d=()=>{s>0&&n(s-1)},r=()=>{s0?Math.min(s,l.length-1):0;return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Time Travel Debugging"}),e.jsx("p",{className:`text-sm mb-2 ${t?"text-gray-400":"text-gray-600"}`,children:"Review past states and fork execution from any checkpoint."})]}),l.length>1&&e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("button",{onClick:d,disabled:c===0,className:`p-1 rounded transition-colors ${c===0?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Previous checkpoint",children:e.jsx(P,{className:"w-5 h-5"})}),e.jsxs("span",{className:`text-sm font-medium min-w-[4rem] text-center ${t?"text-gray-300":"text-gray-700"}`,children:[c+1," / ",l.length]}),e.jsx("button",{onClick:r,disabled:c>=l.length-1,className:`p-1 rounded transition-colors ${c>=l.length-1?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Next checkpoint",children:e.jsx(z,{className:"w-5 h-5"})})]})]}),l.length===0?e.jsx("div",{className:`p-8 text-center rounded-xl border ${t?"bg-gray-800 border-gray-700 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:"No history available for this thread."}):e.jsx("div",{className:"space-y-4",children:l.map((u,p)=>e.jsxs("div",{className:`p-4 rounded-xl border flex items-center justify-between ${p===c?t?"bg-blue-900/20 border-blue-700 ring-1 ring-blue-600":"bg-blue-50 border-blue-300 ring-1 ring-blue-400":t?"bg-gray-800 border-gray-700 hover:bg-gray-750":"bg-white border-gray-200 hover:bg-gray-50"} transition-colors cursor-pointer`,onClick:()=>n(p),children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${p===c?"bg-blue-600 text-white":t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:p+1}),e.jsxs("div",{children:[e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:["Checkpoint ",u.id.slice(0,8),"..."]}),e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:new Date(u.timestamp).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[Object.keys(u.state||{}).length," variables"]}),e.jsxs("button",{onClick:v=>{v.stopPropagation(),m(u.id)},className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg shadow-sm transition-colors flex items-center",children:[e.jsxs("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})]}),"Replay from here"]})]})]},u.id))})]})})};export{ee as DebugView}; +import{u as T,j as e,A as O,f as W,V as f}from"./index-BMj1jeBL.js";import{r as o,R as F}from"./react-vendor-BHJ3EV8m.js";import{F as I}from"./ClipboardDocumentIcon-Cnz7XqGa.js";import"./syntax-vendor-ru7AzRyY.js";function V({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.75 19.5 8.25 12l7.5-7.5"}))}const P=o.forwardRef(V);function H({title:l,titleId:t,...s},n){return o.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},s),l?o.createElement("title",{id:t},l):null,o.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m8.25 4.5 7.5 7.5-7.5 7.5"}))}const z=o.forwardRef(H),ee=()=>{const{graphState:l,selectedThread:t,darkMode:s,executionContext:n,selectedAgent:x,config:m}=T(),[d,r]=o.useState("state"),[c,u]=o.useState(""),[p,v]=o.useState("ALL"),[N,_]=o.useState(0),[j,w]=o.useState(null),[$,h]=o.useState([]),[b,S]=o.useState(!1),[R,L]=o.useState(void 0);o.useEffect(()=>{let a=!0;return(async()=>{if(!x?.id||!t?.id||!m?.apiUrl){w(null),h([]),L(void 0),S(!1);return}S(!0);try{const y=await new O(m.apiUrl,m.apiKey).getState(x.id,t.id);a&&(w(y),L(void 0))}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load real state, using execution context",y),a&&L(y)}try{const y=await new O(m.apiUrl,m.apiKey).getHistory(x.id,t.id);a&&h(y)}catch(g){const y=g instanceof Error?g.message:String(g);console.log("Could not load history",y),a&&L(E=>E||y)}a&&S(!1)})(),()=>{a=!1}},[x?.id,t?.id,m?.apiUrl,m?.apiKey]);const D=n.isExecuting&&n.currentState&&Object.keys(n.currentState).length>0?{...j?.state||{},...n.currentState}:void 0,A=j?{messages:t?.messages||[],current_node:l?.currentNode||j.state?.current_node||"agent",execution_path:l?.executionPath||[],variables:D||j.state||n.currentState||{},metadata:{agent_name:j.agent_name||x?.name||"unknown",thread_id:j.thread_id||t?.id||"unknown",checkpoint_id:j.checkpoint_id||null,timestamp:j.timestamp||new Date().toISOString()}}:{messages:t?.messages||[],current_node:l?.currentNode||"agent",execution_path:l?.executionPath||[],variables:D||n.currentState||{},metadata:{agent_name:x?.name||"unknown",thread_id:t?.id||"unknown",timestamp:new Date().toISOString()}},C=n.logs.filter(a=>a.type==="input"||a.type==="output").reduce((a,i,g)=>{const y=a.find(E=>E.node===i.nodeId);return y?i.type==="output"&&(y.status="completed",y.output=i.data?.output||i.data,y.duration=i.duration||null):a.push({id:i.id||`step_${g}`,node:i.nodeId,status:i.type==="output"?"completed":i.type==="error"?"error":"running",input:i.type==="input"?i.data?.input||i.data:null,output:i.type==="output"?i.data?.output||i.data:null,timestamp:i.timestamp,duration:i.duration||null,tokens_used:0}),a},[]),B=n.logs.map(a=>({level:a.type==="error"?"ERROR":a.type==="debug"?"DEBUG":(a.type==="info","INFO"),message:a.message,timestamp:a.timestamp,node:a.nodeId,details:a.data||{}})),J={total_execution_time:n.startTime&&n.endTime?n.endTime.getTime()-n.startTime.getTime():n.startTime?Date.now()-n.startTime.getTime():0,node_performance:Object.entries(n.logs.reduce((a,i)=>(i.duration!==void 0&&(a[i.nodeId]||(a[i.nodeId]={total:0,count:0}),a[i.nodeId].total+=i.duration,a[i.nodeId].count+=1),a),{})).map(([a,i])=>({node:a,avg_duration:Number((i.total/i.count).toFixed(2)),calls:i.count,total_time:Number(i.total.toFixed(2))})),memory_usage:{current:"N/A",peak:"N/A",average:"N/A"},token_usage:n.logs.reduce((a,i)=>{const g=i.data?.output?.metadata?.tokens_used||i.data?.metadata?.tokens_used||0;return g&&(a.total+=g),a},{total:0,input:0,output:0,cost_estimate:"$0.00"})},U=B.filter(a=>{const i=a.message.toLowerCase().includes(c.toLowerCase())||a.node.toLowerCase().includes(c.toLowerCase()),g=p==="ALL"||a.level===p;return i&&g});return e.jsxs("div",{className:`h-full flex flex-col transition-all duration-300 ${s?"bg-gray-900":"bg-gray-50"}`,children:[R&&e.jsxs("div",{className:`px-4 py-3 text-sm border-b ${s?"bg-red-900/40 border-red-700 text-red-200":"bg-red-50 border-red-200 text-red-800"}`,role:"alert",children:[e.jsx("strong",{children:"Debug load error:"})," ",R]}),e.jsxs("div",{className:`relative overflow-hidden ${s?"bg-gradient-to-r from-gray-800 via-gray-700 to-gray-800":"bg-gradient-to-r from-blue-50 via-white to-purple-50"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),e.jsx("div",{className:"relative border-b border-gray-200 p-4 sm:p-6 dark:border-gray-700",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center space-x-3 sm:space-x-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${s?"bg-blue-600/20 text-blue-400":"bg-blue-100 text-blue-600"}`,children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}),e.jsxs("div",{children:[e.jsx("h2",{className:`text-xl font-bold sm:text-2xl ${s?"text-white":"text-gray-900"}`,children:"Debug Console"}),e.jsx("p",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:"Real-time graph execution monitoring and analysis"})]})]}),e.jsxs("div",{className:"hidden items-center space-x-3 sm:flex",children:[e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full animate-pulse ${b?"bg-amber-500":"bg-green-500"}`}),e.jsx("span",{className:`text-sm font-medium ${s?"text-gray-300":"text-gray-700"}`,children:b?"Loading state…":"Live"})]}),e.jsx("div",{className:`px-3 py-2 rounded-lg ${s?"bg-gray-700/50":"bg-white/50"} backdrop-blur-sm`,children:e.jsxs("span",{className:`text-sm ${s?"text-gray-400":"text-gray-600"}`,children:[C.filter(a=>a.status==="completed").length,"/",C.length," Steps"]})})]})]})})]}),e.jsx("div",{className:`border-b ${s?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsx("div",{className:"overflow-x-auto px-3 sm:px-6",children:e.jsx("nav",{className:"flex min-w-max space-x-5 sm:space-x-8",children:[{id:"state",label:"State",icon:"🔍",count:Object.keys(A.variables).length},{id:"history",label:"Time Travel",icon:"⏪",count:$.length},{id:"steps",label:"Steps",icon:"📋",count:C.length},{id:"logs",label:"Logs",icon:"📝",count:U.length},{id:"performance",label:"Performance",icon:"⚡",count:J.node_performance.length}].map(a=>e.jsx("button",{onClick:()=>r(a.id),className:`relative py-4 px-1 font-medium text-sm transition-all duration-200 ${d===a.id?s?"text-blue-400 border-b-2 border-blue-400":"text-blue-600 border-b-2 border-blue-500":s?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{children:a.icon}),e.jsx("span",{children:a.label}),e.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${d===a.id?s?"bg-blue-600 text-white":"bg-blue-100 text-blue-600":s?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-600"}`,children:a.count})]})},a.id))})})}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[d==="state"&&e.jsx(G,{state:A,darkMode:s,isExecuting:n.isExecuting,onStateUpdated:w}),d==="history"&&e.jsx(X,{history:$,darkMode:s,checkpointIndex:N,setCheckpointIndex:_}),d==="steps"&&e.jsx(K,{steps:C,darkMode:s}),d==="logs"&&e.jsx(q,{logs:U,darkMode:s,searchTerm:c,setSearchTerm:u,logLevel:p,setLogLevel:v}),d==="performance"&&e.jsx(Q,{performance:J,darkMode:s})]})]})},G=({state:l,darkMode:t,isExecuting:s,onStateUpdated:n})=>{const[x,m]=o.useState(new Set(["variables"])),[d,r]=o.useState(!1),[c,u]=o.useState(""),{selectedAgent:p,selectedThread:v,config:N}=T(),_=async()=>{try{await navigator.clipboard.writeText(JSON.stringify(l.variables,null,2)),f.success("State JSON copied to clipboard")}catch{f.error("Failed to copy to clipboard")}},j=()=>{u(JSON.stringify(l.variables,null,2)),r(!0)},w=async()=>{let h;try{h=JSON.parse(c)}catch{f.error("State must be valid JSON");return}if(!p||!v||!N?.apiUrl){f.error("Select an agent and thread before editing state");return}try{const S=await new O(N.apiUrl,N.apiKey).updateState(p.id,v.id,h);n(S),r(!1),f.success("State updated")}catch(b){f.error(b instanceof Error?b.message:"Failed to update state")}},$=h=>{const b=new Set(x);b.has(h)?b.delete(h):b.add(h),m(b)};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("h3",{className:`text-lg font-semibold mb-4 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("svg",{className:"w-5 h-5 mr-2 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Execution Overview",s&&e.jsxs("span",{className:"ml-3 flex items-center space-x-2",children:[e.jsxs("span",{className:"relative flex h-3 w-3",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-green-500"})]}),e.jsx("span",{className:`text-xs font-normal ${t?"text-green-400":"text-green-600"}`,children:"Live updating"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Current Node"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:l.current_node})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Steps Completed"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.execution_path?.length||0})]}),e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Messages"}),e.jsx("div",{className:`text-xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.messages?.length||0})]})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Execution Path"}),e.jsx("div",{className:"flex items-center space-x-2 flex-wrap gap-2",children:l.execution_path?.map((h,b)=>e.jsxs(F.Fragment,{children:[e.jsxs("div",{className:`flex items-center px-4 py-2 rounded-lg border-2 ${t?"bg-blue-600 border-blue-500 text-white":"bg-blue-50 border-blue-200 text-blue-700"}`,children:[e.jsx("span",{className:`w-6 h-6 rounded-full flex items-center justify-center mr-2 text-xs font-bold ${t?"bg-blue-500":"bg-blue-200"}`,children:b+1}),h]}),br(!1),className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Cancel"})]}):e.jsx("button",{onClick:j,className:`px-3 py-1 text-xs rounded border ${t?"bg-gray-700 border-gray-600 text-gray-200":"bg-white border-gray-300 text-gray-700"}`,children:"Edit State"})]}),e.jsx("button",{onClick:()=>$("variables"),children:e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("variables")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]}),x.has("variables")&&e.jsx("div",{className:`mx-6 mb-6 p-4 rounded-lg overflow-x-auto ${t?"bg-gray-900":"bg-gray-50"}`,children:d?e.jsx("textarea",{"aria-label":"Edit state JSON",className:`w-full h-64 p-2 font-mono text-sm rounded ${t?"bg-gray-800 text-green-400":"bg-white text-green-600"}`,value:c,onChange:h=>u(h.target.value)}):e.jsx("pre",{className:`text-sm font-mono ${t?"text-green-400":"text-green-600"}`,children:JSON.stringify(l.variables,null,2)})})]}),e.jsxs("div",{className:`rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsxs("button",{onClick:()=>$("metadata"),className:`w-full p-6 text-left flex items-center justify-between ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Metadata"}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${x.has("metadata")?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),x.has("metadata")&&e.jsx("div",{className:"px-6 pb-6",children:e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(l.metadata,null,2)})})})]})]})})},K=({steps:l,darkMode:t})=>{const[s,n]=o.useState(new Set),x=r=>{const c=new Set(s);c.has(r)?c.delete(r):c.add(r),n(c)},m=r=>{switch(r){case"completed":return"text-green-600 bg-green-100 border-green-200";case"running":return"text-blue-600 bg-blue-100 border-blue-200";case"error":return"text-red-600 bg-red-100 border-red-200";default:return"text-gray-600 bg-gray-100 border-gray-200"}},d=r=>{switch(r){case"completed":return"text-green-400 bg-green-900/30 border-green-700";case"running":return"text-blue-400 bg-blue-900/30 border-blue-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsx("div",{className:"max-w-4xl mx-auto space-y-4",children:l.map((r,c)=>{const u=s.has(r.id),p=t?d(r.status):m(r.status);return e.jsxs("div",{className:`rounded-xl border transition-all duration-200 ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"} hover:shadow-lg`,children:[e.jsx("button",{onClick:()=>x(r.id),className:`w-full p-6 text-left ${t?"hover:bg-gray-700":"hover:bg-gray-50"} transition-colors rounded-t-xl`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`flex items-center justify-center w-10 h-10 rounded-full font-bold ${t?"bg-blue-600 text-white":"bg-blue-100 text-blue-600"}`,children:c+1}),e.jsxs("div",{children:[e.jsx("h4",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:r.node}),e.jsxs("p",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:["Step ID: ",r.id]})]})]}),e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`px-3 py-1 rounded-full text-sm font-medium border ${p}`,children:r.status}),r.duration&&e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-500"}`,children:[r.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform ${u?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}),u&&e.jsxs("div",{className:`px-6 pb-6 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6",children:[r.input&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Input Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.input,null,2)})})]}),r.output&&e.jsxs("div",{children:[e.jsx("h5",{className:`text-sm font-semibold mb-3 ${t?"text-gray-300":"text-gray-700"}`,children:"Output Data"}),e.jsx("div",{className:`rounded-lg p-4 ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-sm font-mono whitespace-pre-wrap ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.output,null,2)})})]})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Timestamp"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.timestamp?W(r.timestamp,"HH:mm:ss.SSS"):"Pending"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Duration"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.duration?`${r.duration}ms`:"N/A"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Tokens Used"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.tokens_used||0})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-600"}`,children:"Status"}),e.jsx("div",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.status})]})]})]})]},r.id)})})})},q=({logs:l,darkMode:t,searchTerm:s,setSearchTerm:n,logLevel:x,setLogLevel:m})=>{const d=r=>{switch(r){case"ERROR":return t?"text-red-400 bg-red-900/30":"text-red-700 bg-red-50";case"WARN":return t?"text-yellow-400 bg-yellow-900/30":"text-yellow-700 bg-yellow-50";case"INFO":return t?"text-blue-400 bg-blue-900/30":"text-blue-700 bg-blue-50";case"DEBUG":return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100";default:return t?"text-gray-400 bg-gray-800":"text-gray-700 bg-gray-100"}};return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:`p-4 border-b ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx("svg",{className:`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),e.jsx("input",{type:"text",placeholder:"Search logs...",value:s,onChange:r=>n(r.target.value),className:`w-full pl-10 pr-4 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`})]}),e.jsxs("select",{value:x,onChange:r=>m(r.target.value),className:`px-3 py-2 rounded-lg border ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} focus:ring-2 focus:ring-blue-500 focus:border-transparent`,children:[e.jsx("option",{value:"ALL",children:"All Levels"}),e.jsx("option",{value:"ERROR",children:"Error"}),e.jsx("option",{value:"WARN",children:"Warning"}),e.jsx("option",{value:"INFO",children:"Info"}),e.jsx("option",{value:"DEBUG",children:"Debug"})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 custom-scrollbar",children:e.jsx("div",{className:"space-y-3",children:l.map((r,c)=>e.jsx("div",{className:`rounded-lg border p-4 transition-all duration-200 hover:shadow-md ${t?"border-gray-700 bg-gray-800":"border-gray-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx("div",{className:`px-2 py-1 rounded text-xs font-bold ${d(r.level)}`,children:r.level}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${t?"text-gray-200":"text-gray-900"}`,children:r.message}),e.jsxs("div",{className:"flex items-center space-x-4 mt-2",children:[e.jsx("span",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:W(r.timestamp,"HH:mm:ss.SSS")}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:r.node})]}),r.details&&e.jsx("div",{className:`mt-3 p-3 rounded ${t?"bg-gray-700":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-700"}`,children:JSON.stringify(r.details,null,2)})})]})]})},c))})})]})},Q=({performance:l,darkMode:t})=>e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Execution"}),e.jsxs("div",{className:`text-2xl font-bold ${t?"text-blue-400":"text-blue-600"}`,children:[l.total_execution_time,"ms"]})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Memory Usage"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-green-400":"text-green-600"}`,children:l.memory_usage.current})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Total Tokens"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-purple-400":"text-purple-600"}`,children:l.token_usage.total})]}),e.jsxs("div",{className:`p-6 rounded-xl border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:"Cost Estimate"}),e.jsx("div",{className:`text-2xl font-bold ${t?"text-yellow-400":"text-yellow-600"}`,children:l.token_usage.cost_estimate})]})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Node Performance"}),e.jsx("div",{className:"space-y-4",children:l.node_performance.map(s=>e.jsxs("div",{className:`p-4 rounded-lg ${t?"bg-gray-700":"bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:`font-medium ${t?"text-white":"text-gray-900"}`,children:s.node}),e.jsxs("span",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[s.calls," calls"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Avg Duration"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.avg_duration,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Total Time"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[s.total_time,"ms"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:`${t?"text-gray-400":"text-gray-600"}`,children:"Efficiency"}),e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:[Math.round(s.total_time/l.total_execution_time*100),"%"]})]})]})]},s.node))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Memory Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.memory_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]}),e.jsxs("div",{className:`rounded-xl border p-6 ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("h3",{className:`text-lg font-semibold mb-4 ${t?"text-white":"text-gray-900"}`,children:"Token Usage"}),e.jsx("div",{className:"space-y-3",children:Object.entries(l.token_usage).map(([s,n])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:`${t?"text-gray-400":"text-gray-600"} capitalize`,children:s.replace("_"," ")}),e.jsx("span",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:String(n)})]},s))})]})]})]})}),X=({history:l,darkMode:t,checkpointIndex:s,setCheckpointIndex:n})=>{const{startGlobalExecution:x}=T(),m=u=>{x("graph",{checkpoint_id:u})},d=()=>{s>0&&n(s-1)},r=()=>{s0?Math.min(s,l.length-1):0;return e.jsx("div",{className:"h-full overflow-y-auto p-6 custom-scrollbar",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:`text-lg font-semibold ${t?"text-white":"text-gray-900"}`,children:"Time Travel Debugging"}),e.jsx("p",{className:`text-sm mb-2 ${t?"text-gray-400":"text-gray-600"}`,children:"Review past states and fork execution from any checkpoint."})]}),l.length>1&&e.jsxs("div",{className:`flex items-center space-x-2 px-3 py-2 rounded-lg border ${t?"bg-gray-800 border-gray-700":"bg-white border-gray-200"}`,children:[e.jsx("button",{onClick:d,disabled:c===0,className:`p-1 rounded transition-colors ${c===0?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Previous checkpoint",children:e.jsx(P,{className:"w-5 h-5"})}),e.jsxs("span",{className:`text-sm font-medium min-w-[4rem] text-center ${t?"text-gray-300":"text-gray-700"}`,children:[c+1," / ",l.length]}),e.jsx("button",{onClick:r,disabled:c>=l.length-1,className:`p-1 rounded transition-colors ${c>=l.length-1?t?"text-gray-600 cursor-not-allowed":"text-gray-300 cursor-not-allowed":t?"text-gray-300 hover:bg-gray-700":"text-gray-600 hover:bg-gray-100"}`,title:"Next checkpoint",children:e.jsx(z,{className:"w-5 h-5"})})]})]}),l.length===0?e.jsx("div",{className:`p-8 text-center rounded-xl border ${t?"bg-gray-800 border-gray-700 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:"No history available for this thread."}):e.jsx("div",{className:"space-y-4",children:l.map((u,p)=>e.jsxs("div",{className:`p-4 rounded-xl border flex items-center justify-between ${p===c?t?"bg-blue-900/20 border-blue-700 ring-1 ring-blue-600":"bg-blue-50 border-blue-300 ring-1 ring-blue-400":t?"bg-gray-800 border-gray-700 hover:bg-gray-750":"bg-white border-gray-200 hover:bg-gray-50"} transition-colors cursor-pointer`,onClick:()=>n(p),children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${p===c?"bg-blue-600 text-white":t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:p+1}),e.jsxs("div",{children:[e.jsxs("div",{className:`font-medium ${t?"text-gray-200":"text-gray-900"}`,children:["Checkpoint ",u.id.slice(0,8),"..."]}),e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:new Date(u.timestamp).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("div",{className:`text-sm ${t?"text-gray-400":"text-gray-600"}`,children:[Object.keys(u.state||{}).length," variables"]}),e.jsxs("button",{onClick:v=>{v.stopPropagation(),m(u.id)},className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg shadow-sm transition-colors flex items-center",children:[e.jsxs("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})]}),"Replay from here"]})]})]},u.id))})]})})};export{ee as DebugView}; diff --git a/src/agentomatic/studio/static/assets/EndpointsView-fCUdmgxr.js b/src/agentomatic/studio/static/assets/EndpointsView-DqDGXNuG.js similarity index 97% rename from src/agentomatic/studio/static/assets/EndpointsView-fCUdmgxr.js rename to src/agentomatic/studio/static/assets/EndpointsView-DqDGXNuG.js index b2ed5a64..85166d10 100644 --- a/src/agentomatic/studio/static/assets/EndpointsView-fCUdmgxr.js +++ b/src/agentomatic/studio/static/assets/EndpointsView-DqDGXNuG.js @@ -1 +1 @@ -import{u as V,A as U,d as M,j as e}from"./index-FSSL6O5F.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as B}from"./SchemaForm-DyHc2s7z.js";import{O as H}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const y=(l,a)=>`${l}:${a.toUpperCase()}`,g=l=>l.methods.map(a=>a.toUpperCase()).filter((a,u,f)=>!!a&&f.indexOf(a)===u),T=l=>g(l).includes("POST")?"POST":g(l)[0]||"POST",Q=()=>{const{config:l,darkMode:a}=V(),[u,f]=d.useState([]),[p,P]=d.useState({}),[j,R]=d.useState({}),[F,E]=d.useState({}),[_,C]=d.useState({}),[v,k]=d.useState(null),[O,A]=d.useState({}),[b,N]=d.useState(!0),[w,h]=d.useState(null),$=d.useCallback(async()=>{if(!l?.apiUrl){N(!1);return}N(!0);try{const s=new U(l.apiUrl,l.apiKey||void 0),o=await s.listEndpoints(),n=await Promise.all(o.flatMap(t=>g(t).map(async c=>{const S=`/api/v1/endpoints/${encodeURIComponent(t.name)}${t.path}`,x=y(t.name,c);try{return{key:x,contract:await s.getOperationContract(S,c),error:null}}catch(K){return{key:x,contract:null,error:K?.message||`Could not load ${c} contract`}}}))),i=Object.fromEntries(n.flatMap(t=>t.contract?[[t.key,t.contract]]:[])),r=Object.fromEntries(n.flatMap(t=>t.error?[[t.key,t.error]]:[]));f(o),P(i),R(r),C(t=>Object.fromEntries(o.map(c=>[c.name,g(c).includes(t[c.name])?t[c.name]:T(c)]))),E(t=>Object.fromEntries(o.flatMap(c=>g(c).map(S=>{const x=y(c.name,S);return[x,t[x]??M(i[x]?.input_schema||void 0)]})))),h(null)}catch(s){h(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch endpoints")}finally{N(!1)}},[l?.apiUrl,l?.apiKey]);d.useEffect(()=>{$()},[$]);const I=async(s,o,n)=>{if(!l?.apiUrl)return;const i=y(s.name,o);k(i),h(null);try{const t=await new U(l.apiUrl,l.apiKey||void 0).callEndpoint(s.name,s.path,n,o,p[i]);A(c=>({...c,[i]:t}))}catch(r){h(r?.message||`Failed to call endpoint '${s.name}'`)}finally{k(null)}},L=a?"bg-gray-800 border-gray-700":"bg-white border-gray-200",m=a?"text-gray-400":"text-gray-600";return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${a?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Custom Endpoints"}),e.jsx("p",{className:`mt-1 text-sm ${m}`,children:"Live callable APIs. Forms and expected output are generated from each endpoint's registered OpenAPI contract."})]}),e.jsx("button",{type:"button",onClick:()=>{$()},disabled:b||v!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:b?"Refreshing…":"Refresh"})]}),b&&e.jsx("div",{className:m,children:"Loading endpoints…"}),w&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${a?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:w}),!b&&!w&&u.length===0&&e.jsx("div",{className:m,children:"No custom endpoints registered."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:u.map(s=>e.jsx("div",{className:`p-6 rounded-xl border ${L} shadow-sm`,children:(()=>{const o=_[s.name]||T(s),n=y(s.name,o),i=g(s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:s.name}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${s.ready?"bg-green-500":"bg-gray-400"}`}),s.ready?"Ready":"Idle"]})]}),e.jsx("p",{className:`text-sm mb-4 ${m}`,children:s.description||"No description provided"}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[i.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-gray-700 text-gray-200":"bg-gray-100 text-gray-700"}`,children:r},r)),e.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-violet-900 text-violet-200":"bg-violet-100 text-violet-800"}`,children:["/api/v1/endpoints/",s.name,s.path]})]}),e.jsxs("dl",{className:"text-sm space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Aggregation"}),e.jsx("dd",{className:"font-medium",children:s.aggregation||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Upstreams"}),e.jsx("dd",{className:"font-medium",children:s.upstreams.length})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Version"}),e.jsxs("dd",{className:"font-medium",children:["v",s.version]})]})]}),s.upstreams.length>0&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700",children:[e.jsx("div",{className:`text-xs mb-2 ${m}`,children:"Upstreams"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.upstreams.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs ${a?"bg-gray-700":"bg-gray-100"}`,children:r},r))})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[i.length>1&&e.jsxs("label",{className:"block text-sm font-medium",children:["Method",e.jsx("select",{"aria-label":`HTTP method for ${s.name}`,value:o,onChange:r=>C(t=>({...t,[s.name]:r.target.value})),className:`mt-1 block w-full rounded-lg border px-3 py-2 text-sm ${a?"border-gray-600 bg-gray-900 text-white":"border-gray-300 bg-white text-gray-900"}`,children:i.map(r=>e.jsx("option",{value:r,children:r},r))})]}),j[n]&&e.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${a?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live ",o," contract unavailable: ",j[n],". Testing stays disabled until the deployed schema can be read."]}),e.jsx(B,{schema:p[n]?.input_schema,value:F[n]??M(p[n]?.input_schema||void 0),onChange:r=>E(t=>({...t,[n]:r})),onSubmit:r=>{I(s,o,r)},submitLabel:v===n?`Calling ${o}…`:`Test ${o}`,disabled:v!==null||!s.ready||!!j[n],darkMode:a}),e.jsx(H,{schema:p[n]?.output_schema,darkMode:a})]}),O[n]!==void 0&&e.jsx("pre",{className:`mt-4 overflow-x-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${a?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(O[n],null,2)})]})})()},s.name))})]})};export{Q as EndpointsView}; +import{u as V,A as U,d as M,j as e}from"./index-BMj1jeBL.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as B}from"./SchemaForm-Kr1WPDMd.js";import{O as H}from"./OutputSchemaSummary-CiE3pU-0.js";import"./syntax-vendor-ru7AzRyY.js";const y=(l,a)=>`${l}:${a.toUpperCase()}`,g=l=>l.methods.map(a=>a.toUpperCase()).filter((a,u,f)=>!!a&&f.indexOf(a)===u),T=l=>g(l).includes("POST")?"POST":g(l)[0]||"POST",Q=()=>{const{config:l,darkMode:a}=V(),[u,f]=d.useState([]),[p,P]=d.useState({}),[j,R]=d.useState({}),[F,E]=d.useState({}),[_,C]=d.useState({}),[v,k]=d.useState(null),[O,A]=d.useState({}),[b,N]=d.useState(!0),[w,h]=d.useState(null),$=d.useCallback(async()=>{if(!l?.apiUrl){N(!1);return}N(!0);try{const s=new U(l.apiUrl,l.apiKey||void 0),o=await s.listEndpoints(),n=await Promise.all(o.flatMap(t=>g(t).map(async c=>{const S=`/api/v1/endpoints/${encodeURIComponent(t.name)}${t.path}`,x=y(t.name,c);try{return{key:x,contract:await s.getOperationContract(S,c),error:null}}catch(K){return{key:x,contract:null,error:K?.message||`Could not load ${c} contract`}}}))),i=Object.fromEntries(n.flatMap(t=>t.contract?[[t.key,t.contract]]:[])),r=Object.fromEntries(n.flatMap(t=>t.error?[[t.key,t.error]]:[]));f(o),P(i),R(r),C(t=>Object.fromEntries(o.map(c=>[c.name,g(c).includes(t[c.name])?t[c.name]:T(c)]))),E(t=>Object.fromEntries(o.flatMap(c=>g(c).map(S=>{const x=y(c.name,S);return[x,t[x]??M(i[x]?.input_schema||void 0)]})))),h(null)}catch(s){h(s?.status===404?"Control plane is not enabled (start with enable_control_plane=True).":s?.message||"Failed to fetch endpoints")}finally{N(!1)}},[l?.apiUrl,l?.apiKey]);d.useEffect(()=>{$()},[$]);const I=async(s,o,n)=>{if(!l?.apiUrl)return;const i=y(s.name,o);k(i),h(null);try{const t=await new U(l.apiUrl,l.apiKey||void 0).callEndpoint(s.name,s.path,n,o,p[i]);A(c=>({...c,[i]:t}))}catch(r){h(r?.message||`Failed to call endpoint '${s.name}'`)}finally{k(null)}},L=a?"bg-gray-800 border-gray-700":"bg-white border-gray-200",m=a?"text-gray-400":"text-gray-600";return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${a?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Custom Endpoints"}),e.jsx("p",{className:`mt-1 text-sm ${m}`,children:"Live callable APIs. Forms and expected output are generated from each endpoint's registered OpenAPI contract."})]}),e.jsx("button",{type:"button",onClick:()=>{$()},disabled:b||v!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:b?"Refreshing…":"Refresh"})]}),b&&e.jsx("div",{className:m,children:"Loading endpoints…"}),w&&e.jsx("div",{role:"alert",className:`p-4 rounded-lg border mb-4 ${a?"bg-red-900/30 border-red-800 text-red-200":"bg-red-50 border-red-200 text-red-700"}`,children:w}),!b&&!w&&u.length===0&&e.jsx("div",{className:m,children:"No custom endpoints registered."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:u.map(s=>e.jsx("div",{className:`p-6 rounded-xl border ${L} shadow-sm`,children:(()=>{const o=_[s.name]||T(s),n=y(s.name,o),i=g(s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:s.name}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${s.ready?"bg-green-500":"bg-gray-400"}`}),s.ready?"Ready":"Idle"]})]}),e.jsx("p",{className:`text-sm mb-4 ${m}`,children:s.description||"No description provided"}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[i.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-gray-700 text-gray-200":"bg-gray-100 text-gray-700"}`,children:r},r)),e.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-mono ${a?"bg-violet-900 text-violet-200":"bg-violet-100 text-violet-800"}`,children:["/api/v1/endpoints/",s.name,s.path]})]}),e.jsxs("dl",{className:"text-sm space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Aggregation"}),e.jsx("dd",{className:"font-medium",children:s.aggregation||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Upstreams"}),e.jsx("dd",{className:"font-medium",children:s.upstreams.length})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:m,children:"Version"}),e.jsxs("dd",{className:"font-medium",children:["v",s.version]})]})]}),s.upstreams.length>0&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700",children:[e.jsx("div",{className:`text-xs mb-2 ${m}`,children:"Upstreams"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.upstreams.map(r=>e.jsx("span",{className:`px-2 py-0.5 rounded text-xs ${a?"bg-gray-700":"bg-gray-100"}`,children:r},r))})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[i.length>1&&e.jsxs("label",{className:"block text-sm font-medium",children:["Method",e.jsx("select",{"aria-label":`HTTP method for ${s.name}`,value:o,onChange:r=>C(t=>({...t,[s.name]:r.target.value})),className:`mt-1 block w-full rounded-lg border px-3 py-2 text-sm ${a?"border-gray-600 bg-gray-900 text-white":"border-gray-300 bg-white text-gray-900"}`,children:i.map(r=>e.jsx("option",{value:r,children:r},r))})]}),j[n]&&e.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${a?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live ",o," contract unavailable: ",j[n],". Testing stays disabled until the deployed schema can be read."]}),e.jsx(B,{schema:p[n]?.input_schema,value:F[n]??M(p[n]?.input_schema||void 0),onChange:r=>E(t=>({...t,[n]:r})),onSubmit:r=>{I(s,o,r)},submitLabel:v===n?`Calling ${o}…`:`Test ${o}`,disabled:v!==null||!s.ready||!!j[n],darkMode:a}),e.jsx(H,{schema:p[n]?.output_schema,darkMode:a})]}),O[n]!==void 0&&e.jsx("pre",{className:`mt-4 overflow-x-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${a?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(O[n],null,2)})]})})()},s.name))})]})};export{Q as EndpointsView}; diff --git a/src/agentomatic/studio/static/assets/GraphView-CMqOwCTc.js b/src/agentomatic/studio/static/assets/GraphView-CxhhCL_h.js similarity index 99% rename from src/agentomatic/studio/static/assets/GraphView-CMqOwCTc.js rename to src/agentomatic/studio/static/assets/GraphView-CxhhCL_h.js index a84fb94b..b00c24ad 100644 --- a/src/agentomatic/studio/static/assets/GraphView-CMqOwCTc.js +++ b/src/agentomatic/studio/static/assets/GraphView-CxhhCL_h.js @@ -1,4 +1,4 @@ -import{u as V,j as e,d as Ne,a as we,V as ce}from"./index-FSSL6O5F.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";import{S as $e}from"./SchemaForm-DyHc2s7z.js";import{O as Se}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const Ce=({nodeId:i,logs:t,darkMode:n,position:o,onClose:f})=>{const b=t.filter(w=>w.nodeId===i);if(b.length===0)return null;const N=b[b.length-1];return e.jsx("div",{className:"fixed z-50 pointer-events-none",style:{left:o.x+20,top:o.y-10,maxWidth:"400px"},children:e.jsxs("div",{className:`rounded-lg shadow-xl border p-4 pointer-events-auto ${n?"bg-gray-800 border-gray-600 text-white":"bg-white border-gray-200 text-gray-900"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-semibold text-sm",children:"Node Execution Details"}),e.jsx("button",{onClick:f,className:`text-xs px-2 py-1 rounded ${n?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,children:"✕"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Latest Execution"}),e.jsx("div",{className:"text-sm",children:N.message}),e.jsx("div",{className:`text-xs mt-1 ${n?"text-gray-500":"text-gray-400"}`,children:N.timestamp.toLocaleString()})]}),N.data?.intermediate_results&&e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium mb-2 ${n?"text-gray-400":"text-gray-500"}`,children:"Results Preview"}),e.jsx("div",{className:`text-xs p-2 rounded font-mono ${n?"bg-gray-900 text-gray-300":"bg-gray-50 text-gray-700"}`,children:Object.keys(N.data.intermediate_results).length>0?e.jsx("div",{children:Object.entries(N.data.intermediate_results).map(([w,m])=>e.jsxs("div",{className:"mb-1",children:[e.jsxs("span",{className:"font-semibold",children:[w,":"]})," ",typeof m=="object"&&m!==null&&"response"in m?`"${m.response?.substring(0,50)}..."`:JSON.stringify(m).substring(0,50)+"..."]},w))}):"No results available"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-gray-200 dark:border-gray-600",children:[e.jsxs("span",{className:`text-xs ${n?"text-gray-400":"text-gray-500"}`,children:[b.length," total execution",b.length!==1?"s":""]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:"Click node to view all logs"})]})]})]})})},Le=({node:i,isSelected:t,isActive:n,isHighlighted:o,hasBreakpoint:f,onClick:b,onBreakpointToggle:N,canManageBreakpoints:w,logs:m,onShowLogTooltip:d,onHideLogTooltip:_})=>{const{darkMode:l}=V(),y=m.filter(C=>C.nodeId===i.id),r=y.length>0,x=C=>{if(r){const a=C.currentTarget.getBoundingClientRect();d(i.id,{x:a.right,y:a.top})}},h=()=>{r&&_()},u=((C,a)=>{const L={start:{bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",text:l?"#bfdbfe":"#1e40af",indicator:"#3b82f6",icon:"🚀"},end:{bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",text:l?"#fecaca":"#991b1b",indicator:"#ef4444",icon:"🏁"},agent:{bg:l?"#581c87":"#f3e8ff",border:"#8b5cf6",text:l?"#ddd6fe":"#6b21a8",indicator:"#8b5cf6",icon:"🤖"},tool:{bg:l?"#14532d":"#dcfce7",border:"#10b981",text:l?"#bbf7d0":"#065f46",indicator:"#10b981",icon:"🔧"},human:{bg:l?"#92400e":"#fef3c7",border:"#f59e0b",text:l?"#fde68a":"#92400e",indicator:"#f59e0b",icon:"👤"},condition:{bg:l?"#7c2d12":"#fed7aa",border:"#ea580c",text:l?"#fed7aa":"#9a3412",indicator:"#ea580c",icon:"🔀"},retrieval:{bg:l?"#164e63":"#cffafe",border:"#0891b2",text:l?"#a5f3fc":"#164e63",indicator:"#0891b2",icon:"🔍"},processing:{bg:l?"#4c1d95":"#ede9fe",border:"#7c3aed",text:l?"#c4b5fd":"#4c1d95",indicator:"#7c3aed",icon:"⚙️"},generation:{bg:l?"#be185d":"#fce7f3",border:"#ec4899",text:l?"#fbcfe8":"#be185d",indicator:"#ec4899",icon:"✨"},validation:{bg:l?"#365314":"#ecfccb",border:"#65a30d",text:l?"#d9f99d":"#365314",indicator:"#65a30d",icon:"✅"},default:{bg:l?"#374151":"#f9fafb",border:l?"#6b7280":"#d1d5db",text:l?"#e5e7eb":"#374151",indicator:l?"#9ca3af":"#6b7280",icon:"📦"}},j=L[C]||L.default;return a==="running"?{...j,bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",indicator:"#3b82f6"}:a==="completed"?{...j,bg:l?"#14532d":"#dcfce7",border:"#10b981",indicator:"#10b981"}:a==="error"?{...j,bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",indicator:"#ef4444"}:a==="paused"?{...j,bg:l?"#92400e":"#fef3c7",border:"#f59e0b",indicator:"#f59e0b"}:j})(i.type,i.data.status),S=160,p=100;return e.jsxs("g",{transform:`translate(${i.position.x}, ${i.position.y})`,className:"cursor-pointer graph-node-group",onMouseEnter:x,onMouseLeave:h,children:[e.jsxs("defs",{children:[e.jsx("filter",{id:`shadow-${i.id}`,x:"-20%",y:"-20%",width:"140%",height:"140%",children:e.jsx("feDropShadow",{dx:"0",dy:"3",stdDeviation:"4",floodColor:l?"rgba(0,0,0,0.5)":"rgba(0,0,0,0.15)",floodOpacity:"1"})}),e.jsxs("linearGradient",{id:`gradient-${i.id}`,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:u.bg,stopOpacity:"1"}),e.jsx("stop",{offset:"100%",stopColor:u.bg,stopOpacity:"0.8"})]})]}),w&&e.jsxs("g",{className:"cursor-pointer",onClick:C=>{C.stopPropagation(),N(i.id)},children:[e.jsx("title",{children:f?"Remove breakpoint":"Add breakpoint"}),e.jsx("circle",{cx:-8,cy:8,r:7,fill:f?"#ef4444":l?"#374151":"#ffffff",stroke:f?"#fecaca":"#9ca3af",strokeWidth:2}),!f&&e.jsx("path",{d:"M-11 8h6M-8 5v6",stroke:"#6b7280",strokeWidth:1.5,strokeLinecap:"round"})]}),r&&e.jsx("circle",{cx:S-8,cy:8,r:8,fill:l?"#3b82f6":"#2563eb",stroke:l?"#1f2937":"#ffffff",strokeWidth:2,className:"cursor-pointer animate-pulse"}),r&&e.jsx("text",{x:S-8,y:8,textAnchor:"middle",dominantBaseline:"central",fontSize:"10",fill:"white",className:"pointer-events-none font-bold",children:"ℹ️"}),n&&e.jsx("rect",{width:S+12,height:p+12,x:-6,y:-6,rx:20,fill:u.indicator,opacity:"0.2",className:"animate-pulse"}),o&&e.jsx("rect",{width:S+16,height:p+16,x:-8,y:-8,rx:22,fill:"none",stroke:"#f59e0b",strokeWidth:3,strokeDasharray:"12,6",className:"animate-pulse",opacity:"0.8"}),e.jsx("rect",{width:S,height:p,rx:16,fill:`url(#gradient-${i.id})`,stroke:u.border,strokeWidth:t?3:o?2.5:2,filter:`url(#shadow-${i.id})`,onClick:()=>b(i.id),className:o?"animate-pulse":""}),e.jsx("foreignObject",{x:16,y:16,width:S-32,height:p-32,style:{pointerEvents:"none"},children:e.jsxs("div",{className:"h-full flex flex-col justify-between",style:{pointerEvents:"none"},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:"text-lg",children:u.icon}),e.jsx("span",{className:"font-semibold text-sm truncate",style:{color:u.text},children:i.data.label})]}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${i.data.status==="running"?"animate-pulse":""}`,style:{backgroundColor:u.indicator,boxShadow:i.data.status==="running"?`0 0 8px ${u.indicator}`:"none"}}),r&&e.jsx("div",{className:`text-xs px-1 py-0.5 rounded-full font-bold ${l?"bg-blue-600 text-white":"bg-blue-100 text-blue-700"}`,title:`${y.length} execution log${y.length!==1?"s":""}`,children:y.length})]})]}),e.jsx("div",{className:"text-xs px-2 py-1 rounded-full self-start font-medium",style:{backgroundColor:u.indicator+"20",color:u.text},children:i.type}),i.data.description&&e.jsx("div",{className:"text-xs mt-1 line-clamp-2 opacity-80 leading-relaxed",style:{color:u.text},children:i.data.description}),e.jsx("div",{className:"text-xs mt-1 opacity-60 font-medium",style:{color:u.text},children:r?`Click to view ${y.length} logs • Hover for details`:"Click to view • Right-click for breakpoint"})]})})]})},Ee=({edge:i,nodes:t,isActive:n,isInExecutionPath:o})=>{const{darkMode:f}=V(),b=t.find(S=>S.id===i.source),N=t.find(S=>S.id===i.target);if(!b||!N)return null;const w=160,m=100,d=b.position.x+w,_=b.position.y+m/2,l=N.position.x,y=N.position.y+m/2,r=(d+l)/2,x=`M ${d} ${_} C ${r} ${_}, ${r} ${y}, ${l} ${y}`,$=n?"#3b82f6":o?"#10b981":f?"#6b7280":"#9ca3af",u=n?3:o?2.5:2;return e.jsxs("g",{children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrowhead-${i.id}`,markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:$})})}),e.jsx("path",{d:x,fill:"none",stroke:f?"rgba(0,0,0,0.3)":"rgba(0,0,0,0.1)",strokeWidth:u+1,transform:"translate(1, 2)"}),e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u,className:`transition-all duration-300 ${n?"animate-pulse":""} ${o?"execution-path-animated":""}`,style:{filter:n?`drop-shadow(0 0 6px ${$})`:"none"},markerEnd:`url(#arrowhead-${i.id})`}),n&&e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u+4,opacity:"0.3",className:"animate-pulse"})]})},_e=({currentState:i,onStateChange:t,onStartExecution:n,darkMode:o})=>{const{selectedAgent:f,agentSchemas:b,schemasLoading:N,fetchAgentSchemas:w}=V(),m=f?.id,d=m?b[m]:void 0,[_,l]=g.useState({});g.useEffect(()=>{m&&w(m)},[m,w]),g.useEffect(()=>{const x=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object"),h=x?Ne(d?.input_schema):we(d?.input_schema),$=d?.input_schema?.properties,u=$&&typeof $=="object"?Object.fromEntries(Object.entries(i||{}).filter(([C])=>Object.prototype.hasOwnProperty.call($,C))):{};if(x){const C=i?.__root__??h;l(C),t({__root__:C});return}const p={...{...h&&typeof h=="object"&&!Array.isArray(h)?h:{},...u}};delete p.intermediate_results,delete p.execution_history,delete p.error_log,delete p.current_node,l(p),t(p)},[d?.input_schema,m]);const y=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x)},r=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x),n(x)};return e.jsxs("div",{className:`p-4 border-b space-y-3 ${o?"border-gray-600":"border-gray-200"}`,children:[N&&!d&&e.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:"Loading agent schema…"}),e.jsx($e,{schema:d?.input_schema,value:_,onChange:y,onSubmit:r,submitLabel:"Submit & Run",darkMode:o,disabled:!m,schemaSource:d?.schema_source?.input},m||"no-agent"),e.jsx(Se,{schema:d?.output_schema,source:d?.schema_source?.output,darkMode:o})]})},Te=({logs:i,darkMode:t,onLogHover:n,onLogSelect:o,selectedLogId:f,selectedNodeId:b,onClearNodeFilter:N})=>{const w=g.useRef(null),m=g.useRef(null),[d,_]=g.useState(new Set),[l,y]=g.useState(""),[r,x]=g.useState("all");g.useEffect(()=>{w.current?.scrollIntoView({behavior:"smooth"})},[i]),g.useEffect(()=>{f&&m.current&&m.current.scrollIntoView({behavior:"smooth",block:"center"})},[f]);const h=a=>{_(L=>{const j=new Set(L);return j.has(a)?j.delete(a):j.add(a),j})},$=i.filter(a=>{const L=l===""||a.message.toLowerCase().includes(l.toLowerCase())||a.nodeName.toLowerCase().includes(l.toLowerCase()),j=r==="all"||a.type===r,Y=!b||a.nodeId===b;return L&&j&&Y}),u=a=>{switch(a){case"input":return"📥";case"output":return"📤";case"error":return"❌";case"info":return"ℹ️";case"debug":return"🐛";default:return"📝"}},S=a=>{switch(a){case"input":return t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800";case"output":return t?"bg-green-900 text-green-300":"bg-green-100 text-green-800";case"error":return t?"bg-red-900 text-red-300":"bg-red-100 text-red-800";case"info":return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800";case"debug":return t?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-800";default:return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800"}},p=(a,L=!1)=>{if(!a)return null;if(typeof a=="string")return L?a:a.length>100?a.substring(0,100)+"...":a;const j=JSON.stringify(a,null,L?2:0);return!L&&j.length>200?j.substring(0,200)+"...":j},C=a=>{const L=d.has(a.id),j=f===a.id;return e.jsxs("div",{ref:j?m:void 0,className:`rounded-lg border transition-all duration-300 ${j?`log-entry-selected ${t?"bg-blue-900/30 border-blue-500 shadow-lg":"bg-blue-50 border-blue-300 shadow-lg"}`:`${t?"bg-gray-700 border-gray-600 hover:bg-gray-650":"bg-white border-gray-200 hover:bg-gray-50"} hover:log-entry-hover`}`,onMouseEnter:()=>n(a.nodeId),onMouseLeave:()=>n(null),children:[e.jsxs("div",{className:"p-4 cursor-pointer",onClick:()=>{o(j?null:a.id),h(a.id)},children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${S(a.type)}`,children:e.jsx("span",{className:"text-sm",children:u(a.type)})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:`font-semibold text-sm ${t?"text-white":"text-gray-900"}`,children:a.nodeName}),e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${S(a.type)}`,children:a.type.toUpperCase()}),j&&e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${t?"bg-yellow-900 text-yellow-300":"bg-yellow-100 text-yellow-700"}`,children:"FOCUSED"})]}),e.jsxs("div",{className:`text-xs mt-1 ${t?"text-gray-400":"text-gray-500"}`,children:[a.timestamp.toLocaleTimeString()," • Node ID: ",a.nodeId]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[a.duration&&e.jsxs("div",{className:`px-3 py-1 rounded-lg text-xs font-medium ${t?"bg-gray-600 text-gray-300":"bg-gray-100 text-gray-600"}`,children:["⏱️ ",a.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform duration-200 ${L?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]}),e.jsx("div",{className:`text-sm mb-3 p-3 rounded-lg ${t?"bg-gray-800 text-gray-300":"bg-gray-50 text-gray-700"}`,children:e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx("span",{className:"text-lg",children:"💬"}),e.jsx("span",{children:a.message})]})}),a.data?.intermediate_results&&!L&&e.jsxs("div",{className:`p-3 rounded-lg border ${t?"bg-gray-800 border-gray-600":"bg-gray-50 border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Data Preview"}),e.jsx("span",{className:`text-xs ${t?"text-blue-400":"text-blue-600"}`,children:"Click to expand"})]}),e.jsx("div",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-800"}`,children:p(a.data,!1)})]})]}),L&&a.data&&e.jsx("div",{className:`border-t ${t?"border-gray-600":"border-gray-200"}`,children:e.jsxs("div",{className:"p-4 space-y-4",children:[a.data.performance&&e.jsxs("div",{className:`p-3 rounded-lg performance-card ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"⚡"}),"Performance Metrics"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsxs("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:[a.data.performance.duration_ms,"ms"]})]}),e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Node Type"}),e.jsx("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:a.data.performance.node_type})]})]})]}),a.data.state_updates&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔄"}),"State Updates"]}),e.jsx("div",{className:"space-y-2",children:Object.entries(a.data.state_updates).map(([Y,G])=>e.jsxs("div",{className:`p-2 rounded border-l-4 border-blue-500 state-update-indicator ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${t?"text-gray-300":"text-gray-700"}`,children:Y}),e.jsx("div",{className:`text-xs font-mono mt-1 ${t?"text-gray-400":"text-gray-600"}`,children:typeof G=="object"?JSON.stringify(G,null,2):String(G)})]},Y))})]}),a.data.output&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"📤"}),"Output Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.output,null,2)})]}),a.data.current_state&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔍"}),"Current State"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.current_state,null,2)})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🗂️"}),"Raw Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data,null,2)})]})]})})]},a.id)};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${t?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:`text-sm font-semibold flex items-center ${t?"text-white":"text-gray-900"}`,children:["Live Execution Logs",b&&e.jsxs("span",{className:`ml-3 px-2 py-1 rounded text-xs font-medium flex items-center ${t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800"}`,children:["Filtered: ",b,e.jsx("button",{onClick:N,className:"ml-2 hover:text-white hover:bg-blue-800 rounded-full w-4 h-4 flex items-center justify-center transition-colors",title:"Clear filter",children:"×"})]})]}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[$.length," / ",i.length]})})]}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("input",{type:"text",placeholder:"Search logs...",value:l,onChange:a=>y(a.target.value),className:`flex-1 px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`}),e.jsxs("select",{value:r,onChange:a=>x(a.target.value),className:`px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,children:[e.jsx("option",{value:"all",children:"All Types"}),e.jsx("option",{value:"input",children:"Input"}),e.jsx("option",{value:"output",children:"Output"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"info",children:"Info"}),e.jsx("option",{value:"debug",children:"Debug"})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-3 custom-scrollbar",children:[$.length===0?e.jsxs("div",{className:`text-center py-12 ${t?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-4xl mb-4",children:"📋"}),e.jsx("p",{className:"text-lg font-medium mb-2",children:i.length===0?"No execution logs yet":"No logs match your filter"}),e.jsx("p",{className:"text-sm",children:i.length===0?"Start graph execution to see live logs":"Try adjusting your search or filter"})]}):$.map(a=>C(a)),e.jsx("div",{ref:w})]})]})},Oe=({currentState:i,executionContext:t,darkMode:n})=>{const[o,f]=g.useState(new Set(["overview"])),[b,N]=g.useState(""),w=r=>{f(x=>{const h=new Set(x);return h.has(r)?h.delete(r):h.add(r),h})},m=r=>r===null?"null":r===void 0?"undefined":typeof r=="boolean"||typeof r=="number"?r.toString():typeof r=="string"?r.length>100?`${r.substring(0,100)}...`:r:Array.isArray(r)?`Array(${r.length})`:typeof r=="object"?`Object(${Object.keys(r).length} keys)`:String(r),d=r=>r==null?n?"text-gray-500":"text-gray-400":typeof r=="boolean"?n?"text-purple-400":"text-purple-600":typeof r=="number"?n?"text-blue-400":"text-blue-600":typeof r=="string"?n?"text-green-400":"text-green-600":Array.isArray(r)?n?"text-orange-400":"text-orange-600":typeof r=="object"?n?"text-cyan-400":"text-cyan-600":n?"text-gray-300":"text-gray-700",_=r=>r==null?"∅":typeof r=="boolean"?r?"✓":"✗":typeof r=="number"?"#":typeof r=="string"?'"':Array.isArray(r)?"[]":typeof r=="object"?"{}":"?",l=Object.entries(i||{}).filter(([r,x])=>b?r.toLowerCase().includes(b.toLowerCase())||String(x).toLowerCase().includes(b.toLowerCase()):!0),y={totalSteps:t.logs.length,errors:t.logs.filter(r=>r.type==="error").length,duration:t.startTime?(t.endTime||new Date).getTime()-t.startTime.getTime():0,status:t.isExecuting?t.isPaused?"Paused":"Running":"Idle"};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:`text-sm font-semibold ${n?"text-white":"text-gray-900"}`,children:"Current State"}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[Object.keys(i||{}).length," fields"]})})]}),e.jsx("input",{type:"text",placeholder:"Search state fields...",value:b,onChange:r=>N(r.target.value),className:`w-full px-3 py-2 text-xs border rounded-lg ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("overview"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("overview")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Execution Overview"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${y.status==="Running"?"bg-blue-100 text-blue-700":y.status==="Paused"?"bg-orange-100 text-orange-700":"bg-gray-100 text-gray-700"}`,children:y.status})]})}),o.has("overview")&&e.jsx("div",{className:`px-4 pb-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Total Steps"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.totalSteps})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Errors"}),e.jsx("div",{className:`text-lg font-bold ${y.errors>0?"text-red-500":n?"text-white":"text-gray-900"}`,children:y.errors})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.duration>0?`${(y.duration/1e3).toFixed(1)}s`:"0s"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Breakpoints"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:t.breakpoints.filter(r=>r.enabled).length})]})]})})]}),e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("fields"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("fields")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"State Fields"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:l.length})]})}),o.has("fields")&&e.jsx("div",{className:"space-y-1",children:l.length===0?e.jsxs("div",{className:`p-4 text-center ${n?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-2xl mb-2",children:"📭"}),e.jsx("p",{className:"text-sm",children:Object.keys(i||{}).length===0?"No state data":"No fields match your search"})]}):l.map(([r,x])=>e.jsxs("div",{className:`p-3 border-l-4 transition-colors ${n?"border-l-gray-600 hover:bg-gray-700":"border-l-gray-200 hover:bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[e.jsx("span",{className:`text-sm ${d(x)}`,children:_(x)}),e.jsx("span",{className:`font-medium text-sm truncate ${n?"text-white":"text-gray-900"}`,children:r})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded font-mono ${n?"bg-gray-800 text-gray-300":"bg-gray-100 text-gray-600"}`,children:typeof x})]}),e.jsx("div",{className:`mt-1 text-xs font-mono ${d(x)}`,children:m(x)})]},r))})]}),e.jsxs("div",{children:[e.jsx("button",{onClick:()=>w("raw"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("raw")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Raw JSON"})]})}),o.has("raw")&&e.jsx("div",{className:`p-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono p-3 rounded-lg overflow-x-auto ${n?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(i||{},null,2)})})]})]})]})},Ae=()=>{const{graphState:i,darkMode:t,error:n,executionContext:o,selectedAssistant:f,resumeExecution:b,stopExecution:N,setGraphExecutionState:w,addBreakpoint:m,removeBreakpoint:d,startGlobalExecution:_}=V(),[l,y]=g.useState(null),[r,x]=g.useState(1),[h,$]=g.useState({x:0,y:0}),[u,S]=g.useState(!1),[p,C]=g.useState("bottom"),[a,L]=g.useState(!1),[j,Y]=g.useState({x:0,y:0}),[G,K]=g.useState(null),[z,U]=g.useState("input"),[de,xe]=g.useState(null),[ne,R]=g.useState(null),I=g.useRef(null),ae=g.useRef(null),[Q,ie]=g.useState(null),M=(Array.isArray(f?.metadata?.capabilities)?f.metadata.capabilities:Array.isArray(f?.config?.capabilities)?f.config.capabilities:[]).includes("breakpoints"),ge=(s,c)=>{ie({nodeId:s,position:c})},oe=()=>{ie(null)};g.useEffect(()=>{o.isExecuting&&!o.isPaused&&U("logs")},[o.isExecuting,o.isPaused]),g.useEffect(()=>{ae.current&&ae.current.scrollIntoView({behavior:"smooth"})},[o.logs]),g.useEffect(()=>{i?.currentNode&&o.isExecuting&&!o.isPaused&&ee(i.currentNode)},[i?.currentNode,o.isExecuting,o.isPaused]),g.useEffect(()=>{const{selectedThread:s,selectedAssistant:c}=V.getState();if(s&&c){const v=`${s.name} • ${c.name}`;R(v),setTimeout(()=>R(null),3e3)}},[o.threadId,o.assistantId]);const ee=s=>{const c=i?.nodes?.find(q=>q.id===s);if(!c||!I.current)return;const v=I.current.getBoundingClientRect(),E=v.width,T=v.height,X=E/2-c.position.x*r-80,J=T/2-c.position.y*r-50,O={...h},k={x:X,y:J},H=800,A=Date.now(),B=()=>{const q=Date.now()-A,Z=Math.min(q/H,1),D=(W=>W<.5?4*W*W*W:(W-1)*(2*W-2)*(2*W-2)+1)(Z),P={x:O.x+(k.x-O.x)*D,y:O.y+(k.y-O.y)*D};$(P),Z<1&&requestAnimationFrame(B)};requestAnimationFrame(B)},te=()=>{if(i?.nodes?.length===0||!I.current)return;const s=i.nodes.reduce((D,P)=>({minX:Math.min(D.minX,P.position.x),maxX:Math.max(D.maxX,P.position.x+160),minY:Math.min(D.minY,P.position.y),maxY:Math.max(D.maxY,P.position.y+100)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0}),c=50,v=s.maxX-s.minX+c*2,E=s.maxY-s.minY+c*2,T=I.current.clientWidth,X=I.current.clientHeight,J=T/v,O=X/E,k=Math.min(J,O,1),H={x:-(s.minX-c)*k+(T-v*k)/2,y:-(s.minY-c)*k+(X-E*k)/2},A=r,B={...h},q=1e3,Z=Date.now(),se=()=>{const D=Date.now()-Z,P=Math.min(D/q,1),re=(F=>F<.5?4*F*F*F:(F-1)*(2*F-2)*(2*F-2)+1)(P),je=A+(k-A)*re,ve={x:B.x+(H.x-B.x)*re,y:B.y+(H.y-B.y)*re};x(je),$(ve),P<1&&requestAnimationFrame(se)};requestAnimationFrame(se)};if(g.useEffect(()=>{const s=V.getState();s.focusOnNode=ee,s.fitGraphToView=te},[r,h,i?.nodes]),g.useEffect(()=>{const s=I.current;if(!s)return;const c=v=>{v.preventDefault();const E=v.deltaY>0?-.02:.02;x(T=>Math.max(.1,Math.min(3,T+E)))};return s.addEventListener("wheel",c,{passive:!1}),()=>s.removeEventListener("wheel",c)},[]),!i)return e.jsx("div",{className:`flex items-center justify-center h-full ${t?"bg-gray-800 text-white":"bg-white text-gray-900"}`,children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{children:"Loading graph state..."})]})});const he=s=>{y(l===s?null:s),u&&S(!1),U("logs");const c=o.logs.filter(v=>v.nodeId===s);if(c.length>0){const v=c[c.length-1];K(v.id);const E=i.nodes.find(T=>T.id===s)?.data.label||s;R(`📋 Showing ${c.length} logs for ${E}`),setTimeout(()=>R(null),3e3),console.log(`Showing execution logs for node: ${s}`,{totalLogs:c.length,mostRecentLog:v,nodeState:o.currentState})}else{const v=i.nodes.find(E=>E.id===s)?.data.label||s;R(`ℹ️ No execution logs found for ${v}`),setTimeout(()=>R(null),2e3),console.log(`No execution logs found for node: ${s}`),K(null)}},me=s=>{if(!M){R("This agent does not publish server-side breakpoint support."),setTimeout(()=>R(null),3e3);return}o.breakpoints.some(v=>v.nodeId===s)?d(s):m(s)},ue=async(s={})=>{const c=s??{},v=c&&typeof c=="object"&&!Array.isArray(c)?c:{},E={context:{source:"graph"},timestamp:new Date().toISOString(),...v},{selectedThread:T,addMessageToThread:X,createPersistentThread:J}=V.getState();let O=T;if(!O){if(!f?.id){ce.error("Select a live Agentomatic agent before running the graph.");return}try{O=await J(f.id,"Graph Execution")}catch(A){ce.error(A instanceof Error?A.message:"Could not create a durable graph conversation.");return}}const k=JSON.stringify(c,null,2),H={id:`msg-${Date.now()}-graph-user`,role:"user",content:`🔄 **Graph Execution Initiated** +import{u as V,j as e,d as Ne,a as we,V as ce}from"./index-BMj1jeBL.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";import{S as $e}from"./SchemaForm-Kr1WPDMd.js";import{O as Se}from"./OutputSchemaSummary-CiE3pU-0.js";import"./syntax-vendor-ru7AzRyY.js";const Ce=({nodeId:i,logs:t,darkMode:n,position:o,onClose:f})=>{const b=t.filter(w=>w.nodeId===i);if(b.length===0)return null;const N=b[b.length-1];return e.jsx("div",{className:"fixed z-50 pointer-events-none",style:{left:o.x+20,top:o.y-10,maxWidth:"400px"},children:e.jsxs("div",{className:`rounded-lg shadow-xl border p-4 pointer-events-auto ${n?"bg-gray-800 border-gray-600 text-white":"bg-white border-gray-200 text-gray-900"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-semibold text-sm",children:"Node Execution Details"}),e.jsx("button",{onClick:f,className:`text-xs px-2 py-1 rounded ${n?"hover:bg-gray-700 text-gray-400":"hover:bg-gray-100 text-gray-500"}`,children:"✕"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Latest Execution"}),e.jsx("div",{className:"text-sm",children:N.message}),e.jsx("div",{className:`text-xs mt-1 ${n?"text-gray-500":"text-gray-400"}`,children:N.timestamp.toLocaleString()})]}),N.data?.intermediate_results&&e.jsxs("div",{children:[e.jsx("div",{className:`text-xs font-medium mb-2 ${n?"text-gray-400":"text-gray-500"}`,children:"Results Preview"}),e.jsx("div",{className:`text-xs p-2 rounded font-mono ${n?"bg-gray-900 text-gray-300":"bg-gray-50 text-gray-700"}`,children:Object.keys(N.data.intermediate_results).length>0?e.jsx("div",{children:Object.entries(N.data.intermediate_results).map(([w,m])=>e.jsxs("div",{className:"mb-1",children:[e.jsxs("span",{className:"font-semibold",children:[w,":"]})," ",typeof m=="object"&&m!==null&&"response"in m?`"${m.response?.substring(0,50)}..."`:JSON.stringify(m).substring(0,50)+"..."]},w))}):"No results available"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-gray-200 dark:border-gray-600",children:[e.jsxs("span",{className:`text-xs ${n?"text-gray-400":"text-gray-500"}`,children:[b.length," total execution",b.length!==1?"s":""]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700"}`,children:"Click node to view all logs"})]})]})]})})},Le=({node:i,isSelected:t,isActive:n,isHighlighted:o,hasBreakpoint:f,onClick:b,onBreakpointToggle:N,canManageBreakpoints:w,logs:m,onShowLogTooltip:d,onHideLogTooltip:_})=>{const{darkMode:l}=V(),y=m.filter(C=>C.nodeId===i.id),r=y.length>0,x=C=>{if(r){const a=C.currentTarget.getBoundingClientRect();d(i.id,{x:a.right,y:a.top})}},h=()=>{r&&_()},u=((C,a)=>{const L={start:{bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",text:l?"#bfdbfe":"#1e40af",indicator:"#3b82f6",icon:"🚀"},end:{bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",text:l?"#fecaca":"#991b1b",indicator:"#ef4444",icon:"🏁"},agent:{bg:l?"#581c87":"#f3e8ff",border:"#8b5cf6",text:l?"#ddd6fe":"#6b21a8",indicator:"#8b5cf6",icon:"🤖"},tool:{bg:l?"#14532d":"#dcfce7",border:"#10b981",text:l?"#bbf7d0":"#065f46",indicator:"#10b981",icon:"🔧"},human:{bg:l?"#92400e":"#fef3c7",border:"#f59e0b",text:l?"#fde68a":"#92400e",indicator:"#f59e0b",icon:"👤"},condition:{bg:l?"#7c2d12":"#fed7aa",border:"#ea580c",text:l?"#fed7aa":"#9a3412",indicator:"#ea580c",icon:"🔀"},retrieval:{bg:l?"#164e63":"#cffafe",border:"#0891b2",text:l?"#a5f3fc":"#164e63",indicator:"#0891b2",icon:"🔍"},processing:{bg:l?"#4c1d95":"#ede9fe",border:"#7c3aed",text:l?"#c4b5fd":"#4c1d95",indicator:"#7c3aed",icon:"⚙️"},generation:{bg:l?"#be185d":"#fce7f3",border:"#ec4899",text:l?"#fbcfe8":"#be185d",indicator:"#ec4899",icon:"✨"},validation:{bg:l?"#365314":"#ecfccb",border:"#65a30d",text:l?"#d9f99d":"#365314",indicator:"#65a30d",icon:"✅"},default:{bg:l?"#374151":"#f9fafb",border:l?"#6b7280":"#d1d5db",text:l?"#e5e7eb":"#374151",indicator:l?"#9ca3af":"#6b7280",icon:"📦"}},j=L[C]||L.default;return a==="running"?{...j,bg:l?"#1e3a8a":"#dbeafe",border:"#3b82f6",indicator:"#3b82f6"}:a==="completed"?{...j,bg:l?"#14532d":"#dcfce7",border:"#10b981",indicator:"#10b981"}:a==="error"?{...j,bg:l?"#7f1d1d":"#fef2f2",border:"#ef4444",indicator:"#ef4444"}:a==="paused"?{...j,bg:l?"#92400e":"#fef3c7",border:"#f59e0b",indicator:"#f59e0b"}:j})(i.type,i.data.status),S=160,p=100;return e.jsxs("g",{transform:`translate(${i.position.x}, ${i.position.y})`,className:"cursor-pointer graph-node-group",onMouseEnter:x,onMouseLeave:h,children:[e.jsxs("defs",{children:[e.jsx("filter",{id:`shadow-${i.id}`,x:"-20%",y:"-20%",width:"140%",height:"140%",children:e.jsx("feDropShadow",{dx:"0",dy:"3",stdDeviation:"4",floodColor:l?"rgba(0,0,0,0.5)":"rgba(0,0,0,0.15)",floodOpacity:"1"})}),e.jsxs("linearGradient",{id:`gradient-${i.id}`,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:u.bg,stopOpacity:"1"}),e.jsx("stop",{offset:"100%",stopColor:u.bg,stopOpacity:"0.8"})]})]}),w&&e.jsxs("g",{className:"cursor-pointer",onClick:C=>{C.stopPropagation(),N(i.id)},children:[e.jsx("title",{children:f?"Remove breakpoint":"Add breakpoint"}),e.jsx("circle",{cx:-8,cy:8,r:7,fill:f?"#ef4444":l?"#374151":"#ffffff",stroke:f?"#fecaca":"#9ca3af",strokeWidth:2}),!f&&e.jsx("path",{d:"M-11 8h6M-8 5v6",stroke:"#6b7280",strokeWidth:1.5,strokeLinecap:"round"})]}),r&&e.jsx("circle",{cx:S-8,cy:8,r:8,fill:l?"#3b82f6":"#2563eb",stroke:l?"#1f2937":"#ffffff",strokeWidth:2,className:"cursor-pointer animate-pulse"}),r&&e.jsx("text",{x:S-8,y:8,textAnchor:"middle",dominantBaseline:"central",fontSize:"10",fill:"white",className:"pointer-events-none font-bold",children:"ℹ️"}),n&&e.jsx("rect",{width:S+12,height:p+12,x:-6,y:-6,rx:20,fill:u.indicator,opacity:"0.2",className:"animate-pulse"}),o&&e.jsx("rect",{width:S+16,height:p+16,x:-8,y:-8,rx:22,fill:"none",stroke:"#f59e0b",strokeWidth:3,strokeDasharray:"12,6",className:"animate-pulse",opacity:"0.8"}),e.jsx("rect",{width:S,height:p,rx:16,fill:`url(#gradient-${i.id})`,stroke:u.border,strokeWidth:t?3:o?2.5:2,filter:`url(#shadow-${i.id})`,onClick:()=>b(i.id),className:o?"animate-pulse":""}),e.jsx("foreignObject",{x:16,y:16,width:S-32,height:p-32,style:{pointerEvents:"none"},children:e.jsxs("div",{className:"h-full flex flex-col justify-between",style:{pointerEvents:"none"},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:"text-lg",children:u.icon}),e.jsx("span",{className:"font-semibold text-sm truncate",style:{color:u.text},children:i.data.label})]}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${i.data.status==="running"?"animate-pulse":""}`,style:{backgroundColor:u.indicator,boxShadow:i.data.status==="running"?`0 0 8px ${u.indicator}`:"none"}}),r&&e.jsx("div",{className:`text-xs px-1 py-0.5 rounded-full font-bold ${l?"bg-blue-600 text-white":"bg-blue-100 text-blue-700"}`,title:`${y.length} execution log${y.length!==1?"s":""}`,children:y.length})]})]}),e.jsx("div",{className:"text-xs px-2 py-1 rounded-full self-start font-medium",style:{backgroundColor:u.indicator+"20",color:u.text},children:i.type}),i.data.description&&e.jsx("div",{className:"text-xs mt-1 line-clamp-2 opacity-80 leading-relaxed",style:{color:u.text},children:i.data.description}),e.jsx("div",{className:"text-xs mt-1 opacity-60 font-medium",style:{color:u.text},children:r?`Click to view ${y.length} logs • Hover for details`:"Click to view • Right-click for breakpoint"})]})})]})},Ee=({edge:i,nodes:t,isActive:n,isInExecutionPath:o})=>{const{darkMode:f}=V(),b=t.find(S=>S.id===i.source),N=t.find(S=>S.id===i.target);if(!b||!N)return null;const w=160,m=100,d=b.position.x+w,_=b.position.y+m/2,l=N.position.x,y=N.position.y+m/2,r=(d+l)/2,x=`M ${d} ${_} C ${r} ${_}, ${r} ${y}, ${l} ${y}`,$=n?"#3b82f6":o?"#10b981":f?"#6b7280":"#9ca3af",u=n?3:o?2.5:2;return e.jsxs("g",{children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrowhead-${i.id}`,markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:$})})}),e.jsx("path",{d:x,fill:"none",stroke:f?"rgba(0,0,0,0.3)":"rgba(0,0,0,0.1)",strokeWidth:u+1,transform:"translate(1, 2)"}),e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u,className:`transition-all duration-300 ${n?"animate-pulse":""} ${o?"execution-path-animated":""}`,style:{filter:n?`drop-shadow(0 0 6px ${$})`:"none"},markerEnd:`url(#arrowhead-${i.id})`}),n&&e.jsx("path",{d:x,fill:"none",stroke:$,strokeWidth:u+4,opacity:"0.3",className:"animate-pulse"})]})},_e=({currentState:i,onStateChange:t,onStartExecution:n,darkMode:o})=>{const{selectedAgent:f,agentSchemas:b,schemasLoading:N,fetchAgentSchemas:w}=V(),m=f?.id,d=m?b[m]:void 0,[_,l]=g.useState({});g.useEffect(()=>{m&&w(m)},[m,w]),g.useEffect(()=>{const x=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object"),h=x?Ne(d?.input_schema):we(d?.input_schema),$=d?.input_schema?.properties,u=$&&typeof $=="object"?Object.fromEntries(Object.entries(i||{}).filter(([C])=>Object.prototype.hasOwnProperty.call($,C))):{};if(x){const C=i?.__root__??h;l(C),t({__root__:C});return}const p={...{...h&&typeof h=="object"&&!Array.isArray(h)?h:{},...u}};delete p.intermediate_results,delete p.execution_history,delete p.error_log,delete p.current_node,l(p),t(p)},[d?.input_schema,m]);const y=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x)},r=x=>{l(x);const h=!!(d?.input_schema&&(!d.input_schema.properties||Object.keys(d.input_schema.properties).length===0)&&d.input_schema.type&&d.input_schema.type!=="object");t(h?{__root__:x}:x),n(x)};return e.jsxs("div",{className:`p-4 border-b space-y-3 ${o?"border-gray-600":"border-gray-200"}`,children:[N&&!d&&e.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:"Loading agent schema…"}),e.jsx($e,{schema:d?.input_schema,value:_,onChange:y,onSubmit:r,submitLabel:"Submit & Run",darkMode:o,disabled:!m,schemaSource:d?.schema_source?.input},m||"no-agent"),e.jsx(Se,{schema:d?.output_schema,source:d?.schema_source?.output,darkMode:o})]})},Te=({logs:i,darkMode:t,onLogHover:n,onLogSelect:o,selectedLogId:f,selectedNodeId:b,onClearNodeFilter:N})=>{const w=g.useRef(null),m=g.useRef(null),[d,_]=g.useState(new Set),[l,y]=g.useState(""),[r,x]=g.useState("all");g.useEffect(()=>{w.current?.scrollIntoView({behavior:"smooth"})},[i]),g.useEffect(()=>{f&&m.current&&m.current.scrollIntoView({behavior:"smooth",block:"center"})},[f]);const h=a=>{_(L=>{const j=new Set(L);return j.has(a)?j.delete(a):j.add(a),j})},$=i.filter(a=>{const L=l===""||a.message.toLowerCase().includes(l.toLowerCase())||a.nodeName.toLowerCase().includes(l.toLowerCase()),j=r==="all"||a.type===r,Y=!b||a.nodeId===b;return L&&j&&Y}),u=a=>{switch(a){case"input":return"📥";case"output":return"📤";case"error":return"❌";case"info":return"ℹ️";case"debug":return"🐛";default:return"📝"}},S=a=>{switch(a){case"input":return t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800";case"output":return t?"bg-green-900 text-green-300":"bg-green-100 text-green-800";case"error":return t?"bg-red-900 text-red-300":"bg-red-100 text-red-800";case"info":return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800";case"debug":return t?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-800";default:return t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-800"}},p=(a,L=!1)=>{if(!a)return null;if(typeof a=="string")return L?a:a.length>100?a.substring(0,100)+"...":a;const j=JSON.stringify(a,null,L?2:0);return!L&&j.length>200?j.substring(0,200)+"...":j},C=a=>{const L=d.has(a.id),j=f===a.id;return e.jsxs("div",{ref:j?m:void 0,className:`rounded-lg border transition-all duration-300 ${j?`log-entry-selected ${t?"bg-blue-900/30 border-blue-500 shadow-lg":"bg-blue-50 border-blue-300 shadow-lg"}`:`${t?"bg-gray-700 border-gray-600 hover:bg-gray-650":"bg-white border-gray-200 hover:bg-gray-50"} hover:log-entry-hover`}`,onMouseEnter:()=>n(a.nodeId),onMouseLeave:()=>n(null),children:[e.jsxs("div",{className:"p-4 cursor-pointer",onClick:()=>{o(j?null:a.id),h(a.id)},children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${S(a.type)}`,children:e.jsx("span",{className:"text-sm",children:u(a.type)})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:`font-semibold text-sm ${t?"text-white":"text-gray-900"}`,children:a.nodeName}),e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${S(a.type)}`,children:a.type.toUpperCase()}),j&&e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${t?"bg-yellow-900 text-yellow-300":"bg-yellow-100 text-yellow-700"}`,children:"FOCUSED"})]}),e.jsxs("div",{className:`text-xs mt-1 ${t?"text-gray-400":"text-gray-500"}`,children:[a.timestamp.toLocaleTimeString()," • Node ID: ",a.nodeId]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[a.duration&&e.jsxs("div",{className:`px-3 py-1 rounded-lg text-xs font-medium ${t?"bg-gray-600 text-gray-300":"bg-gray-100 text-gray-600"}`,children:["⏱️ ",a.duration,"ms"]}),e.jsx("svg",{className:`w-5 h-5 transition-transform duration-200 ${L?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]}),e.jsx("div",{className:`text-sm mb-3 p-3 rounded-lg ${t?"bg-gray-800 text-gray-300":"bg-gray-50 text-gray-700"}`,children:e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx("span",{className:"text-lg",children:"💬"}),e.jsx("span",{children:a.message})]})}),a.data?.intermediate_results&&!L&&e.jsxs("div",{className:`p-3 rounded-lg border ${t?"bg-gray-800 border-gray-600":"bg-gray-50 border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:`text-xs font-medium ${t?"text-gray-400":"text-gray-500"}`,children:"Data Preview"}),e.jsx("span",{className:`text-xs ${t?"text-blue-400":"text-blue-600"}`,children:"Click to expand"})]}),e.jsx("div",{className:`text-xs font-mono ${t?"text-gray-300":"text-gray-800"}`,children:p(a.data,!1)})]})]}),L&&a.data&&e.jsx("div",{className:`border-t ${t?"border-gray-600":"border-gray-200"}`,children:e.jsxs("div",{className:"p-4 space-y-4",children:[a.data.performance&&e.jsxs("div",{className:`p-3 rounded-lg performance-card ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"⚡"}),"Performance Metrics"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsxs("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:[a.data.performance.duration_ms,"ms"]})]}),e.jsxs("div",{className:`p-2 rounded ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs ${t?"text-gray-400":"text-gray-500"}`,children:"Node Type"}),e.jsx("div",{className:`font-semibold ${t?"text-white":"text-gray-900"}`,children:a.data.performance.node_type})]})]})]}),a.data.state_updates&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔄"}),"State Updates"]}),e.jsx("div",{className:"space-y-2",children:Object.entries(a.data.state_updates).map(([Y,G])=>e.jsxs("div",{className:`p-2 rounded border-l-4 border-blue-500 state-update-indicator ${t?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${t?"text-gray-300":"text-gray-700"}`,children:Y}),e.jsx("div",{className:`text-xs font-mono mt-1 ${t?"text-gray-400":"text-gray-600"}`,children:typeof G=="object"?JSON.stringify(G,null,2):String(G)})]},Y))})]}),a.data.output&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"📤"}),"Output Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.output,null,2)})]}),a.data.current_state&&e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🔍"}),"Current State"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data.current_state,null,2)})]}),e.jsxs("div",{className:`p-3 rounded-lg ${t?"bg-gray-800":"bg-gray-50"}`,children:[e.jsxs("h4",{className:`text-sm font-semibold mb-2 flex items-center ${t?"text-white":"text-gray-900"}`,children:[e.jsx("span",{className:"mr-2",children:"🗂️"}),"Raw Data"]}),e.jsx("pre",{className:`text-xs font-mono p-3 rounded overflow-x-auto log-data-json ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(a.data,null,2)})]})]})})]},a.id)};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${t?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:`text-sm font-semibold flex items-center ${t?"text-white":"text-gray-900"}`,children:["Live Execution Logs",b&&e.jsxs("span",{className:`ml-3 px-2 py-1 rounded text-xs font-medium flex items-center ${t?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-800"}`,children:["Filtered: ",b,e.jsx("button",{onClick:N,className:"ml-2 hover:text-white hover:bg-blue-800 rounded-full w-4 h-4 flex items-center justify-center transition-colors",title:"Clear filter",children:"×"})]})]}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${t?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[$.length," / ",i.length]})})]}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("input",{type:"text",placeholder:"Search logs...",value:l,onChange:a=>y(a.target.value),className:`flex-1 px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`}),e.jsxs("select",{value:r,onChange:a=>x(a.target.value),className:`px-3 py-2 text-xs border rounded-lg ${t?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"}`,children:[e.jsx("option",{value:"all",children:"All Types"}),e.jsx("option",{value:"input",children:"Input"}),e.jsx("option",{value:"output",children:"Output"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"info",children:"Info"}),e.jsx("option",{value:"debug",children:"Debug"})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-3 custom-scrollbar",children:[$.length===0?e.jsxs("div",{className:`text-center py-12 ${t?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-4xl mb-4",children:"📋"}),e.jsx("p",{className:"text-lg font-medium mb-2",children:i.length===0?"No execution logs yet":"No logs match your filter"}),e.jsx("p",{className:"text-sm",children:i.length===0?"Start graph execution to see live logs":"Try adjusting your search or filter"})]}):$.map(a=>C(a)),e.jsx("div",{ref:w})]})]})},Oe=({currentState:i,executionContext:t,darkMode:n})=>{const[o,f]=g.useState(new Set(["overview"])),[b,N]=g.useState(""),w=r=>{f(x=>{const h=new Set(x);return h.has(r)?h.delete(r):h.add(r),h})},m=r=>r===null?"null":r===void 0?"undefined":typeof r=="boolean"||typeof r=="number"?r.toString():typeof r=="string"?r.length>100?`${r.substring(0,100)}...`:r:Array.isArray(r)?`Array(${r.length})`:typeof r=="object"?`Object(${Object.keys(r).length} keys)`:String(r),d=r=>r==null?n?"text-gray-500":"text-gray-400":typeof r=="boolean"?n?"text-purple-400":"text-purple-600":typeof r=="number"?n?"text-blue-400":"text-blue-600":typeof r=="string"?n?"text-green-400":"text-green-600":Array.isArray(r)?n?"text-orange-400":"text-orange-600":typeof r=="object"?n?"text-cyan-400":"text-cyan-600":n?"text-gray-300":"text-gray-700",_=r=>r==null?"∅":typeof r=="boolean"?r?"✓":"✗":typeof r=="number"?"#":typeof r=="string"?'"':Array.isArray(r)?"[]":typeof r=="object"?"{}":"?",l=Object.entries(i||{}).filter(([r,x])=>b?r.toLowerCase().includes(b.toLowerCase())||String(x).toLowerCase().includes(b.toLowerCase()):!0),y={totalSteps:t.logs.length,errors:t.logs.filter(r=>r.type==="error").length,duration:t.startTime?(t.endTime||new Date).getTime()-t.startTime.getTime():0,status:t.isExecuting?t.isPaused?"Paused":"Running":"Idle"};return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:`p-4 border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:`text-sm font-semibold ${n?"text-white":"text-gray-900"}`,children:"Current State"}),e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:[Object.keys(i||{}).length," fields"]})})]}),e.jsx("input",{type:"text",placeholder:"Search state fields...",value:b,onChange:r=>N(r.target.value),className:`w-full px-3 py-2 text-xs border rounded-lg ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("overview"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("overview")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Execution Overview"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${y.status==="Running"?"bg-blue-100 text-blue-700":y.status==="Paused"?"bg-orange-100 text-orange-700":"bg-gray-100 text-gray-700"}`,children:y.status})]})}),o.has("overview")&&e.jsx("div",{className:`px-4 pb-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Total Steps"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.totalSteps})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Errors"}),e.jsx("div",{className:`text-lg font-bold ${y.errors>0?"text-red-500":n?"text-white":"text-gray-900"}`,children:y.errors})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Duration"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:y.duration>0?`${(y.duration/1e3).toFixed(1)}s`:"0s"})]}),e.jsxs("div",{className:`p-3 rounded-lg ${n?"bg-gray-700":"bg-white"}`,children:[e.jsx("div",{className:`text-xs font-medium ${n?"text-gray-400":"text-gray-500"}`,children:"Breakpoints"}),e.jsx("div",{className:`text-lg font-bold ${n?"text-white":"text-gray-900"}`,children:t.breakpoints.filter(r=>r.enabled).length})]})]})})]}),e.jsxs("div",{className:`border-b ${n?"border-gray-600":"border-gray-200"}`,children:[e.jsx("button",{onClick:()=>w("fields"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("fields")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"State Fields"})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded ${n?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:l.length})]})}),o.has("fields")&&e.jsx("div",{className:"space-y-1",children:l.length===0?e.jsxs("div",{className:`p-4 text-center ${n?"text-gray-400":"text-gray-500"}`,children:[e.jsx("div",{className:"text-2xl mb-2",children:"📭"}),e.jsx("p",{className:"text-sm",children:Object.keys(i||{}).length===0?"No state data":"No fields match your search"})]}):l.map(([r,x])=>e.jsxs("div",{className:`p-3 border-l-4 transition-colors ${n?"border-l-gray-600 hover:bg-gray-700":"border-l-gray-200 hover:bg-gray-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[e.jsx("span",{className:`text-sm ${d(x)}`,children:_(x)}),e.jsx("span",{className:`font-medium text-sm truncate ${n?"text-white":"text-gray-900"}`,children:r})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded font-mono ${n?"bg-gray-800 text-gray-300":"bg-gray-100 text-gray-600"}`,children:typeof x})]}),e.jsx("div",{className:`mt-1 text-xs font-mono ${d(x)}`,children:m(x)})]},r))})]}),e.jsxs("div",{children:[e.jsx("button",{onClick:()=>w("raw"),className:`w-full p-4 text-left hover:bg-opacity-50 transition-colors ${n?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${o.has("raw")?"rotate-90":""} ${n?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),e.jsx("span",{className:`font-medium ${n?"text-white":"text-gray-900"}`,children:"Raw JSON"})]})}),o.has("raw")&&e.jsx("div",{className:`p-4 ${n?"bg-gray-800":"bg-gray-50"}`,children:e.jsx("pre",{className:`text-xs font-mono p-3 rounded-lg overflow-x-auto ${n?"bg-gray-900 text-gray-300":"bg-white text-gray-800"}`,children:JSON.stringify(i||{},null,2)})})]})]})]})},Ae=()=>{const{graphState:i,darkMode:t,error:n,executionContext:o,selectedAssistant:f,resumeExecution:b,stopExecution:N,setGraphExecutionState:w,addBreakpoint:m,removeBreakpoint:d,startGlobalExecution:_}=V(),[l,y]=g.useState(null),[r,x]=g.useState(1),[h,$]=g.useState({x:0,y:0}),[u,S]=g.useState(!1),[p,C]=g.useState("bottom"),[a,L]=g.useState(!1),[j,Y]=g.useState({x:0,y:0}),[G,K]=g.useState(null),[z,U]=g.useState("input"),[de,xe]=g.useState(null),[ne,R]=g.useState(null),I=g.useRef(null),ae=g.useRef(null),[Q,ie]=g.useState(null),M=(Array.isArray(f?.metadata?.capabilities)?f.metadata.capabilities:Array.isArray(f?.config?.capabilities)?f.config.capabilities:[]).includes("breakpoints"),ge=(s,c)=>{ie({nodeId:s,position:c})},oe=()=>{ie(null)};g.useEffect(()=>{o.isExecuting&&!o.isPaused&&U("logs")},[o.isExecuting,o.isPaused]),g.useEffect(()=>{ae.current&&ae.current.scrollIntoView({behavior:"smooth"})},[o.logs]),g.useEffect(()=>{i?.currentNode&&o.isExecuting&&!o.isPaused&&ee(i.currentNode)},[i?.currentNode,o.isExecuting,o.isPaused]),g.useEffect(()=>{const{selectedThread:s,selectedAssistant:c}=V.getState();if(s&&c){const v=`${s.name} • ${c.name}`;R(v),setTimeout(()=>R(null),3e3)}},[o.threadId,o.assistantId]);const ee=s=>{const c=i?.nodes?.find(q=>q.id===s);if(!c||!I.current)return;const v=I.current.getBoundingClientRect(),E=v.width,T=v.height,X=E/2-c.position.x*r-80,J=T/2-c.position.y*r-50,O={...h},k={x:X,y:J},H=800,A=Date.now(),B=()=>{const q=Date.now()-A,Z=Math.min(q/H,1),D=(W=>W<.5?4*W*W*W:(W-1)*(2*W-2)*(2*W-2)+1)(Z),P={x:O.x+(k.x-O.x)*D,y:O.y+(k.y-O.y)*D};$(P),Z<1&&requestAnimationFrame(B)};requestAnimationFrame(B)},te=()=>{if(i?.nodes?.length===0||!I.current)return;const s=i.nodes.reduce((D,P)=>({minX:Math.min(D.minX,P.position.x),maxX:Math.max(D.maxX,P.position.x+160),minY:Math.min(D.minY,P.position.y),maxY:Math.max(D.maxY,P.position.y+100)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0}),c=50,v=s.maxX-s.minX+c*2,E=s.maxY-s.minY+c*2,T=I.current.clientWidth,X=I.current.clientHeight,J=T/v,O=X/E,k=Math.min(J,O,1),H={x:-(s.minX-c)*k+(T-v*k)/2,y:-(s.minY-c)*k+(X-E*k)/2},A=r,B={...h},q=1e3,Z=Date.now(),se=()=>{const D=Date.now()-Z,P=Math.min(D/q,1),re=(F=>F<.5?4*F*F*F:(F-1)*(2*F-2)*(2*F-2)+1)(P),je=A+(k-A)*re,ve={x:B.x+(H.x-B.x)*re,y:B.y+(H.y-B.y)*re};x(je),$(ve),P<1&&requestAnimationFrame(se)};requestAnimationFrame(se)};if(g.useEffect(()=>{const s=V.getState();s.focusOnNode=ee,s.fitGraphToView=te},[r,h,i?.nodes]),g.useEffect(()=>{const s=I.current;if(!s)return;const c=v=>{v.preventDefault();const E=v.deltaY>0?-.02:.02;x(T=>Math.max(.1,Math.min(3,T+E)))};return s.addEventListener("wheel",c,{passive:!1}),()=>s.removeEventListener("wheel",c)},[]),!i)return e.jsx("div",{className:`flex items-center justify-center h-full ${t?"bg-gray-800 text-white":"bg-white text-gray-900"}`,children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{children:"Loading graph state..."})]})});const he=s=>{y(l===s?null:s),u&&S(!1),U("logs");const c=o.logs.filter(v=>v.nodeId===s);if(c.length>0){const v=c[c.length-1];K(v.id);const E=i.nodes.find(T=>T.id===s)?.data.label||s;R(`📋 Showing ${c.length} logs for ${E}`),setTimeout(()=>R(null),3e3),console.log(`Showing execution logs for node: ${s}`,{totalLogs:c.length,mostRecentLog:v,nodeState:o.currentState})}else{const v=i.nodes.find(E=>E.id===s)?.data.label||s;R(`ℹ️ No execution logs found for ${v}`),setTimeout(()=>R(null),2e3),console.log(`No execution logs found for node: ${s}`),K(null)}},me=s=>{if(!M){R("This agent does not publish server-side breakpoint support."),setTimeout(()=>R(null),3e3);return}o.breakpoints.some(v=>v.nodeId===s)?d(s):m(s)},ue=async(s={})=>{const c=s??{},v=c&&typeof c=="object"&&!Array.isArray(c)?c:{},E={context:{source:"graph"},timestamp:new Date().toISOString(),...v},{selectedThread:T,addMessageToThread:X,createPersistentThread:J}=V.getState();let O=T;if(!O){if(!f?.id){ce.error("Select a live Agentomatic agent before running the graph.");return}try{O=await J(f.id,"Graph Execution")}catch(A){ce.error(A instanceof Error?A.message:"Could not create a durable graph conversation.");return}}const k=JSON.stringify(c,null,2),H={id:`msg-${Date.now()}-graph-user`,role:"user",content:`🔄 **Graph Execution Initiated** \`\`\`json ${k} diff --git a/src/agentomatic/studio/static/assets/IngestorsView-Cd56f61k.js b/src/agentomatic/studio/static/assets/IngestorsView-Be0ZMvN2.js similarity index 95% rename from src/agentomatic/studio/static/assets/IngestorsView-Cd56f61k.js rename to src/agentomatic/studio/static/assets/IngestorsView-Be0ZMvN2.js index 1d667135..b50f4ad9 100644 --- a/src/agentomatic/studio/static/assets/IngestorsView-Cd56f61k.js +++ b/src/agentomatic/studio/static/assets/IngestorsView-Be0ZMvN2.js @@ -1 +1 @@ -import{u as F,A as S,d as $,j as a}from"./index-FSSL6O5F.js";import{r as s}from"./react-vendor-BHJ3EV8m.js";import{S as L}from"./SchemaForm-DyHc2s7z.js";import{O as _}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const B=()=>{const{config:o,darkMode:r}=F(),[v,I]=s.useState([]),[p,E]=s.useState({}),[x,C]=s.useState({}),[R,j]=s.useState({}),[N,O]=s.useState({}),[b,w]=s.useState(null),[i,g]=s.useState(!0),[h,m]=s.useState(null),y=s.useCallback(async()=>{if(!o?.apiUrl){g(!1);return}g(!0);try{const e=new S(o.apiUrl,o.apiKey||void 0),n=await e.listIngestors(),l=await Promise.all(n.map(async t=>{try{return{name:t.name,contract:await e.getOperationContract(`/api/v1/ingestion/${encodeURIComponent(t.name)}/run`),error:null}}catch(d){return{name:t.name,contract:null,error:d?.message||"Could not load run contract"}}})),u=Object.fromEntries(l.flatMap(t=>t.contract?[[t.name,t.contract]]:[])),f=Object.fromEntries(l.flatMap(t=>t.error?[[t.name,t.error]]:[]));I(n),E(u),C(f),j(t=>Object.fromEntries(n.map(d=>[d.name,t[d.name]??$(u[d.name]?.input_schema||void 0)]))),m(null)}catch(e){m(e?.message||"Failed to fetch ingestors")}finally{g(!1)}},[o?.apiUrl,o?.apiKey]);s.useEffect(()=>{y()},[y]);const U=async(e,n)=>{if(o?.apiUrl){w(e.name),m(null);try{const u=await new S(o.apiUrl,o.apiKey||void 0).runIngestor(e.name,n);O(f=>({...f,[e.name]:u}))}catch(l){m(l?.message||`Failed to run ingestor '${e.name}'`)}finally{w(null)}}},k=r?"bg-gray-800 border-gray-700":"bg-white border-gray-200",c=r?"text-gray-400":"text-gray-600";return a.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[a.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold",children:"Ingestors"}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:"Run each live ingestion resource independently. Input forms and expected output are read from the deployed OpenAPI contract."})]}),a.jsx("button",{type:"button",onClick:()=>{y()},disabled:i||b!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:i?"Refreshing…":"Refresh"})]}),i&&a.jsx("div",{className:c,children:"Loading ingestors…"}),h&&a.jsx("div",{role:"alert",className:`mb-4 rounded-lg border p-4 ${r?"border-red-800 bg-red-900/30 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:h}),!i&&!h&&v.length===0&&a.jsx("div",{className:c,children:"No ingestors registered."}),a.jsx("div",{className:"grid grid-cols-1 gap-6 xl:grid-cols-2",children:v.map(e=>a.jsxs("section",{className:`rounded-xl border p-5 shadow-sm sm:p-6 ${k}`,children:[a.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("h2",{className:"truncate text-lg font-semibold",children:e.name}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:e.description||"No description provided"})]}),a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs",children:[a.jsx("span",{className:`h-2 w-2 rounded-full ${e.ready?"bg-green-500":"bg-gray-400"}`}),e.ready?"Ready":"Idle"]})]}),a.jsxs("div",{className:`mb-4 flex flex-wrap gap-2 text-xs ${c}`,children:[a.jsxs("span",{className:`rounded px-2 py-0.5 font-mono ${r?"bg-teal-950 text-teal-200":"bg-teal-50 text-teal-800"}`,children:["POST /api/v1/ingestion/",e.name,"/run"]}),a.jsxs("span",{children:["v",e.version]})]}),a.jsxs("div",{className:`space-y-3 border-t pt-4 ${r?"border-gray-700":"border-gray-200"}`,children:[x[e.name]&&a.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live run contract unavailable: ",x[e.name],". Execution stays disabled until the deployed schema can be read."]}),a.jsx(L,{schema:p[e.name]?.input_schema,value:R[e.name]??$(p[e.name]?.input_schema||void 0),onChange:n=>j(l=>({...l,[e.name]:n})),onSubmit:n=>{U(e,n)},submitLabel:b===e.name?"Running ingestor…":"Run ingestor",disabled:b!==null||!e.ready||!!x[e.name],darkMode:r}),a.jsx(_,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]!==void 0&&a.jsx("pre",{className:`mt-4 max-h-64 overflow-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${r?"bg-gray-950 text-gray-200":"bg-gray-50 text-gray-800"}`,children:JSON.stringify(N[e.name],null,2)})]},e.name))})]})};export{B as IngestorsView}; +import{u as F,A as S,d as $,j as a}from"./index-BMj1jeBL.js";import{r as s}from"./react-vendor-BHJ3EV8m.js";import{S as L}from"./SchemaForm-Kr1WPDMd.js";import{O as _}from"./OutputSchemaSummary-CiE3pU-0.js";import"./syntax-vendor-ru7AzRyY.js";const B=()=>{const{config:o,darkMode:r}=F(),[v,I]=s.useState([]),[p,E]=s.useState({}),[x,C]=s.useState({}),[R,j]=s.useState({}),[N,O]=s.useState({}),[b,w]=s.useState(null),[i,g]=s.useState(!0),[h,m]=s.useState(null),y=s.useCallback(async()=>{if(!o?.apiUrl){g(!1);return}g(!0);try{const e=new S(o.apiUrl,o.apiKey||void 0),n=await e.listIngestors(),l=await Promise.all(n.map(async t=>{try{return{name:t.name,contract:await e.getOperationContract(`/api/v1/ingestion/${encodeURIComponent(t.name)}/run`),error:null}}catch(d){return{name:t.name,contract:null,error:d?.message||"Could not load run contract"}}})),u=Object.fromEntries(l.flatMap(t=>t.contract?[[t.name,t.contract]]:[])),f=Object.fromEntries(l.flatMap(t=>t.error?[[t.name,t.error]]:[]));I(n),E(u),C(f),j(t=>Object.fromEntries(n.map(d=>[d.name,t[d.name]??$(u[d.name]?.input_schema||void 0)]))),m(null)}catch(e){m(e?.message||"Failed to fetch ingestors")}finally{g(!1)}},[o?.apiUrl,o?.apiKey]);s.useEffect(()=>{y()},[y]);const U=async(e,n)=>{if(o?.apiUrl){w(e.name),m(null);try{const u=await new S(o.apiUrl,o.apiKey||void 0).runIngestor(e.name,n);O(f=>({...f,[e.name]:u}))}catch(l){m(l?.message||`Failed to run ingestor '${e.name}'`)}finally{w(null)}}},k=r?"bg-gray-800 border-gray-700":"bg-white border-gray-200",c=r?"text-gray-400":"text-gray-600";return a.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[a.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold",children:"Ingestors"}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:"Run each live ingestion resource independently. Input forms and expected output are read from the deployed OpenAPI contract."})]}),a.jsx("button",{type:"button",onClick:()=>{y()},disabled:i||b!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:i?"Refreshing…":"Refresh"})]}),i&&a.jsx("div",{className:c,children:"Loading ingestors…"}),h&&a.jsx("div",{role:"alert",className:`mb-4 rounded-lg border p-4 ${r?"border-red-800 bg-red-900/30 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:h}),!i&&!h&&v.length===0&&a.jsx("div",{className:c,children:"No ingestors registered."}),a.jsx("div",{className:"grid grid-cols-1 gap-6 xl:grid-cols-2",children:v.map(e=>a.jsxs("section",{className:`rounded-xl border p-5 shadow-sm sm:p-6 ${k}`,children:[a.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("h2",{className:"truncate text-lg font-semibold",children:e.name}),a.jsx("p",{className:`mt-1 text-sm ${c}`,children:e.description||"No description provided"})]}),a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs",children:[a.jsx("span",{className:`h-2 w-2 rounded-full ${e.ready?"bg-green-500":"bg-gray-400"}`}),e.ready?"Ready":"Idle"]})]}),a.jsxs("div",{className:`mb-4 flex flex-wrap gap-2 text-xs ${c}`,children:[a.jsxs("span",{className:`rounded px-2 py-0.5 font-mono ${r?"bg-teal-950 text-teal-200":"bg-teal-50 text-teal-800"}`,children:["POST /api/v1/ingestion/",e.name,"/run"]}),a.jsxs("span",{children:["v",e.version]})]}),a.jsxs("div",{className:`space-y-3 border-t pt-4 ${r?"border-gray-700":"border-gray-200"}`,children:[x[e.name]&&a.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live run contract unavailable: ",x[e.name],". Execution stays disabled until the deployed schema can be read."]}),a.jsx(L,{schema:p[e.name]?.input_schema,value:R[e.name]??$(p[e.name]?.input_schema||void 0),onChange:n=>j(l=>({...l,[e.name]:n})),onSubmit:n=>{U(e,n)},submitLabel:b===e.name?"Running ingestor…":"Run ingestor",disabled:b!==null||!e.ready||!!x[e.name],darkMode:r}),a.jsx(_,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]!==void 0&&a.jsx("pre",{className:`mt-4 max-h-64 overflow-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${r?"bg-gray-950 text-gray-200":"bg-gray-50 text-gray-800"}`,children:JSON.stringify(N[e.name],null,2)})]},e.name))})]})};export{B as IngestorsView}; diff --git a/src/agentomatic/studio/static/assets/OutputSchemaSummary-C65WaRqI.js b/src/agentomatic/studio/static/assets/OutputSchemaSummary-CiE3pU-0.js similarity index 97% rename from src/agentomatic/studio/static/assets/OutputSchemaSummary-C65WaRqI.js rename to src/agentomatic/studio/static/assets/OutputSchemaSummary-CiE3pU-0.js index a63b8ac3..883b122c 100644 --- a/src/agentomatic/studio/static/assets/OutputSchemaSummary-C65WaRqI.js +++ b/src/agentomatic/studio/static/assets/OutputSchemaSummary-CiE3pU-0.js @@ -1 +1 @@ -import{q as c,i as o,j as e}from"./index-FSSL6O5F.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";const y=({schema:a,source:r,darkMode:t=!1,className:i=""})=>{const[l,m]=g.useState(!1),x=c(a||void 0),n=o(a||void 0);return e.jsxs("div",{className:`rounded-lg border ${t?"border-gray-600 bg-gray-800/50":"border-gray-200 bg-gray-50"} ${i}`,children:[e.jsxs("button",{type:"button",onClick:()=>m(s=>!s),className:`w-full flex items-center justify-between px-3 py-2 text-left ${t?"hover:bg-gray-700/50":"hover:bg-gray-100"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`text-xs font-semibold ${t?"text-gray-200":"text-gray-800"}`,children:"Expected output"}),r?.source&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-medium ${r.source==="custom"?t?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":t?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${r.convention||r.source}`,children:[r.source==="custom"?"Custom":"Default",r.model?` · ${r.model}`:""]})]}),e.jsx("div",{className:`text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:n?"No output schema available":`${x.length} field${x.length===1?"":"s"}`})]}),e.jsx("svg",{className:`w-4 h-4 transition-transform ${l?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),l&&e.jsxs("div",{className:`px-3 pb-3 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[n?e.jsx("p",{className:`text-[10px] mt-2 italic ${t?"text-gray-500":"text-gray-400"}`,children:"Agent did not expose an output schema."}):e.jsx("ul",{className:"mt-2 space-y-1.5",children:x.map(s=>e.jsxs("li",{className:"text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("code",{className:`px-1.5 py-0.5 rounded font-mono text-[10px] ${t?"bg-gray-700 text-blue-300":"bg-white text-blue-700 border border-gray-200"}`,children:s.name}),e.jsx("span",{className:`text-[10px] ${t?"text-gray-400":"text-gray-500"}`,children:s.type}),s.required&&e.jsx("span",{className:"text-[10px] text-red-500 font-medium",children:"required"})]}),s.description&&e.jsx("p",{className:`mt-0.5 text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:s.description})]},s.name))}),!n&&e.jsxs("details",{className:"mt-2",children:[e.jsx("summary",{className:`text-[10px] cursor-pointer ${t?"text-gray-400":"text-gray-500"}`,children:"View raw schema"}),e.jsx("pre",{className:`mt-1 p-2 rounded text-[10px] font-mono overflow-x-auto max-h-40 ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-700 border border-gray-200"}`,children:JSON.stringify(a,null,2)})]})]})]})};export{y as O}; +import{q as c,i as o,j as e}from"./index-BMj1jeBL.js";import{r as g}from"./react-vendor-BHJ3EV8m.js";const y=({schema:a,source:r,darkMode:t=!1,className:i=""})=>{const[l,m]=g.useState(!1),x=c(a||void 0),n=o(a||void 0);return e.jsxs("div",{className:`rounded-lg border ${t?"border-gray-600 bg-gray-800/50":"border-gray-200 bg-gray-50"} ${i}`,children:[e.jsxs("button",{type:"button",onClick:()=>m(s=>!s),className:`w-full flex items-center justify-between px-3 py-2 text-left ${t?"hover:bg-gray-700/50":"hover:bg-gray-100"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`text-xs font-semibold ${t?"text-gray-200":"text-gray-800"}`,children:"Expected output"}),r?.source&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-medium ${r.source==="custom"?t?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":t?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${r.convention||r.source}`,children:[r.source==="custom"?"Custom":"Default",r.model?` · ${r.model}`:""]})]}),e.jsx("div",{className:`text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:n?"No output schema available":`${x.length} field${x.length===1?"":"s"}`})]}),e.jsx("svg",{className:`w-4 h-4 transition-transform ${l?"rotate-90":""} ${t?"text-gray-400":"text-gray-500"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),l&&e.jsxs("div",{className:`px-3 pb-3 border-t ${t?"border-gray-700":"border-gray-200"}`,children:[n?e.jsx("p",{className:`text-[10px] mt-2 italic ${t?"text-gray-500":"text-gray-400"}`,children:"Agent did not expose an output schema."}):e.jsx("ul",{className:"mt-2 space-y-1.5",children:x.map(s=>e.jsxs("li",{className:"text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("code",{className:`px-1.5 py-0.5 rounded font-mono text-[10px] ${t?"bg-gray-700 text-blue-300":"bg-white text-blue-700 border border-gray-200"}`,children:s.name}),e.jsx("span",{className:`text-[10px] ${t?"text-gray-400":"text-gray-500"}`,children:s.type}),s.required&&e.jsx("span",{className:"text-[10px] text-red-500 font-medium",children:"required"})]}),s.description&&e.jsx("p",{className:`mt-0.5 text-[10px] ${t?"text-gray-500":"text-gray-400"}`,children:s.description})]},s.name))}),!n&&e.jsxs("details",{className:"mt-2",children:[e.jsx("summary",{className:`text-[10px] cursor-pointer ${t?"text-gray-400":"text-gray-500"}`,children:"View raw schema"}),e.jsx("pre",{className:`mt-1 p-2 rounded text-[10px] font-mono overflow-x-auto max-h-40 ${t?"bg-gray-900 text-gray-300":"bg-white text-gray-700 border border-gray-200"}`,children:JSON.stringify(a,null,2)})]})]})]})};export{y as O}; diff --git a/src/agentomatic/studio/static/assets/PipelinesView-DacXbEMw.js b/src/agentomatic/studio/static/assets/PipelinesView-Yvdzmlvq.js similarity index 96% rename from src/agentomatic/studio/static/assets/PipelinesView-DacXbEMw.js rename to src/agentomatic/studio/static/assets/PipelinesView-Yvdzmlvq.js index ca7cfa5a..ad616663 100644 --- a/src/agentomatic/studio/static/assets/PipelinesView-DacXbEMw.js +++ b/src/agentomatic/studio/static/assets/PipelinesView-Yvdzmlvq.js @@ -1 +1 @@ -import{u as _,A as E,p as $,a as K,j as t}from"./index-FSSL6O5F.js";import{r as n}from"./react-vendor-BHJ3EV8m.js";import{S as A}from"./SchemaForm-DyHc2s7z.js";import{O as I}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const z=()=>{const{config:o,darkMode:r,setCurrentView:C,setBuilderPipelineToLoad:P}=_(),[y,R]=n.useState([]),[c,u]=n.useState(!0),[x,v]=n.useState(null),[f,k]=n.useState({}),[b,O]=n.useState({}),[L,j]=n.useState({}),[g,N]=n.useState(null),[d,B]=n.useState({}),[w,S]=n.useState(null),h=n.useCallback(async()=>{if(!o?.apiUrl){u(!1);return}u(!0);try{const e=new E(o.apiUrl,o.apiKey||void 0),s=await e.listPipelines(),l=await Promise.all(s.map(async a=>{try{const i=await e.getPipelineConfig(a.name);return{name:a.name,schema:{input:$(i.input_schema),output:$(i.output_schema)},error:null}}catch(i){return{name:a.name,schema:{input:null,output:null},error:i?.message||"Could not load pipeline contract"}}})),m=Object.fromEntries(l.map(a=>[a.name,a.schema])),p=Object.fromEntries(l.flatMap(a=>a.error?[[a.name,a.error]]:[]));R(s),k(m),O(p),j(a=>Object.fromEntries(s.map(i=>[i.name,a[i.name]??K(m[i.name]?.input||void 0)]))),v(null)}catch(e){v(e.message||"Failed to fetch pipelines")}finally{u(!1)}},[o?.apiUrl,o?.apiKey]);n.useEffect(()=>{h()},[h]);const U=async(e,s)=>{if(o?.apiUrl){N(e),S(null);try{const m=await new E(o.apiUrl,o.apiKey||void 0).runPipeline(e,{input:s});B(p=>({...p,[e]:m}))}catch(l){S(l?.message||`Failed to run pipeline '${e}'`)}finally{N(null)}}},F=e=>{P(e),C("builder")};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Pipelines"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Run live pipeline contracts independently and refresh their deployed schemas without reconnecting."})]}),t.jsx("button",{type:"button",onClick:()=>{h()},disabled:c||g!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:c?"Refreshing…":"Refresh"})]}),c&&t.jsx("div",{className:"text-gray-500",children:"Loading pipelines..."}),x&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:x}),w&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:w}),!c&&!x&&y.length===0&&t.jsx("div",{className:"text-gray-500",children:"No pipelines found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:y.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm`,children:[t.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[t.jsx("h2",{className:"min-w-0 truncate text-lg font-semibold",children:e.name}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-blue-900 text-blue-200":"bg-blue-100 text-blue-800"}`,children:["v",e.version]}),t.jsx("button",{type:"button",onClick:()=>F(e.name),className:`rounded-lg border px-2.5 py-1.5 text-xs font-semibold transition-colors ${r?"border-violet-700 bg-violet-950/50 text-violet-200 hover:bg-violet-900/70":"border-violet-200 bg-violet-50 text-violet-800 hover:bg-violet-100"}`,title:`Load ${e.name} into the visual Builder`,children:"Edit in Builder"})]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4",children:[t.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2",children:"Steps"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:e.steps.map((s,l)=>t.jsx("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:s},l))})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[b[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live pipeline contract unavailable: ",b[e.name],". Running stays disabled until the deployed schema can be read."]}),t.jsx(A,{schema:f[e.name]?.input,value:L[e.name]||{},onChange:s=>j(l=>({...l,[e.name]:s})),onSubmit:s=>{U(e.name,s)},submitLabel:g===e.name?"Running pipeline…":"Run pipeline",disabled:g!==null||!!b[e.name],darkMode:r}),t.jsx(I,{schema:f[e.name]?.output,darkMode:r})]}),d[e.name]&&t.jsxs("div",{className:`mt-4 rounded-lg p-3 text-xs ${r?"bg-gray-900":"bg-gray-50"}`,children:[t.jsxs("div",{className:"font-medium mb-2",children:[d[e.name].status," · ",d[e.name].duration_ms," ms"]}),t.jsx("pre",{className:"whitespace-pre-wrap break-words",children:JSON.stringify(d[e.name].output,null,2)}),t.jsx("div",{className:"mt-3 border-t border-gray-200 pt-2 dark:border-gray-700",children:Object.values(d[e.name].steps).map(s=>t.jsxs("div",{className:"flex justify-between gap-2 py-0.5 font-mono",children:[t.jsx("span",{children:s.name}),t.jsxs("span",{children:[s.status," · ",s.duration_ms," ms"]})]},s.name))})]})]},e.name))})]})};export{z as PipelinesView}; +import{u as _,A as E,p as $,a as K,j as t}from"./index-BMj1jeBL.js";import{r as n}from"./react-vendor-BHJ3EV8m.js";import{S as A}from"./SchemaForm-Kr1WPDMd.js";import{O as I}from"./OutputSchemaSummary-CiE3pU-0.js";import"./syntax-vendor-ru7AzRyY.js";const z=()=>{const{config:o,darkMode:r,setCurrentView:C,setBuilderPipelineToLoad:P}=_(),[y,R]=n.useState([]),[c,u]=n.useState(!0),[x,v]=n.useState(null),[f,k]=n.useState({}),[b,O]=n.useState({}),[L,j]=n.useState({}),[g,N]=n.useState(null),[d,B]=n.useState({}),[w,S]=n.useState(null),h=n.useCallback(async()=>{if(!o?.apiUrl){u(!1);return}u(!0);try{const e=new E(o.apiUrl,o.apiKey||void 0),s=await e.listPipelines(),l=await Promise.all(s.map(async a=>{try{const i=await e.getPipelineConfig(a.name);return{name:a.name,schema:{input:$(i.input_schema),output:$(i.output_schema)},error:null}}catch(i){return{name:a.name,schema:{input:null,output:null},error:i?.message||"Could not load pipeline contract"}}})),m=Object.fromEntries(l.map(a=>[a.name,a.schema])),p=Object.fromEntries(l.flatMap(a=>a.error?[[a.name,a.error]]:[]));R(s),k(m),O(p),j(a=>Object.fromEntries(s.map(i=>[i.name,a[i.name]??K(m[i.name]?.input||void 0)]))),v(null)}catch(e){v(e.message||"Failed to fetch pipelines")}finally{u(!1)}},[o?.apiUrl,o?.apiKey]);n.useEffect(()=>{h()},[h]);const U=async(e,s)=>{if(o?.apiUrl){N(e),S(null);try{const m=await new E(o.apiUrl,o.apiKey||void 0).runPipeline(e,{input:s});B(p=>({...p,[e]:m}))}catch(l){S(l?.message||`Failed to run pipeline '${e}'`)}finally{N(null)}}},F=e=>{P(e),C("builder")};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Pipelines"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Run live pipeline contracts independently and refresh their deployed schemas without reconnecting."})]}),t.jsx("button",{type:"button",onClick:()=>{h()},disabled:c||g!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:c?"Refreshing…":"Refresh"})]}),c&&t.jsx("div",{className:"text-gray-500",children:"Loading pipelines..."}),x&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:x}),w&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:w}),!c&&!x&&y.length===0&&t.jsx("div",{className:"text-gray-500",children:"No pipelines found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:y.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm`,children:[t.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[t.jsx("h2",{className:"min-w-0 truncate text-lg font-semibold",children:e.name}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-blue-900 text-blue-200":"bg-blue-100 text-blue-800"}`,children:["v",e.version]}),t.jsx("button",{type:"button",onClick:()=>F(e.name),className:`rounded-lg border px-2.5 py-1.5 text-xs font-semibold transition-colors ${r?"border-violet-700 bg-violet-950/50 text-violet-200 hover:bg-violet-900/70":"border-violet-200 bg-violet-50 text-violet-800 hover:bg-violet-100"}`,title:`Load ${e.name} into the visual Builder`,children:"Edit in Builder"})]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4",children:[t.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2",children:"Steps"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:e.steps.map((s,l)=>t.jsx("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-700"}`,children:s},l))})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[b[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live pipeline contract unavailable: ",b[e.name],". Running stays disabled until the deployed schema can be read."]}),t.jsx(A,{schema:f[e.name]?.input,value:L[e.name]||{},onChange:s=>j(l=>({...l,[e.name]:s})),onSubmit:s=>{U(e.name,s)},submitLabel:g===e.name?"Running pipeline…":"Run pipeline",disabled:g!==null||!!b[e.name],darkMode:r}),t.jsx(I,{schema:f[e.name]?.output,darkMode:r})]}),d[e.name]&&t.jsxs("div",{className:`mt-4 rounded-lg p-3 text-xs ${r?"bg-gray-900":"bg-gray-50"}`,children:[t.jsxs("div",{className:"font-medium mb-2",children:[d[e.name].status," · ",d[e.name].duration_ms," ms"]}),t.jsx("pre",{className:"whitespace-pre-wrap break-words",children:JSON.stringify(d[e.name].output,null,2)}),t.jsx("div",{className:"mt-3 border-t border-gray-200 pt-2 dark:border-gray-700",children:Object.values(d[e.name].steps).map(s=>t.jsxs("div",{className:"flex justify-between gap-2 py-0.5 font-mono",children:[t.jsx("span",{children:s.name}),t.jsxs("span",{children:[s.status," · ",s.duration_ms," ms"]})]},s.name))})]})]},e.name))})]})};export{z as PipelinesView}; diff --git a/src/agentomatic/studio/static/assets/PluginsView-COAn7Q5V.js b/src/agentomatic/studio/static/assets/PluginsView-BCct6WZb.js similarity index 96% rename from src/agentomatic/studio/static/assets/PluginsView-COAn7Q5V.js rename to src/agentomatic/studio/static/assets/PluginsView-BCct6WZb.js index 5bf2186a..13cfc03d 100644 --- a/src/agentomatic/studio/static/assets/PluginsView-COAn7Q5V.js +++ b/src/agentomatic/studio/static/assets/PluginsView-BCct6WZb.js @@ -1 +1 @@ -import{u as J,A as C,d as P,j as t}from"./index-FSSL6O5F.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as K}from"./SchemaForm-DyHc2s7z.js";import{O as A}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const G=()=>{const{config:c,darkMode:r}=J(),[v,j]=d.useState([]),[u,x]=d.useState(!0),[g,l]=d.useState(null),[p,E]=d.useState({}),[h,k]=d.useState({}),[M,w]=d.useState({}),[i,m]=d.useState(null),[N,O]=d.useState({}),[$,_]=d.useState({}),[S,L]=d.useState({}),y=d.useCallback(async()=>{if(!c?.apiUrl){x(!1);return}x(!0);try{const e=new C(c.apiUrl,c.apiKey||void 0),a=await e.listPlugins(),s=await Promise.all(a.map(async o=>{try{return{name:o.name,contract:await e.getOperationContract(`/api/v1/plugins/${encodeURIComponent(o.name)}/predict`),error:null}}catch(b){return{name:o.name,contract:null,error:b?.message||"Could not load predict contract"}}})),n=Object.fromEntries(s.flatMap(o=>o.contract?[[o.name,o.contract]]:[])),B=Object.fromEntries(s.flatMap(o=>o.error?[[o.name,o.error]]:[]));j(a),E(n),k(B),w(o=>Object.fromEntries(a.map(b=>[b.name,o[b.name]??P(n[b.name]?.input_schema||void 0)]))),l(null)}catch(e){l(e.message||"Failed to fetch plugins")}finally{x(!1)}},[c?.apiUrl,c?.apiKey]);d.useEffect(()=>{y()},[y]);const f=()=>new C(c.apiUrl,c.apiKey||void 0),R=async e=>{m(`card:${e}`),l(null);try{const a=await f().getPluginModelCard(e);O(s=>({...s,[e]:a}))}catch(a){l(a?.message||`Failed to load model card for '${e}'`)}finally{m(null)}},F=async(e,a)=>{m(`predict:${e}`),l(null);try{const s=await f().runPluginPredict(e,a);_(n=>({...n,[e]:s}))}catch(s){l(s?.message||`Failed to run '${e}'`)}finally{m(null)}},U=async e=>{m(`reload:${e}`),l(null);try{const a=await f().reloadPlugin(e);L(s=>({...s,[e]:a})),j(s=>s.map(n=>n.name===e?{...n,is_loaded:!!a.is_loaded}:n))}catch(a){l(a?.message||`Failed to reload '${e}'`)}finally{m(null)}};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"ML Plugins"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Reload the live inventory and its published prediction contracts without reconnecting Studio."})]}),t.jsx("button",{type:"button",onClick:()=>{y()},disabled:u||i!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:u?"Refreshing…":"Refresh"})]}),u&&t.jsx("div",{className:"text-gray-500",children:"Loading plugins..."}),g&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:g}),!u&&!g&&v.length===0&&t.jsx("div",{className:"text-gray-500",children:"No ML plugins found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:v.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm flex flex-col justify-between`,children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-start mb-4",children:[t.jsx("h2",{className:"text-lg font-semibold",children:e.name}),t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-purple-900 text-purple-200":"bg-purple-100 text-purple-800"}`,children:["v",e.version]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4 flex items-center",children:[t.jsx("span",{className:`w-2 h-2 rounded-full mr-2 ${e.is_loaded?"bg-green-500":"bg-red-500"}`}),t.jsx("span",{className:"text-sm",children:e.is_loaded?"Loaded":"Unloaded"})]})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 flex flex-wrap justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{U(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-violet-800 hover:bg-violet-700":"bg-violet-100 text-violet-900 hover:bg-violet-200"}`,children:i===`reload:${e.name}`?"Reloading…":"Reload"}),t.jsx("button",{type:"button",onClick:()=>{R(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-gray-700 hover:bg-gray-600":"bg-gray-200 hover:bg-gray-300"}`,children:i===`card:${e.name}`?"Loading…":"Model Card"})]}),t.jsxs("div",{className:"space-y-3",children:[h[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live predict contract unavailable: ",h[e.name],". Prediction stays disabled until the deployed schema can be read."]}),t.jsx(K,{schema:p[e.name]?.input_schema,value:M[e.name]??P(p[e.name]?.input_schema||void 0),onChange:a=>w(s=>({...s,[e.name]:a})),onSubmit:a=>{F(e.name,a)},submitLabel:i===`predict:${e.name}`?"Predicting…":"Predict",disabled:i!==null||!e.is_loaded||!!h[e.name],darkMode:r}),t.jsx(A,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(N[e.name],null,2)}),S[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(S[e.name],null,2)}),$[e.name]!==void 0&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify($[e.name],null,2)})]},e.name))})]})};export{G as PluginsView}; +import{u as J,A as C,d as P,j as t}from"./index-BMj1jeBL.js";import{r as d}from"./react-vendor-BHJ3EV8m.js";import{S as K}from"./SchemaForm-Kr1WPDMd.js";import{O as A}from"./OutputSchemaSummary-CiE3pU-0.js";import"./syntax-vendor-ru7AzRyY.js";const G=()=>{const{config:c,darkMode:r}=J(),[v,j]=d.useState([]),[u,x]=d.useState(!0),[g,l]=d.useState(null),[p,E]=d.useState({}),[h,k]=d.useState({}),[M,w]=d.useState({}),[i,m]=d.useState(null),[N,O]=d.useState({}),[$,_]=d.useState({}),[S,L]=d.useState({}),y=d.useCallback(async()=>{if(!c?.apiUrl){x(!1);return}x(!0);try{const e=new C(c.apiUrl,c.apiKey||void 0),a=await e.listPlugins(),s=await Promise.all(a.map(async o=>{try{return{name:o.name,contract:await e.getOperationContract(`/api/v1/plugins/${encodeURIComponent(o.name)}/predict`),error:null}}catch(b){return{name:o.name,contract:null,error:b?.message||"Could not load predict contract"}}})),n=Object.fromEntries(s.flatMap(o=>o.contract?[[o.name,o.contract]]:[])),B=Object.fromEntries(s.flatMap(o=>o.error?[[o.name,o.error]]:[]));j(a),E(n),k(B),w(o=>Object.fromEntries(a.map(b=>[b.name,o[b.name]??P(n[b.name]?.input_schema||void 0)]))),l(null)}catch(e){l(e.message||"Failed to fetch plugins")}finally{x(!1)}},[c?.apiUrl,c?.apiKey]);d.useEffect(()=>{y()},[y]);const f=()=>new C(c.apiUrl,c.apiKey||void 0),R=async e=>{m(`card:${e}`),l(null);try{const a=await f().getPluginModelCard(e);O(s=>({...s,[e]:a}))}catch(a){l(a?.message||`Failed to load model card for '${e}'`)}finally{m(null)}},F=async(e,a)=>{m(`predict:${e}`),l(null);try{const s=await f().runPluginPredict(e,a);_(n=>({...n,[e]:s}))}catch(s){l(s?.message||`Failed to run '${e}'`)}finally{m(null)}},U=async e=>{m(`reload:${e}`),l(null);try{const a=await f().reloadPlugin(e);L(s=>({...s,[e]:a})),j(s=>s.map(n=>n.name===e?{...n,is_loaded:!!a.is_loaded}:n))}catch(a){l(a?.message||`Failed to reload '${e}'`)}finally{m(null)}};return t.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${r?"text-white bg-gray-900":"text-gray-900 bg-gray-50"}`,children:[t.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold",children:"ML Plugins"}),t.jsx("p",{className:`mt-1 text-sm ${r?"text-gray-400":"text-gray-600"}`,children:"Reload the live inventory and its published prediction contracts without reconnecting Studio."})]}),t.jsx("button",{type:"button",onClick:()=>{y()},disabled:u||i!==null,className:`rounded-lg border px-3 py-2 text-sm font-medium disabled:opacity-50 ${r?"border-gray-600 hover:bg-gray-800":"border-gray-300 hover:bg-gray-100"}`,children:u?"Refreshing…":"Refresh"})]}),u&&t.jsx("div",{className:"text-gray-500",children:"Loading plugins..."}),g&&t.jsx("div",{role:"alert",className:"text-red-500 mb-4",children:g}),!u&&!g&&v.length===0&&t.jsx("div",{className:"text-gray-500",children:"No ML plugins found."}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:v.map(e=>t.jsxs("div",{className:`p-6 rounded-xl border ${r?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} shadow-sm flex flex-col justify-between`,children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-start mb-4",children:[t.jsx("h2",{className:"text-lg font-semibold",children:e.name}),t.jsxs("span",{className:`px-2 py-1 rounded text-xs ${r?"bg-purple-900 text-purple-200":"bg-purple-100 text-purple-800"}`,children:["v",e.version]})]}),t.jsx("p",{className:`text-sm mb-4 ${r?"text-gray-400":"text-gray-600"}`,children:e.description||"No description provided"}),t.jsxs("div",{className:"mb-4 flex items-center",children:[t.jsx("span",{className:`w-2 h-2 rounded-full mr-2 ${e.is_loaded?"bg-green-500":"bg-red-500"}`}),t.jsx("span",{className:"text-sm",children:e.is_loaded?"Loaded":"Unloaded"})]})]}),t.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 flex flex-wrap justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{U(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-violet-800 hover:bg-violet-700":"bg-violet-100 text-violet-900 hover:bg-violet-200"}`,children:i===`reload:${e.name}`?"Reloading…":"Reload"}),t.jsx("button",{type:"button",onClick:()=>{R(e.name)},disabled:i!==null,className:`px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${r?"bg-gray-700 hover:bg-gray-600":"bg-gray-200 hover:bg-gray-300"}`,children:i===`card:${e.name}`?"Loading…":"Model Card"})]}),t.jsxs("div",{className:"space-y-3",children:[h[e.name]&&t.jsxs("p",{role:"status",className:`rounded-md border p-2 text-xs ${r?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live predict contract unavailable: ",h[e.name],". Prediction stays disabled until the deployed schema can be read."]}),t.jsx(K,{schema:p[e.name]?.input_schema,value:M[e.name]??P(p[e.name]?.input_schema||void 0),onChange:a=>w(s=>({...s,[e.name]:a})),onSubmit:a=>{F(e.name,a)},submitLabel:i===`predict:${e.name}`?"Predicting…":"Predict",disabled:i!==null||!e.is_loaded||!!h[e.name],darkMode:r}),t.jsx(A,{schema:p[e.name]?.output_schema,darkMode:r})]}),N[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(N[e.name],null,2)}),S[e.name]&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify(S[e.name],null,2)}),$[e.name]!==void 0&&t.jsx("pre",{className:`mt-4 p-3 rounded-lg text-xs whitespace-pre-wrap break-words ${r?"bg-gray-900":"bg-gray-50"}`,children:JSON.stringify($[e.name],null,2)})]},e.name))})]})};export{G as PluginsView}; diff --git a/src/agentomatic/studio/static/assets/SchemaForm-DyHc2s7z.js b/src/agentomatic/studio/static/assets/SchemaForm-Kr1WPDMd.js similarity index 99% rename from src/agentomatic/studio/static/assets/SchemaForm-DyHc2s7z.js rename to src/agentomatic/studio/static/assets/SchemaForm-Kr1WPDMd.js index 13a57e3a..bfb59dde 100644 --- a/src/agentomatic/studio/static/assets/SchemaForm-DyHc2s7z.js +++ b/src/agentomatic/studio/static/assets/SchemaForm-Kr1WPDMd.js @@ -1 +1 @@ -import{j as e,n as I,s as W,h as X,a as Y,k as Z,l as T,o as k,i as P,d as M,m as ee}from"./index-FSSL6O5F.js";import{r as v}from"./react-vendor-BHJ3EV8m.js";const D=()=>`row_${Math.random().toString(36).slice(2,10)}`;function te(n){if(n==null)return"string";if(Array.isArray(n))return"array";switch(typeof n){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"object"}}function U(n,g){const a=n?.properties;if(!a||typeof a!="object")return null;const s=I(a[g],n).type;return s==="string"||s==="number"||s==="integer"||s==="boolean"||s==="array"||s==="object"||s==="null"?s==="integer"?"number":s:null}function z(n){return!n||typeof n!="object"||Array.isArray(n)?[]:Object.entries(n).map(([g,a])=>{const r=te(a);return{id:D(),key:g,type:r,value:r==="object"||r==="array"||r==="null"?a==null?"null":JSON.stringify(a,null,2):String(a),error:null}})}function G(n){const g={};for(const a of n){const r=a.key.trim();if(r&&!a.error)switch(a.type){case"string":g[r]=a.value;break;case"number":{const s=a.value.trim()===""?0:Number(a.value);g[r]=Number.isNaN(s)?a.value:s;break}case"boolean":g[r]=a.value==="true";break;case"null":g[r]=null;break;case"object":case"array":{try{const s=JSON.parse(a.value);g[r]=s}catch{}break}}}return g}const V=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`;function re(n,g){let a=n,r=1;for(;g.has(a);)a=`${n}_${r++}`;return a}const se=({value:n,onChange:g,schema:a,darkMode:r=!1,disabled:s=!1,className:m=""})=>{const[h,f]=v.useState(()=>z(n)),b=t=>{f(t),g(G(t))},o=(t,i)=>{const j=h.map(l=>{if(l.id!==t)return l;const x={...l,...i};if(i.type==="object"||i.type==="array")try{JSON.parse(x.value),x.error=null}catch{x.error="Invalid JSON"}else x.error=null;return x});b(j)},y=()=>{const t="string",i=re(`field_${h.length+1}`,new Set(h.map(j=>j.key)));b([...h,{id:D(),key:i,type:t,value:"",error:null}])},A=t=>b(h.filter(i=>i.id!==t)),J=t=>t.type==="boolean"?e.jsx("input",{type:"checkbox",checked:t.value==="true",disabled:s,onChange:i=>o(t.id,{value:String(i.target.checked)}),className:"h-4 w-4 rounded border-gray-300"}):t.type==="null"?e.jsx("span",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"null"}):t.type==="object"||t.type==="array"?e.jsxs("div",{children:[e.jsx("textarea",{value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),rows:3,spellCheck:!1,placeholder:t.type==="array"?"[]":"{}",className:`${V(r)} font-mono ${t.error?"border-red-500":""}`}),t.error&&e.jsx("p",{className:"mt-0.5 text-[10px] text-red-500",children:t.error})]}):e.jsx("input",{type:t.type==="number"?"number":"text",value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),placeholder:t.type==="number"?"0":`Enter ${t.key||"value"}...`,className:V(r),step:t.type==="number"?"any":void 0}),N=v.useMemo(()=>JSON.stringify(n),[n]),[$,S]=v.useState(N);return N!==$&&(S(N),JSON.stringify(G(h))!==N&&f(z(n))),e.jsxs("div",{className:`space-y-2 ${m}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[10px] ${r?"text-gray-500":"text-gray-400"}`,children:"Generic dict — add any fields your agent accepts"}),e.jsx("button",{type:"button",disabled:s,onClick:y,className:`px-2 py-0.5 text-[10px] rounded ${r?"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-600":"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-300"}`,children:"+ Add field"})]}),h.length===0?e.jsx("p",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"No fields yet — click “Add field” to pass custom inputs."}):e.jsx("div",{className:"space-y-2",children:h.map(t=>e.jsx("div",{className:"flex items-start gap-1.5",children:e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",value:t.key,disabled:s,onChange:i=>o(t.id,{key:i.target.value}),placeholder:"field_name",className:`${V(r)} font-mono flex-1`}),e.jsxs("select",{value:t.type,disabled:s,onChange:i=>{const j=i.target.value;let l=t.value;if(j==="object"||j==="array")try{l=JSON.stringify(JSON.parse(t.value),null,2)}catch{l=j==="array"?"[]":"{}"}else j==="null"?l="null":t.type==="object"||t.type==="array"?l="":j==="boolean"&&(l=t.value==="true"?"true":"false");o(t.id,{type:j,value:l})},className:`${V(r)} w-24 flex-shrink-0`,children:[e.jsx("option",{value:"string",children:"string"}),e.jsx("option",{value:"number",children:"number"}),e.jsx("option",{value:"boolean",children:"boolean"}),e.jsx("option",{value:"object",children:"object"}),e.jsx("option",{value:"array",children:"array"}),e.jsx("option",{value:"null",children:"null"})]}),e.jsx("button",{type:"button",disabled:s,onClick:()=>A(t.id),title:"Remove field",className:`px-1.5 py-1 text-xs rounded ${r?"bg-red-700 hover:bg-red-600 text-white disabled:bg-gray-600":"bg-red-600 hover:bg-red-700 text-white disabled:bg-gray-300"}`,children:"×"})]}),e.jsx("div",{className:"pl-0",children:J(t)})]})},t.id))}),a&&e.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(a.properties||{}).filter(t=>!h.some(i=>i.key===t)).slice(0,8).map(t=>e.jsx(ne,{keyName:t,type:U(a,t),darkMode:r,disabled:s,onClick:()=>b([...h,{id:D(),key:t,type:U(a,t)||"string",value:"",error:null}])},t))})]})},ne=({keyName:n,type:g,darkMode:a,disabled:r,onClick:s})=>e.jsxs("button",{type:"button",disabled:r,onClick:s,className:`px-1.5 py-0.5 text-[10px] rounded border ${a?"border-gray-600 text-gray-400 hover:border-blue-500 hover:text-blue-300":"border-gray-200 text-gray-500 hover:border-blue-400 hover:text-blue-600"}`,children:["+ ",n,g?`:${g}`:""]}),O=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`,_=n=>`text-xs font-medium ${n?"text-gray-300":"text-gray-700"}`,F=({name:n,schema:g,rootSchema:a,value:r,required:s=!1,darkMode:m=!1,depth:h=0,onChange:f})=>{const b=v.useId(),o=I(g,a),y=W(g,a),[A,J]=v.useState(0);v.useEffect(()=>{J(l=>Math.min(l,Math.max(y.length-1,0)))},[y.length]);const N=X(n,o),$=typeof o.description=="string"?o.description:void 0,S=o.type||(o.properties?"object":"string"),t=e.jsx("div",{className:"flex items-center justify-between gap-2 mb-1",children:e.jsxs("label",{htmlFor:b,className:_(m),children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"}),e.jsx("span",{className:`ml-2 text-[10px] font-normal ${m?"text-gray-500":"text-gray-400"}`,children:String(S)})]})}),i=$?e.jsx("p",{className:`text-[10px] mb-1 ${m?"text-gray-500":"text-gray-400"}`,children:$}):null;if(y.length>0){const l=y[A]||y[0],x=(u,c)=>typeof u.title=="string"&&u.title?u.title:typeof u.$ref=="string"?u.$ref.split("/").at(-1)||`Option ${c+1}`:u.type?String(u.type):`Option ${c+1}`;return e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-violet-800/70 bg-violet-950/20":"border-violet-200 bg-violet-50/50"}`,children:[t,i,e.jsxs("label",{className:_(m),children:["Input shape",e.jsx("select",{value:A,onChange:u=>{const c=Number(u.target.value),d=y[c]||y[0];J(c),f(Y(d,a))},className:`${O(m)} mt-1`,children:y.map((u,c)=>e.jsx("option",{value:c,children:x(u,c)},`${x(u,c)}-${c}`))})]}),e.jsx(F,{name:n,schema:l,rootSchema:a,value:r,required:s,darkMode:m,depth:h,onChange:f})]})}if(Array.isArray(o.enum)&&o.enum.length>0){const l=Z(o.enum,r);return e.jsxs("div",{children:[t,i,e.jsxs("select",{id:b,value:l>=0?String(l):"",onChange:x=>f(k(o.enum,x.target.value)),className:O(m),children:[!s&&e.jsx("option",{value:"",children:"—"}),o.enum.map((x,u)=>e.jsx("option",{value:String(u),children:T(x)},`${T(x)}-${u}`))]})]})}if(o.const!==void 0)return e.jsxs("div",{children:[t,i,e.jsx("output",{"aria-label":`${N} fixed value`,className:`block w-full rounded border px-2 py-1.5 text-xs font-mono ${m?"border-gray-600 bg-gray-800 text-gray-300":"border-gray-300 bg-gray-50 text-gray-700"}`,children:T(o.const)})]});if(S==="boolean")return e.jsxs("div",{children:[e.jsxs("label",{className:`flex items-center gap-2 cursor-pointer ${_(m)}`,children:[e.jsx("input",{type:"checkbox",checked:!!r,onChange:l=>f(l.target.checked),className:"rounded border-gray-300"}),e.jsxs("span",{children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]})]}),i]});if(S==="number"||S==="integer")return e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"number",step:S==="integer"?1:"any",value:r??"",onChange:l=>{const x=l.target.value;if(x===""){f(void 0);return}const u=S==="integer"?parseInt(x,10):parseFloat(x);f(Number.isNaN(u)?x:u)},className:O(m),placeholder:o.examples?.[0]!=null?String(o.examples[0]):N})]});if(S==="array"){const x=I(o.items||{type:"string"},a).type||"string",u=Array.isArray(r)?r:[];return x==="string"||x==="number"||x==="integer"?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t,e.jsx("button",{type:"button",onClick:()=>f([...u,x==="string"?"":0]),className:"px-2 py-0.5 text-[10px] rounded bg-blue-600 hover:bg-blue-700 text-white",children:"+ Add"})]}),i,e.jsxs("div",{className:"space-y-1",children:[u.length===0&&e.jsx("p",{className:`text-[10px] italic ${m?"text-gray-500":"text-gray-400"}`,children:"Empty array"}),u.map((c,d)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:x==="string"?"text":"number",value:c??"",onChange:w=>{const C=[...u];if(x==="string")C[d]=w.target.value;else{const E=x==="integer"?parseInt(w.target.value,10):parseFloat(w.target.value);C[d]=Number.isNaN(E)?w.target.value:E}f(C)},className:O(m)}),e.jsx("button",{type:"button",onClick:()=>f(u.filter((w,C)=>C!==d)),className:`px-2 py-1 text-xs rounded ${m?"bg-red-700 hover:bg-red-600 text-white":"bg-red-600 hover:bg-red-700 text-white"}`,children:"×"})]},d))]})]}):e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"[]"})]})}if(S==="object"||o.properties){const l=o.properties||{},x=new Set(Array.isArray(o.required)?o.required:[]),u=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return h>=2||Object.keys(l).length===0?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);d&&typeof d=="object"&&!Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"{}"})]}):e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-gray-600 bg-gray-800/40":"border-gray-200 bg-gray-50"}`,children:[t,i,Object.entries(l).map(([c,d])=>e.jsx(F,{name:c,schema:d,rootSchema:a,value:u[c],required:x.has(c),darkMode:m,depth:h+1,onChange:w=>f({...u,[c]:w})},c))]})}return o.format==="textarea"||o.maxLength>200||["query","current_query","message","prompt","content","text"].includes(n)?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:r??"",onChange:l=>f(l.target.value),rows:3,className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]}):e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"text",value:r??"",onChange:l=>f(l.target.value),className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]})},ae={type:"object",title:"Unspecified input",additionalProperties:!0,properties:{}},oe=({schema:n,value:g,onChange:a,onSubmit:r,darkMode:s=!1,showViewToggle:m=!0,disabled:h=!1,submitLabel:f,schemaSource:b,className:o=""})=>{const y=v.useMemo(()=>P(n||void 0)?ae:I(n,n),[n]),A=v.useMemo(()=>M(y,y),[y]),[J,N]=v.useState(()=>g!==void 0?g:A),[$,S]=v.useState("form"),[t,i]=v.useState(""),[j,l]=v.useState(null),[x,u]=v.useState(null),c=g!==void 0?g:J;v.useEffect(()=>{g===void 0&&N(A),i(JSON.stringify(g!==void 0?g:A,null,2)),l(null)},[y]),v.useEffect(()=>{$!=="raw"&&i(JSON.stringify(c,null,2))},[c,$]);const d=p=>{g===void 0&&N(p),a?.(p)},w=y.properties||{},C=new Set(Array.isArray(y.required)?y.required:[]),E=Object.entries(w),H=P(n||void 0),q=E.length===0&&!!(y.type&&y.type!=="object"),L=c&&typeof c=="object"&&!Array.isArray(c)?c:{},K=()=>{try{const p=JSON.parse(t);l(null),d(p)}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}},B=p=>{const R=ee(y,p,y);return R.length?(u(`Complete required field${R.length===1?"":"s"}: ${R.join(", ")}`),!1):(u(null),!0)};return e.jsxs("div",{className:`space-y-3 ${o}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:`text-sm font-semibold truncate ${s?"text-white":"text-gray-900"}`,children:y.title||"Input"}),b?.source&&e.jsxs("span",{className:`flex-shrink-0 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${b.source==="custom"?s?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":s?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${b.convention||b.source}`,children:[b.source==="custom"?"Custom schema":"Default schema",b.model?` · ${b.model}`:""]})]}),H&&!b?.source&&e.jsx("p",{className:`text-[10px] ${s?"text-amber-400":"text-amber-600"}`,children:"No input schema published — use Dict or Raw JSON for this operation"})]}),m&&e.jsx("div",{className:`inline-flex rounded-lg p-0.5 text-xs ${s?"bg-gray-700":"bg-gray-100"}`,children:["form","dict","raw"].map(p=>e.jsx("button",{type:"button",disabled:h||p==="dict"&&q,onClick:()=>{p==="raw"?(i(JSON.stringify(c,null,2)),l(null)):$==="raw"&&K(),S(p)},className:`px-2 py-1 rounded-md transition-colors ${$===p?s?"bg-gray-600 text-white":"bg-white text-gray-900 shadow-sm":s?"text-gray-300 hover:text-white":"text-gray-600 hover:text-gray-900"}`,children:p==="form"?"Form":p==="dict"?"Dict":"Raw JSON"},p))})]}),y.description&&e.jsx("p",{className:`text-xs ${s?"text-gray-400":"text-gray-500"}`,children:y.description}),$==="form"?e.jsx("div",{className:`space-y-3 max-h-96 overflow-y-auto pr-1 ${h?"opacity-60 pointer-events-none":""}`,children:q?e.jsx(F,{name:y.title||"value",schema:y,rootSchema:y,value:c,darkMode:s,onChange:d}):E.length===0?e.jsx("p",{className:`text-xs italic ${s?"text-gray-500":"text-gray-400"}`,children:"Schema has no properties to render."}):E.map(([p,R])=>e.jsx(F,{name:p,schema:R,rootSchema:y,value:L[p],required:C.has(p),darkMode:s,onChange:Q=>d({...L,[p]:Q})},p))}):$==="dict"&&!q?e.jsx(se,{value:L,onChange:d,schema:y,darkMode:s,disabled:h}):e.jsxs("div",{children:[e.jsx("textarea",{value:t,disabled:h,onChange:p=>{i(p.target.value),l(null)},onBlur:K,rows:12,className:`w-full px-2 py-2 text-xs font-mono border rounded ${s?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} ${j?"border-red-500":""}`,spellCheck:!1}),j&&e.jsx("p",{className:"mt-1 text-[10px] text-red-500",children:j})]}),f&&r&&e.jsx("button",{type:"button",disabled:h,onClick:()=>{if($==="raw"){try{const p=JSON.parse(t);l(null),d(p),B(p)&&r(p);return}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}return}B(c)&&r(c)},className:`w-full px-3 py-2 text-sm font-medium rounded-lg transition-colors ${s?"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-600":"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-300"}`,children:f}),x&&e.jsx("p",{role:"alert",className:"text-xs text-red-500",children:x})]})};export{oe as S}; +import{j as e,n as I,s as W,h as X,a as Y,k as Z,l as T,o as k,i as P,d as M,m as ee}from"./index-BMj1jeBL.js";import{r as v}from"./react-vendor-BHJ3EV8m.js";const D=()=>`row_${Math.random().toString(36).slice(2,10)}`;function te(n){if(n==null)return"string";if(Array.isArray(n))return"array";switch(typeof n){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"object"}}function U(n,g){const a=n?.properties;if(!a||typeof a!="object")return null;const s=I(a[g],n).type;return s==="string"||s==="number"||s==="integer"||s==="boolean"||s==="array"||s==="object"||s==="null"?s==="integer"?"number":s:null}function z(n){return!n||typeof n!="object"||Array.isArray(n)?[]:Object.entries(n).map(([g,a])=>{const r=te(a);return{id:D(),key:g,type:r,value:r==="object"||r==="array"||r==="null"?a==null?"null":JSON.stringify(a,null,2):String(a),error:null}})}function G(n){const g={};for(const a of n){const r=a.key.trim();if(r&&!a.error)switch(a.type){case"string":g[r]=a.value;break;case"number":{const s=a.value.trim()===""?0:Number(a.value);g[r]=Number.isNaN(s)?a.value:s;break}case"boolean":g[r]=a.value==="true";break;case"null":g[r]=null;break;case"object":case"array":{try{const s=JSON.parse(a.value);g[r]=s}catch{}break}}}return g}const V=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`;function re(n,g){let a=n,r=1;for(;g.has(a);)a=`${n}_${r++}`;return a}const se=({value:n,onChange:g,schema:a,darkMode:r=!1,disabled:s=!1,className:m=""})=>{const[h,f]=v.useState(()=>z(n)),b=t=>{f(t),g(G(t))},o=(t,i)=>{const j=h.map(l=>{if(l.id!==t)return l;const x={...l,...i};if(i.type==="object"||i.type==="array")try{JSON.parse(x.value),x.error=null}catch{x.error="Invalid JSON"}else x.error=null;return x});b(j)},y=()=>{const t="string",i=re(`field_${h.length+1}`,new Set(h.map(j=>j.key)));b([...h,{id:D(),key:i,type:t,value:"",error:null}])},A=t=>b(h.filter(i=>i.id!==t)),J=t=>t.type==="boolean"?e.jsx("input",{type:"checkbox",checked:t.value==="true",disabled:s,onChange:i=>o(t.id,{value:String(i.target.checked)}),className:"h-4 w-4 rounded border-gray-300"}):t.type==="null"?e.jsx("span",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"null"}):t.type==="object"||t.type==="array"?e.jsxs("div",{children:[e.jsx("textarea",{value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),rows:3,spellCheck:!1,placeholder:t.type==="array"?"[]":"{}",className:`${V(r)} font-mono ${t.error?"border-red-500":""}`}),t.error&&e.jsx("p",{className:"mt-0.5 text-[10px] text-red-500",children:t.error})]}):e.jsx("input",{type:t.type==="number"?"number":"text",value:t.value,disabled:s,onChange:i=>o(t.id,{value:i.target.value}),placeholder:t.type==="number"?"0":`Enter ${t.key||"value"}...`,className:V(r),step:t.type==="number"?"any":void 0}),N=v.useMemo(()=>JSON.stringify(n),[n]),[$,S]=v.useState(N);return N!==$&&(S(N),JSON.stringify(G(h))!==N&&f(z(n))),e.jsxs("div",{className:`space-y-2 ${m}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[10px] ${r?"text-gray-500":"text-gray-400"}`,children:"Generic dict — add any fields your agent accepts"}),e.jsx("button",{type:"button",disabled:s,onClick:y,className:`px-2 py-0.5 text-[10px] rounded ${r?"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-600":"bg-blue-600 hover:bg-blue-700 text-white disabled:bg-gray-300"}`,children:"+ Add field"})]}),h.length===0?e.jsx("p",{className:`text-[10px] italic ${r?"text-gray-500":"text-gray-400"}`,children:"No fields yet — click “Add field” to pass custom inputs."}):e.jsx("div",{className:"space-y-2",children:h.map(t=>e.jsx("div",{className:"flex items-start gap-1.5",children:e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",value:t.key,disabled:s,onChange:i=>o(t.id,{key:i.target.value}),placeholder:"field_name",className:`${V(r)} font-mono flex-1`}),e.jsxs("select",{value:t.type,disabled:s,onChange:i=>{const j=i.target.value;let l=t.value;if(j==="object"||j==="array")try{l=JSON.stringify(JSON.parse(t.value),null,2)}catch{l=j==="array"?"[]":"{}"}else j==="null"?l="null":t.type==="object"||t.type==="array"?l="":j==="boolean"&&(l=t.value==="true"?"true":"false");o(t.id,{type:j,value:l})},className:`${V(r)} w-24 flex-shrink-0`,children:[e.jsx("option",{value:"string",children:"string"}),e.jsx("option",{value:"number",children:"number"}),e.jsx("option",{value:"boolean",children:"boolean"}),e.jsx("option",{value:"object",children:"object"}),e.jsx("option",{value:"array",children:"array"}),e.jsx("option",{value:"null",children:"null"})]}),e.jsx("button",{type:"button",disabled:s,onClick:()=>A(t.id),title:"Remove field",className:`px-1.5 py-1 text-xs rounded ${r?"bg-red-700 hover:bg-red-600 text-white disabled:bg-gray-600":"bg-red-600 hover:bg-red-700 text-white disabled:bg-gray-300"}`,children:"×"})]}),e.jsx("div",{className:"pl-0",children:J(t)})]})},t.id))}),a&&e.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(a.properties||{}).filter(t=>!h.some(i=>i.key===t)).slice(0,8).map(t=>e.jsx(ne,{keyName:t,type:U(a,t),darkMode:r,disabled:s,onClick:()=>b([...h,{id:D(),key:t,type:U(a,t)||"string",value:"",error:null}])},t))})]})},ne=({keyName:n,type:g,darkMode:a,disabled:r,onClick:s})=>e.jsxs("button",{type:"button",disabled:r,onClick:s,className:`px-1.5 py-0.5 text-[10px] rounded border ${a?"border-gray-600 text-gray-400 hover:border-blue-500 hover:text-blue-300":"border-gray-200 text-gray-500 hover:border-blue-400 hover:text-blue-600"}`,children:["+ ",n,g?`:${g}`:""]}),O=n=>`w-full px-2 py-1.5 text-xs border rounded ${n?"bg-gray-700 border-gray-600 text-white placeholder-gray-400":"bg-white border-gray-300 text-gray-900 placeholder-gray-500"}`,_=n=>`text-xs font-medium ${n?"text-gray-300":"text-gray-700"}`,F=({name:n,schema:g,rootSchema:a,value:r,required:s=!1,darkMode:m=!1,depth:h=0,onChange:f})=>{const b=v.useId(),o=I(g,a),y=W(g,a),[A,J]=v.useState(0);v.useEffect(()=>{J(l=>Math.min(l,Math.max(y.length-1,0)))},[y.length]);const N=X(n,o),$=typeof o.description=="string"?o.description:void 0,S=o.type||(o.properties?"object":"string"),t=e.jsx("div",{className:"flex items-center justify-between gap-2 mb-1",children:e.jsxs("label",{htmlFor:b,className:_(m),children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"}),e.jsx("span",{className:`ml-2 text-[10px] font-normal ${m?"text-gray-500":"text-gray-400"}`,children:String(S)})]})}),i=$?e.jsx("p",{className:`text-[10px] mb-1 ${m?"text-gray-500":"text-gray-400"}`,children:$}):null;if(y.length>0){const l=y[A]||y[0],x=(u,c)=>typeof u.title=="string"&&u.title?u.title:typeof u.$ref=="string"?u.$ref.split("/").at(-1)||`Option ${c+1}`:u.type?String(u.type):`Option ${c+1}`;return e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-violet-800/70 bg-violet-950/20":"border-violet-200 bg-violet-50/50"}`,children:[t,i,e.jsxs("label",{className:_(m),children:["Input shape",e.jsx("select",{value:A,onChange:u=>{const c=Number(u.target.value),d=y[c]||y[0];J(c),f(Y(d,a))},className:`${O(m)} mt-1`,children:y.map((u,c)=>e.jsx("option",{value:c,children:x(u,c)},`${x(u,c)}-${c}`))})]}),e.jsx(F,{name:n,schema:l,rootSchema:a,value:r,required:s,darkMode:m,depth:h,onChange:f})]})}if(Array.isArray(o.enum)&&o.enum.length>0){const l=Z(o.enum,r);return e.jsxs("div",{children:[t,i,e.jsxs("select",{id:b,value:l>=0?String(l):"",onChange:x=>f(k(o.enum,x.target.value)),className:O(m),children:[!s&&e.jsx("option",{value:"",children:"—"}),o.enum.map((x,u)=>e.jsx("option",{value:String(u),children:T(x)},`${T(x)}-${u}`))]})]})}if(o.const!==void 0)return e.jsxs("div",{children:[t,i,e.jsx("output",{"aria-label":`${N} fixed value`,className:`block w-full rounded border px-2 py-1.5 text-xs font-mono ${m?"border-gray-600 bg-gray-800 text-gray-300":"border-gray-300 bg-gray-50 text-gray-700"}`,children:T(o.const)})]});if(S==="boolean")return e.jsxs("div",{children:[e.jsxs("label",{className:`flex items-center gap-2 cursor-pointer ${_(m)}`,children:[e.jsx("input",{type:"checkbox",checked:!!r,onChange:l=>f(l.target.checked),className:"rounded border-gray-300"}),e.jsxs("span",{children:[N,s&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]})]}),i]});if(S==="number"||S==="integer")return e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"number",step:S==="integer"?1:"any",value:r??"",onChange:l=>{const x=l.target.value;if(x===""){f(void 0);return}const u=S==="integer"?parseInt(x,10):parseFloat(x);f(Number.isNaN(u)?x:u)},className:O(m),placeholder:o.examples?.[0]!=null?String(o.examples[0]):N})]});if(S==="array"){const x=I(o.items||{type:"string"},a).type||"string",u=Array.isArray(r)?r:[];return x==="string"||x==="number"||x==="integer"?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t,e.jsx("button",{type:"button",onClick:()=>f([...u,x==="string"?"":0]),className:"px-2 py-0.5 text-[10px] rounded bg-blue-600 hover:bg-blue-700 text-white",children:"+ Add"})]}),i,e.jsxs("div",{className:"space-y-1",children:[u.length===0&&e.jsx("p",{className:`text-[10px] italic ${m?"text-gray-500":"text-gray-400"}`,children:"Empty array"}),u.map((c,d)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:x==="string"?"text":"number",value:c??"",onChange:w=>{const C=[...u];if(x==="string")C[d]=w.target.value;else{const E=x==="integer"?parseInt(w.target.value,10):parseFloat(w.target.value);C[d]=Number.isNaN(E)?w.target.value:E}f(C)},className:O(m)}),e.jsx("button",{type:"button",onClick:()=>f(u.filter((w,C)=>C!==d)),className:`px-2 py-1 text-xs rounded ${m?"bg-red-700 hover:bg-red-600 text-white":"bg-red-600 hover:bg-red-700 text-white"}`,children:"×"})]},d))]})]}):e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"[]"})]})}if(S==="object"||o.properties){const l=o.properties||{},x=new Set(Array.isArray(o.required)?o.required:[]),u=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return h>=2||Object.keys(l).length===0?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:JSON.stringify(u,null,2),onChange:c=>{try{const d=JSON.parse(c.target.value);d&&typeof d=="object"&&!Array.isArray(d)&&f(d)}catch{}},rows:4,className:`${O(m)} font-mono`,placeholder:"{}"})]}):e.jsxs("div",{className:`rounded border p-2 space-y-2 ${m?"border-gray-600 bg-gray-800/40":"border-gray-200 bg-gray-50"}`,children:[t,i,Object.entries(l).map(([c,d])=>e.jsx(F,{name:c,schema:d,rootSchema:a,value:u[c],required:x.has(c),darkMode:m,depth:h+1,onChange:w=>f({...u,[c]:w})},c))]})}return o.format==="textarea"||o.maxLength>200||["query","current_query","message","prompt","content","text"].includes(n)?e.jsxs("div",{children:[t,i,e.jsx("textarea",{id:b,value:r??"",onChange:l=>f(l.target.value),rows:3,className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]}):e.jsxs("div",{children:[t,i,e.jsx("input",{id:b,type:"text",value:r??"",onChange:l=>f(l.target.value),className:O(m),placeholder:Array.isArray(o.examples)&&o.examples[0]!=null?String(o.examples[0]):`Enter ${N.toLowerCase()}...`})]})},ae={type:"object",title:"Unspecified input",additionalProperties:!0,properties:{}},oe=({schema:n,value:g,onChange:a,onSubmit:r,darkMode:s=!1,showViewToggle:m=!0,disabled:h=!1,submitLabel:f,schemaSource:b,className:o=""})=>{const y=v.useMemo(()=>P(n||void 0)?ae:I(n,n),[n]),A=v.useMemo(()=>M(y,y),[y]),[J,N]=v.useState(()=>g!==void 0?g:A),[$,S]=v.useState("form"),[t,i]=v.useState(""),[j,l]=v.useState(null),[x,u]=v.useState(null),c=g!==void 0?g:J;v.useEffect(()=>{g===void 0&&N(A),i(JSON.stringify(g!==void 0?g:A,null,2)),l(null)},[y]),v.useEffect(()=>{$!=="raw"&&i(JSON.stringify(c,null,2))},[c,$]);const d=p=>{g===void 0&&N(p),a?.(p)},w=y.properties||{},C=new Set(Array.isArray(y.required)?y.required:[]),E=Object.entries(w),H=P(n||void 0),q=E.length===0&&!!(y.type&&y.type!=="object"),L=c&&typeof c=="object"&&!Array.isArray(c)?c:{},K=()=>{try{const p=JSON.parse(t);l(null),d(p)}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}},B=p=>{const R=ee(y,p,y);return R.length?(u(`Complete required field${R.length===1?"":"s"}: ${R.join(", ")}`),!1):(u(null),!0)};return e.jsxs("div",{className:`space-y-3 ${o}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:`text-sm font-semibold truncate ${s?"text-white":"text-gray-900"}`,children:y.title||"Input"}),b?.source&&e.jsxs("span",{className:`flex-shrink-0 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${b.source==="custom"?s?"bg-green-900/60 text-green-300":"bg-green-100 text-green-700":s?"bg-amber-900/60 text-amber-300":"bg-amber-100 text-amber-700"}`,title:`Schema source: ${b.convention||b.source}`,children:[b.source==="custom"?"Custom schema":"Default schema",b.model?` · ${b.model}`:""]})]}),H&&!b?.source&&e.jsx("p",{className:`text-[10px] ${s?"text-amber-400":"text-amber-600"}`,children:"No input schema published — use Dict or Raw JSON for this operation"})]}),m&&e.jsx("div",{className:`inline-flex rounded-lg p-0.5 text-xs ${s?"bg-gray-700":"bg-gray-100"}`,children:["form","dict","raw"].map(p=>e.jsx("button",{type:"button",disabled:h||p==="dict"&&q,onClick:()=>{p==="raw"?(i(JSON.stringify(c,null,2)),l(null)):$==="raw"&&K(),S(p)},className:`px-2 py-1 rounded-md transition-colors ${$===p?s?"bg-gray-600 text-white":"bg-white text-gray-900 shadow-sm":s?"text-gray-300 hover:text-white":"text-gray-600 hover:text-gray-900"}`,children:p==="form"?"Form":p==="dict"?"Dict":"Raw JSON"},p))})]}),y.description&&e.jsx("p",{className:`text-xs ${s?"text-gray-400":"text-gray-500"}`,children:y.description}),$==="form"?e.jsx("div",{className:`space-y-3 max-h-96 overflow-y-auto pr-1 ${h?"opacity-60 pointer-events-none":""}`,children:q?e.jsx(F,{name:y.title||"value",schema:y,rootSchema:y,value:c,darkMode:s,onChange:d}):E.length===0?e.jsx("p",{className:`text-xs italic ${s?"text-gray-500":"text-gray-400"}`,children:"Schema has no properties to render."}):E.map(([p,R])=>e.jsx(F,{name:p,schema:R,rootSchema:y,value:L[p],required:C.has(p),darkMode:s,onChange:Q=>d({...L,[p]:Q})},p))}):$==="dict"&&!q?e.jsx(se,{value:L,onChange:d,schema:y,darkMode:s,disabled:h}):e.jsxs("div",{children:[e.jsx("textarea",{value:t,disabled:h,onChange:p=>{i(p.target.value),l(null)},onBlur:K,rows:12,className:`w-full px-2 py-2 text-xs font-mono border rounded ${s?"bg-gray-700 border-gray-600 text-white":"bg-white border-gray-300 text-gray-900"} ${j?"border-red-500":""}`,spellCheck:!1}),j&&e.jsx("p",{className:"mt-1 text-[10px] text-red-500",children:j})]}),f&&r&&e.jsx("button",{type:"button",disabled:h,onClick:()=>{if($==="raw"){try{const p=JSON.parse(t);l(null),d(p),B(p)&&r(p);return}catch(p){l(p instanceof Error?p.message:"Invalid JSON")}return}B(c)&&r(c)},className:`w-full px-3 py-2 text-sm font-medium rounded-lg transition-colors ${s?"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-600":"bg-green-600 hover:bg-green-700 text-white disabled:bg-gray-300"}`,children:f}),x&&e.jsx("p",{role:"alert",className:"text-xs text-red-500",children:x})]})};export{oe as S}; diff --git a/src/agentomatic/studio/static/assets/TasksView-DAoR0f0z.js b/src/agentomatic/studio/static/assets/TasksView-B5ml_CT4.js similarity index 98% rename from src/agentomatic/studio/static/assets/TasksView-DAoR0f0z.js rename to src/agentomatic/studio/static/assets/TasksView-B5ml_CT4.js index 24c8f486..2bb0e4b9 100644 --- a/src/agentomatic/studio/static/assets/TasksView-DAoR0f0z.js +++ b/src/agentomatic/studio/static/assets/TasksView-B5ml_CT4.js @@ -1,3 +1,3 @@ -import{u as le,A as ie,j as e,d as oe,m as z}from"./index-FSSL6O5F.js";import{r as l}from"./react-vendor-BHJ3EV8m.js";import{S as de}from"./SchemaForm-DyHc2s7z.js";import{O as ce}from"./OutputSchemaSummary-C65WaRqI.js";import"./syntax-vendor-ru7AzRyY.js";const me=["agent","plugin","pipeline","endpoint","ingestion"],L=new Set(["succeeded","failed","cancelled"]),ue={agent:[],plugin:[],pipeline:[],endpoint:[],ingestion:[]},B=p=>({agent:"Agent",plugin:"Plugin",pipeline:"Pipeline",endpoint:"Endpoint",ingestion:"Ingestor"})[p],pe=p=>p?new Date(p*1e3).toLocaleTimeString():"—",ge=(p,a)=>(a?{queued:"bg-amber-900/60 text-amber-200",running:"bg-blue-900/60 text-blue-200",succeeded:"bg-emerald-900/60 text-emerald-200",failed:"bg-red-900/60 text-red-200",cancelled:"bg-gray-700 text-gray-200"}:{queued:"bg-amber-100 text-amber-800",running:"bg-blue-100 text-blue-800",succeeded:"bg-emerald-100 text-emerald-800",failed:"bg-red-100 text-red-800",cancelled:"bg-gray-200 text-gray-700"})[p],ve=()=>{const{config:p,darkMode:a}=le(),[f,H]=l.useState(ue),[Q,X]=l.useState({}),[Z,T]=l.useState({}),[k,F]=l.useState(!1),[w,P]=l.useState([]),[m,ee]=l.useState("agent"),[i,E]=l.useState(""),[$,S]=l.useState({}),[h,te]=l.useState("async"),[U,R]=l.useState(`[ +import{u as le,A as ie,j as e,d as oe,m as z}from"./index-BMj1jeBL.js";import{r as l}from"./react-vendor-BHJ3EV8m.js";import{S as de}from"./SchemaForm-Kr1WPDMd.js";import{O as ce}from"./OutputSchemaSummary-CiE3pU-0.js";import"./syntax-vendor-ru7AzRyY.js";const me=["agent","plugin","pipeline","endpoint","ingestion"],L=new Set(["succeeded","failed","cancelled"]),ue={agent:[],plugin:[],pipeline:[],endpoint:[],ingestion:[]},B=p=>({agent:"Agent",plugin:"Plugin",pipeline:"Pipeline",endpoint:"Endpoint",ingestion:"Ingestor"})[p],pe=p=>p?new Date(p*1e3).toLocaleTimeString():"—",ge=(p,a)=>(a?{queued:"bg-amber-900/60 text-amber-200",running:"bg-blue-900/60 text-blue-200",succeeded:"bg-emerald-900/60 text-emerald-200",failed:"bg-red-900/60 text-red-200",cancelled:"bg-gray-700 text-gray-200"}:{queued:"bg-amber-100 text-amber-800",running:"bg-blue-100 text-blue-800",succeeded:"bg-emerald-100 text-emerald-800",failed:"bg-red-100 text-red-800",cancelled:"bg-gray-200 text-gray-700"})[p],ve=()=>{const{config:p,darkMode:a}=le(),[f,H]=l.useState(ue),[Q,X]=l.useState({}),[Z,T]=l.useState({}),[k,F]=l.useState(!1),[w,P]=l.useState([]),[m,ee]=l.useState("agent"),[i,E]=l.useState(""),[$,S]=l.useState({}),[h,te]=l.useState("async"),[U,R]=l.useState(`[ {} ]`),[J,se]=l.useState(!1),[M,q]=l.useState(!0),[_,D]=l.useState(!1),[C,K]=l.useState(null),[V,x]=l.useState(null),[b,I]=l.useState(null),r=l.useMemo(()=>p?.apiUrl?new ie(p.apiUrl,p.apiKey||void 0):null,[p?.apiKey,p?.apiUrl]),y=`${m}:${i}`,v=Q[y],O=Z[y],A=!!(i&&v&&!k&&!O),j=l.useCallback(async(t=!1)=>{if(r)try{const d=await r.listTasks({limit:100});P(d.tasks),I(s=>s&&d.tasks.find(o=>o.id===s.id)||null),t||x(null)}catch(d){t||x(d?.message||"Failed to load task board")}},[r]);l.useEffect(()=>{if(!r)return;let t=!0;return(async()=>{q(!0);try{const[s,o,c,g,N]=await Promise.all([r.listAgents(),r.listPlugins(),r.listPipelines(),r.listEndpoints(),r.listIngestors()]);if(!t)return;const Y={agent:s.map(n=>({name:n.name,label:n.description||n.name})),plugin:o.map(n=>({name:n.name,label:n.description||n.name})),pipeline:c.map(n=>({name:n.name,label:n.description||n.name})),endpoint:g.map(n=>({name:n.name,label:n.description||n.name})),ingestion:N.map(n=>({name:n.name,label:n.description||n.name}))};H(Y),E(n=>n||Y.agent[0]?.name||""),x(null),await j()}catch(s){t&&x(s?.message||"Failed to discover platform resources")}finally{t&&q(!1)}})(),()=>{t=!1}},[r,j]),l.useEffect(()=>{if(!r||!i)return;let t=!0;return(async()=>{F(!0),T(s=>{const o={...s};return delete o[y],o});try{let s=null;if(m==="agent"){const c=await r.getSchemas(i);s={input_schema:c.input_schema,output_schema:c.output_schema,method:"POST",path:`/api/v1/${i}/invoke`}}else{const c=m==="plugin"?`/api/v1/plugins/${encodeURIComponent(i)}/predict`:m==="pipeline"?`/api/v1/pipelines/${encodeURIComponent(i)}/run`:m==="endpoint"?f.endpoint.find(g=>g.name===i)?.name?`/api/v1/endpoints/${encodeURIComponent(i)}`:"":`/api/v1/ingestion/${encodeURIComponent(i)}/run`;if(m==="endpoint"){const g=(await r.listEndpoints()).find(N=>N.name===i);g?.path&&(s=await r.getEndpointContract(g))}else c&&(s=await r.getOperationContract(c),m==="pipeline"&&s.input_schema?.properties?.input&&(s={...s,input_schema:s.input_schema.properties.input}))}if(!t||!s)return;X(c=>({...c,[y]:s}));const o=oe(s.input_schema||void 0);S(o),R(JSON.stringify([o],null,2)),T(c=>{const g={...c};return delete g[y],g})}catch(s){if(t){const o=s?.message||`Failed to load the input contract for '${i}'`;T(c=>({...c,[y]:o})),x(o)}}finally{t&&F(!1)}})(),()=>{t=!1}},[r,y,f.endpoint,i,m]),l.useEffect(()=>{if(!w.some(d=>!L.has(d.status)))return;const t=window.setInterval(()=>{j(!0)},1500);return()=>window.clearInterval(t)},[j,w]);const ae=t=>{ee(t),E(f[t][0]?.name||""),S({})},re=()=>{R(JSON.stringify([$],null,2))},ne=async()=>{if(!(!r||!i)){D(!0),x(null);try{let t;if(h==="batch"){const s=JSON.parse(U);if(!Array.isArray(s)||s.length===0)throw new Error("Batch input must be a non-empty JSON array.");const o=s.flatMap((c,g)=>z(v?.input_schema||void 0,c).map(N=>`item ${g+1}: ${N}`));if(o.length)throw new Error(`Complete required field${o.length===1?"":"s"}: ${o.join(", ")}`);t=s}else{const s=z(v?.input_schema||void 0,$);if(s.length)throw new Error(`Complete required field${s.length===1?"":"s"}: ${s.join(", ")}`)}const d=await r.submitTask({target_type:m,target:i,input:h==="batch"?void 0:$,batch:t,mode:h==="sync"?"sync":"async",wait:h==="sync",retry:J?{max_attempts:3,backoff:"exponential",base_delay:1}:void 0});P(s=>[d,...s.filter(o=>o.id!==d.id)]),I(d)}catch(t){x(t?.message||"Task submission failed")}finally{D(!1)}}},G=async(t,d)=>{if(r){K(`${d}:${t.id}`),x(null);try{d==="cancel"?await r.cancelTask(t.id):await r.deleteTask(t.id),await j()}catch(s){x(s?.message||`Could not ${d} task`)}finally{K(null)}}},W=a?"border-gray-700 bg-gray-800":"border-gray-200 bg-white",u=a?"text-gray-400":"text-gray-600";return e.jsxs("div",{className:`h-full overflow-y-auto p-4 sm:p-6 ${a?"bg-gray-900 text-white":"bg-gray-50 text-gray-900"}`,children:[e.jsxs("div",{className:"mb-6 flex flex-col justify-between gap-3 sm:flex-row sm:items-start",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Task Board"}),e.jsx("p",{className:`mt-1 max-w-3xl text-sm ${u}`,children:"Submit real platform work, inspect its durable progress, and safely cancel or remove completed records. Inputs are generated from the deployed resource contract."})]}),e.jsx("button",{type:"button",onClick:()=>{j()},className:`self-start rounded-lg border px-3 py-2 text-sm font-medium ${a?"border-gray-600 hover:bg-gray-700":"border-gray-300 hover:bg-gray-100"}`,children:"Refresh"})]}),V&&e.jsx("div",{role:"alert",className:`mb-5 rounded-lg border p-3 text-sm ${a?"border-red-800 bg-red-950/50 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:V}),M&&e.jsx("p",{className:u,children:"Discovering live resources and task records…"}),!M&&e.jsxs("div",{className:"grid grid-cols-1 gap-6 2xl:grid-cols-[minmax(26rem,0.85fr)_minmax(32rem,1.15fr)]",children:[e.jsxs("section",{className:`rounded-xl border p-4 shadow-sm sm:p-5 ${W}`,children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Submit work"}),e.jsx("p",{className:`mt-1 text-xs ${u}`,children:"Choose the real resource first; its published request schema appears below."}),e.jsxs("div",{className:"mt-5 grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-sm font-medium",children:["Resource type",e.jsx("select",{value:m,onChange:t=>ae(t.target.value),className:`mt-1 block w-full rounded-lg border p-2.5 ${a?"border-gray-600 bg-gray-900":"border-gray-300 bg-white"}`,children:me.map(t=>e.jsx("option",{value:t,children:B(t)},t))})]}),e.jsxs("label",{className:"text-sm font-medium",children:["Resource",e.jsxs("select",{value:i,onChange:t=>{E(t.target.value),S({})},disabled:!f[m].length,className:`mt-1 block w-full rounded-lg border p-2.5 disabled:opacity-50 ${a?"border-gray-600 bg-gray-900":"border-gray-300 bg-white"}`,children:[!f[m].length&&e.jsxs("option",{value:"",children:["No live ",B(m).toLowerCase()," available"]}),f[m].map(t=>e.jsx("option",{value:t.name,children:t.name},t.name))]})]})]}),i&&e.jsxs("p",{className:`mt-2 text-xs ${u}`,children:["Target: ",e.jsx("code",{children:i})," · ",v?.method||"POST"," ",v?.path||(k?"Loading contract…":"Contract unavailable")]}),i&&k&&e.jsx("p",{role:"status",className:`mt-2 text-xs ${u}`,children:"Reading the deployed input contract before enabling execution…"}),i&&O&&e.jsxs("p",{role:"status",className:`mt-2 rounded-md border p-2 text-xs ${a?"border-amber-800 bg-amber-950/30 text-amber-200":"border-amber-200 bg-amber-50 text-amber-800"}`,children:["Live input contract unavailable: ",O,". Submission stays disabled until it can be read."]}),e.jsxs("div",{className:`mt-4 border-t pt-4 ${a?"border-gray-700":"border-gray-200"}`,children:[e.jsx(de,{schema:v?.input_schema,value:$,onChange:S,darkMode:a,submitLabel:void 0,disabled:!A||_}),e.jsx(ce,{schema:v?.output_schema,darkMode:a,className:"mt-3"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-sm font-medium",children:["Execution mode",e.jsxs("select",{value:h,onChange:t=>te(t.target.value),className:`mt-1 block w-full rounded-lg border p-2.5 ${a?"border-gray-600 bg-gray-900":"border-gray-300 bg-white"}`,children:[e.jsx("option",{value:"async",children:"Async (tracked)"}),e.jsx("option",{value:"sync",children:"Sync (wait for result)"}),e.jsx("option",{value:"batch",children:"Batch (tracked)"})]})]}),e.jsxs("label",{className:`flex items-center gap-2 pt-6 text-sm ${u}`,children:[e.jsx("input",{type:"checkbox",checked:J,onChange:t=>se(t.target.checked)})," Retry failed work up to 3 times"]})]}),h==="batch"&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("label",{className:"block text-sm font-medium",children:["Batch payloads ",e.jsx("span",{className:u,children:"(non-empty JSON array)"})]}),e.jsx("button",{type:"button",onClick:re,disabled:!A,className:`rounded-md border px-2.5 py-1.5 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-700":"border-gray-300 hover:bg-gray-100"}`,children:"Use current form as first item"})]}),e.jsx("p",{className:`mt-1 text-xs ${u}`,children:"The first item is generated from this resource’s live input schema; duplicate or edit it to create the batch. Items may be objects, arrays, or scalar JSON values when that is what the selected resource publishes."}),e.jsx("textarea",{"aria-label":"Batch payloads",value:U,onChange:t=>R(t.target.value),rows:7,spellCheck:!1,className:`mt-2 block w-full rounded-lg border p-3 font-mono text-xs ${a?"border-gray-600 bg-gray-950":"border-gray-300 bg-gray-50"}`})]}),e.jsx("button",{type:"button",disabled:!A||_,onClick:()=>{ne()},className:"mt-5 w-full rounded-lg bg-violet-600 px-4 py-3 text-sm font-semibold text-white hover:bg-violet-700 disabled:cursor-not-allowed disabled:opacity-50",children:_?"Submitting…":h==="sync"?"Run and wait for result":h==="batch"?"Submit batch task":"Submit tracked task"})]}),e.jsxs("section",{className:`rounded-xl border shadow-sm ${W}`,children:[e.jsx("div",{className:`flex flex-wrap items-center justify-between gap-2 border-b p-4 sm:p-5 ${a?"border-gray-700":"border-gray-200"}`,children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Live tasks"}),e.jsxs("p",{className:`text-xs ${u}`,children:[w.length," most recent records · active records refresh every 1.5 seconds"]})]})}),w.length===0?e.jsx("p",{className:`p-5 text-sm ${u}`,children:"No tasks have been submitted from this deployment."}):e.jsx("div",{className:"divide-y overflow-x-auto divide-gray-200 dark:divide-gray-700",children:w.map(t=>e.jsxs("article",{className:`min-w-0 p-4 transition-colors ${b?.id===t.id?a?"bg-violet-950/25":"bg-violet-50/60":""}`,children:[e.jsxs("div",{className:"flex flex-col items-start justify-between gap-3 sm:flex-row",children:[e.jsxs("button",{type:"button",onClick:()=>I(t),className:"min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-semibold",children:t.target}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${ge(t.status,a)}`,children:t.status})]}),e.jsxs("p",{className:`mt-1 text-xs ${u}`,children:[B(t.target_type)," · ",t.mode," · started ",pe(t.started_at||t.created_at)]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!L.has(t.status)&&e.jsx("button",{type:"button",onClick:()=>{G(t,"cancel")},disabled:C!==null,className:"rounded border border-amber-400 px-2 py-1 text-xs text-amber-700 hover:bg-amber-50 disabled:opacity-50 dark:text-amber-300 dark:hover:bg-amber-950",children:C===`cancel:${t.id}`?"Cancelling…":"Cancel"}),L.has(t.status)&&e.jsx("button",{type:"button",onClick:()=>{G(t,"delete")},disabled:C!==null,className:`rounded border px-2 py-1 text-xs disabled:opacity-50 ${a?"border-gray-600 hover:bg-gray-700":"border-gray-300 hover:bg-gray-100"}`,children:C===`delete:${t.id}`?"Removing…":"Remove"})]})]}),(t.progress.message||t.progress.percent!==null)&&e.jsxs("div",{className:`mt-3 text-xs ${u}`,children:[e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t.progress.stage||t.progress.message||"Working"}),e.jsx("span",{children:t.progress.percent===null?"In progress":`${Math.round(t.progress.percent)}%`})]}),e.jsx("div",{className:`mt-1 h-1.5 overflow-hidden rounded-full ${a?"bg-gray-700":"bg-gray-200"}`,children:e.jsx("div",{className:"h-full bg-violet-500 transition-all",style:{width:`${t.progress.percent??8}%`}})})]}),t.error&&e.jsx("p",{className:"mt-2 rounded bg-red-50 p-2 text-xs text-red-700 dark:bg-red-950/40 dark:text-red-200",children:t.error})]},t.id))}),b&&e.jsxs("div",{className:`border-t p-4 sm:p-5 ${a?"border-gray-700 bg-gray-950/35":"border-gray-100 bg-gray-50/70"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold",children:"Task detail"}),e.jsx("code",{className:`max-w-full truncate text-xs ${u}`,children:b.id})]}),e.jsxs("div",{className:`mt-2 grid grid-cols-2 gap-2 text-xs ${u}`,children:[e.jsxs("span",{children:["Attempts: ",b.attempts]}),e.jsxs("span",{children:["Duration: ",b.duration_ms===null?"—":`${Math.round(b.duration_ms)} ms`]})]}),e.jsx("pre",{className:`mt-3 max-h-64 overflow-auto rounded-lg p-3 text-xs whitespace-pre-wrap break-words ${a?"bg-gray-950 text-gray-200":"bg-white text-gray-800"}`,children:JSON.stringify(b.error?{error:b.error}:b.result??b.input,null,2)})]})]})]})]})};export{ve as TasksView}; diff --git a/src/agentomatic/studio/static/assets/index-FSSL6O5F.js b/src/agentomatic/studio/static/assets/index-BMj1jeBL.js similarity index 99% rename from src/agentomatic/studio/static/assets/index-FSSL6O5F.js rename to src/agentomatic/studio/static/assets/index-BMj1jeBL.js index f76b1e7a..fd3e78ec 100644 --- a/src/agentomatic/studio/static/assets/index-FSSL6O5F.js +++ b/src/agentomatic/studio/static/assets/index-BMj1jeBL.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GraphView-CMqOwCTc.js","assets/react-vendor-BHJ3EV8m.js","assets/SchemaForm-DyHc2s7z.js","assets/OutputSchemaSummary-C65WaRqI.js","assets/syntax-vendor-ru7AzRyY.js","assets/ChatView-C7_FNxo9.js","assets/ClipboardDocumentIcon-Cnz7XqGa.js","assets/DebugView-Bwa7sy_c.js","assets/PipelinesView-DacXbEMw.js","assets/BuilderView-C296ULRo.js","assets/ui-vendor-DIaV1y77.js","assets/PluginsView-COAn7Q5V.js","assets/IngestorsView-Cd56f61k.js","assets/TasksView-DAoR0f0z.js","assets/ControlPlaneView-CC__Od52.js","assets/EndpointsView-fCUdmgxr.js","assets/ConnectionsView-Dvq88oBW.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GraphView-CxhhCL_h.js","assets/react-vendor-BHJ3EV8m.js","assets/SchemaForm-Kr1WPDMd.js","assets/OutputSchemaSummary-CiE3pU-0.js","assets/syntax-vendor-ru7AzRyY.js","assets/ChatView-Bc4TZ9mm.js","assets/ClipboardDocumentIcon-Cnz7XqGa.js","assets/DebugView-BXWYXNI6.js","assets/PipelinesView-Yvdzmlvq.js","assets/BuilderView-BChq4Mpg.js","assets/ui-vendor-DIaV1y77.js","assets/PluginsView-BCct6WZb.js","assets/IngestorsView-Be0ZMvN2.js","assets/TasksView-B5ml_CT4.js","assets/ControlPlaneView-Vj8HdZgI.js","assets/EndpointsView-DqDGXNuG.js","assets/ConnectionsView-CD79PtTG.js"])))=>i.map(i=>d[i]); import{a as Qe,b as Dt,g as St,r as h,R as B,c as Pt,u as Mt,B as It,d as Lt,e as Re,N as et}from"./react-vendor-BHJ3EV8m.js";import{_ as Et,a as G}from"./syntax-vendor-ru7AzRyY.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();var De={exports:{}},fe={};var tt;function Ut(){if(tt)return fe;tt=1;var t=Qe(),e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,a=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function s(i,l,d){var u,m={},f=null,x=null;d!==void 0&&(f=""+d),l.key!==void 0&&(f=""+l.key),l.ref!==void 0&&(x=l.ref);for(u in l)n.call(l,u)&&!o.hasOwnProperty(u)&&(m[u]=l[u]);if(i&&i.defaultProps)for(u in l=i.defaultProps,l)m[u]===void 0&&(m[u]=l[u]);return{$$typeof:e,type:i,key:f,ref:x,props:m,_owner:a.current}}return fe.Fragment=r,fe.jsx=s,fe.jsxs=s,fe}var rt;function qt(){return rt||(rt=1,De.exports=Ut()),De.exports}var c=qt(),we={},nt;function Vt(){if(nt)return we;nt=1;var t=Dt();return we.createRoot=t.createRoot,we.hydrateRoot=t.hydrateRoot,we}var Wt=Vt();const Bt=St(Wt);let Ft={data:""},zt=t=>typeof window=="object"?((t?t.querySelector("#_goober"):window._goober)||Object.assign((t||document.head).appendChild(document.createElement("style")),{innerHTML:" ",id:"_goober"})).firstChild:t||Ft,Yt=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,Ht=/\/\*[^]*?\*\/| +/g,at=/\n+/g,te=(t,e)=>{let r="",n="",a="";for(let o in t){let s=t[o];o[0]=="@"?o[1]=="i"?r=o+" "+s+";":n+=o[1]=="f"?te(s,o):o+"{"+te(s,o[1]=="k"?"":e)+"}":typeof s=="object"?n+=te(s,e?e.replace(/([^,])+/g,i=>o.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,l=>/&/.test(l)?l.replace(/&/g,i):i?i+" "+l:l)):o):s!=null&&(o=/^--/.test(o)?o:o.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=te.p?te.p(o,s):o+":"+s+";")}return r+(e&&a?e+"{"+a+"}":a)+n},Q={},kt=t=>{if(typeof t=="object"){let e="";for(let r in t)e+=r+kt(t[r]);return e}return t},Gt=(t,e,r,n,a)=>{let o=kt(t),s=Q[o]||(Q[o]=(l=>{let d=0,u=11;for(;d>>0;return"go"+u})(o));if(!Q[s]){let l=o!==t?t:(d=>{let u,m,f=[{}];for(;u=Yt.exec(d.replace(Ht,""));)u[4]?f.shift():u[3]?(m=u[3].replace(at," ").trim(),f.unshift(f[0][m]=f[0][m]||{})):f[0][u[1]]=u[2].replace(at," ").trim();return f[0]})(t);Q[s]=te(a?{["@keyframes "+s]:l}:l,r?"":"."+s)}let i=r&&Q.g?Q.g:null;return r&&(Q.g=Q[s]),((l,d,u,m)=>{m?d.data=d.data.replace(m,l):d.data.indexOf(l)===-1&&(d.data=u?l+d.data:d.data+l)})(Q[s],e,n,i),s},Kt=(t,e,r)=>t.reduce((n,a,o)=>{let s=e[o];if(s&&s.call){let i=s(r),l=i&&i.props&&i.props.className||/^go/.test(i)&&i;s=l?"."+l:i&&typeof i=="object"?i.props?"":te(i,""):i===!1?"":i}return n+a+(s??"")},"");function $e(t){let e=this||{},r=t.call?t(e.p):t;return Gt(r.unshift?r.raw?Kt(r,[].slice.call(arguments,1),e.p):r.reduce((n,a)=>Object.assign(n,a&&a.call?a(e.p):a),{}):r,zt(e.target),e.g,e.o,e.k)}let Tt,He,Ge;$e.bind({g:1});let Z=$e.bind({k:1});function Jt(t,e,r,n){te.p=e,Tt=t,He=r,Ge=n}function re(t,e){let r=this||{};return function(){let n=arguments;function a(o,s){let i=Object.assign({},o),l=i.className||a.className;r.p=Object.assign({theme:He&&He()},i),r.o=/ *go\d+/.test(l),i.className=$e.apply(r,n)+(l?" "+l:"");let d=t;return t[0]&&(d=i.as||t,delete i.as),Ge&&d[0]&&Ge(i),Tt(d,i)}return a}}var Xt=t=>typeof t=="function",Te=(t,e)=>Xt(t)?t(e):t,Qt=(()=>{let t=0;return()=>(++t).toString()})(),At=(()=>{let t;return()=>{if(t===void 0&&typeof window<"u"){let e=matchMedia("(prefers-reduced-motion: reduce)");t=!e||e.matches}return t}})(),Zt=20,jt=(t,e)=>{switch(e.type){case 0:return{...t,toasts:[e.toast,...t.toasts].slice(0,Zt)};case 1:return{...t,toasts:t.toasts.map(o=>o.id===e.toast.id?{...o,...e.toast}:o)};case 2:let{toast:r}=e;return jt(t,{type:t.toasts.find(o=>o.id===r.id)?1:0,toast:r});case 3:let{toastId:n}=e;return{...t,toasts:t.toasts.map(o=>o.id===n||n===void 0?{...o,dismissed:!0,visible:!1}:o)};case 4:return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(o=>o.id!==e.toastId)};case 5:return{...t,pausedAt:e.time};case 6:let a=e.time-(t.pausedAt||0);return{...t,pausedAt:void 0,toasts:t.toasts.map(o=>({...o,pauseDuration:o.pauseDuration+a}))}}},ke=[],ie={toasts:[],pausedAt:void 0},de=t=>{ie=jt(ie,t),ke.forEach(e=>{e(ie)})},er={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},tr=(t={})=>{let[e,r]=h.useState(ie),n=h.useRef(ie);h.useEffect(()=>(n.current!==ie&&r(ie),ke.push(r),()=>{let o=ke.indexOf(r);o>-1&&ke.splice(o,1)}),[]);let a=e.toasts.map(o=>{var s,i,l;return{...t,...t[o.type],...o,removeDelay:o.removeDelay||((s=t[o.type])==null?void 0:s.removeDelay)||t?.removeDelay,duration:o.duration||((i=t[o.type])==null?void 0:i.duration)||t?.duration||er[o.type],style:{...t.style,...(l=t[o.type])==null?void 0:l.style,...o.style}}});return{...e,toasts:a}},rr=(t,e="blank",r)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:e,ariaProps:{role:"status","aria-live":"polite"},message:t,pauseDuration:0,...r,id:r?.id||Qt()}),be=t=>(e,r)=>{let n=rr(e,t,r);return de({type:2,toast:n}),n.id},V=(t,e)=>be("blank")(t,e);V.error=be("error");V.success=be("success");V.loading=be("loading");V.custom=be("custom");V.dismiss=t=>{de({type:3,toastId:t})};V.remove=t=>de({type:4,toastId:t});V.promise=(t,e,r)=>{let n=V.loading(e.loading,{...r,...r?.loading});return typeof t=="function"&&(t=t()),t.then(a=>{let o=e.success?Te(e.success,a):void 0;return o?V.success(o,{id:n,...r,...r?.success}):V.dismiss(n),a}).catch(a=>{let o=e.error?Te(e.error,a):void 0;o?V.error(o,{id:n,...r,...r?.error}):V.dismiss(n)}),t};var nr=(t,e)=>{de({type:1,toast:{id:t,height:e}})},ar=()=>{de({type:5,time:Date.now()})},xe=new Map,or=1e3,sr=(t,e=or)=>{if(xe.has(t))return;let r=setTimeout(()=>{xe.delete(t),de({type:4,toastId:t})},e);xe.set(t,r)},ir=t=>{let{toasts:e,pausedAt:r}=tr(t);h.useEffect(()=>{if(r)return;let o=Date.now(),s=e.map(i=>{if(i.duration===1/0)return;let l=(i.duration||0)+i.pauseDuration-(o-i.createdAt);if(l<0){i.visible&&V.dismiss(i.id);return}return setTimeout(()=>V.dismiss(i.id),l)});return()=>{s.forEach(i=>i&&clearTimeout(i))}},[e,r]);let n=h.useCallback(()=>{r&&de({type:6,time:Date.now()})},[r]),a=h.useCallback((o,s)=>{let{reverseOrder:i=!1,gutter:l=8,defaultPosition:d}=s||{},u=e.filter(x=>(x.position||d)===(o.position||d)&&x.height),m=u.findIndex(x=>x.id===o.id),f=u.filter((x,v)=>vx.visible).slice(...i?[f+1]:[0,f]).reduce((x,v)=>x+(v.height||0)+l,0)},[e]);return h.useEffect(()=>{e.forEach(o=>{if(o.dismissed)sr(o.id,o.removeDelay);else{let s=xe.get(o.id);s&&(clearTimeout(s),xe.delete(o.id))}})},[e]),{toasts:e,handlers:{updateHeight:nr,startPause:ar,endPause:n,calculateOffset:a}}},cr=Z` from { transform: scale(0) rotate(45deg); @@ -194,4 +194,4 @@ ${k} The agent may not be reachable (check name/slug, server logs, and /studio/agents).`,timestamp:new Date}),R.emit({type:"EXECUTION_COMPLETED",data:{threadId:w.selectedThread?.id||"unknown",finalState:w.executionContext.currentState,duration:0}})},onDone:()=>{console.log("📡 SSE stream complete");const b=e();b.executionContext.isExecuting&&!b.executionContext.isPaused&&b.stopExecution(),t({isLoading:!1})}});t({activeAbortController:ne});return}throw new Error("Studio API client not initialized. Cannot execute agent.")}catch(v){console.error("❌ Agentomatic execution error:",v);const p=e();if(p.stopExecution(),p.addExecutionLog({nodeId:"system",nodeName:"System",type:"error",message:`Execution failed: ${v instanceof Error?v.message:"Unknown error"}`,data:{error:v instanceof Error?v.message:String(v)}}),p.selectedThread){const y={id:`msg-${Date.now()}-error`,role:"assistant",content:`❌ **Execution Error** -Failed to execute: ${v instanceof Error?v.message:"Unknown error"}`,timestamp:new Date};p.addMessageToThread(p.selectedThread.id,y)}}})().catch(v=>{console.error("Failed to execute Agentomatic agent:",v),e().stopExecution()})},addInterrupt:r=>t(n=>(R.emit({type:"INTERRUPT_RECEIVED",data:r}),{activeInterrupts:[...n.activeInterrupts,r]})),resolveInterrupt:(r,n)=>t(a=>(R.emit({type:"INTERRUPT_RESOLVED",data:{interruptId:r,resolution:n}}),{activeInterrupts:a.activeInterrupts.map(o=>o.id===r?{...o,status:n==="approved"?"approved":"rejected",resolvedAt:new Date}:o)})),clearInterrupts:()=>t({activeInterrupts:[]}),addSubAgentResult:r=>t(n=>(R.emit({type:"SUB_AGENT_COMPLETED",data:r}),{subAgentResults:[...n.subAgentResults,r]})),clearSubAgentResults:()=>t({subAgentResults:[]}),reset:()=>t({...We,selectedThread:void 0,selectedAgent:void 0,selectedAssistant:void 0,threads:[],agents:[],assistants:[],runs:[],currentRun:void 0,executionContext:Be,executionContexts:new Map,activeInterrupts:[],subAgentResults:[],agentSchemas:{},schemasLoading:!1,isStreaming:!1,streamingMessage:"",activeAbortController:null})}),{name:"studio-store"})),Ro=(t,e,r=[])=>{const n=h.useRef(e);n.current=e,h.useEffect(()=>R.subscribe(t,o=>{n.current(o)}),[t,...r])},Do=(t,e=[])=>{const r=h.useRef(t);r.current=t,h.useEffect(()=>R.subscribeAll(a=>{r.current(a)}),e)};function cn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"}))}const dn=h.forwardRef(cn);function ln({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"}))}const un=h.forwardRef(ln);function mn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 0 1-.825-.242m9.345-8.334a2.126 2.126 0 0 0-.476-.095 48.64 48.64 0 0 0-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0 0 11.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155"}))}const fn=h.forwardRef(mn);function pn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"}))}const pt=h.forwardRef(pn);function hn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m19.5 8.25-7.5 7.5-7.5-7.5"}))}const gn=h.forwardRef(hn);function yn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 0v3.75m-16.5-3.75v3.75m16.5 0v3.75C20.25 16.153 16.556 18 12 18s-8.25-1.847-8.25-4.125v-3.75m16.5 0c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125"}))}const xn=h.forwardRef(yn);function bn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const vn=h.forwardRef(bn);function wn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4.5 12a7.5 7.5 0 0 0 15 0m-15 0a7.5 7.5 0 1 1 15 0m-15 0H3m16.5 0H21m-1.5 0H12m-8.457 3.077 1.41-.513m14.095-5.13 1.41-.513M5.106 17.785l1.15-.964m11.49-9.642 1.149-.964M7.501 19.795l.75-1.3m7.5-12.99.75-1.3m-6.063 16.658.26-1.477m2.605-14.772.26-1.477m0 17.726-.26-1.477M10.698 4.614l-.26-1.477M16.5 19.794l-.75-1.299M7.5 4.205 12 12m6.894 5.785-1.149-.964M6.256 7.178l-1.15-.964m15.352 8.864-1.41-.513M4.954 9.435l-1.41-.514M12.002 12l-3.75 6.495"}))}const pe=h.forwardRef(wn);function Cn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m6.75 7.5 3 2.25-3 2.25m4.5 0h3m-9 8.25h13.5A2.25 2.25 0 0 0 21 18V6a2.25 2.25 0 0 0-2.25-2.25H5.25A2.25 2.25 0 0 0 3 6v12a2.25 2.25 0 0 0 2.25 2.25Z"}))}const Fe=h.forwardRef(Cn);function Sn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418"}))}const En=h.forwardRef(Sn);function kn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z"}))}const Tn=h.forwardRef(kn);function An({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4.5v15m7.5-7.5h-15"}))}const jn=h.forwardRef(An);function _n({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 0 1 0 3.75H5.625a1.875 1.875 0 0 1 0-3.75Z"}))}const Nn=h.forwardRef(_n);function $n({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"}))}const On=h.forwardRef($n);function Rn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"}))}const Dn=h.forwardRef(Rn);function Pn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"}))}const Mn=h.forwardRef(Pn);function In({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const Ln=h.forwardRef(In),Un=()=>{const{assistants:t,selectedAssistant:e,setSelectedAssistant:r,currentView:n,setCurrentView:a,darkMode:o,setDarkMode:s,sidebarCollapsed:i,setSidebarCollapsed:l,config:d,fetchGraphData:u,refreshThreads:m,connectionStatus:f,retryAttempts:x,maxRetryAttempts:v,attemptReconnection:p}=me(),[y,g]=h.useState(!1),C=h.useRef(null),T=h.useRef(null),[j,N]=h.useState({top:0,left:0,width:0});h.useEffect(()=>{const E=L=>{C.current&&!C.current.contains(L.target)&&T.current&&!T.current.contains(L.target)&&g(!1)};if(y)return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[y]),h.useEffect(()=>{if(y&&T.current){const E=()=>{const M=T.current.getBoundingClientRect();N({top:M.bottom+8,left:M.left,width:M.width})};E();const L=()=>E(),D=()=>E();return window.addEventListener("scroll",L,!0),window.addEventListener("resize",D),()=>{window.removeEventListener("scroll",L,!0),window.removeEventListener("resize",D)}}},[y]);const A=async E=>{r(E),g(!1);try{await u(E.id),await m(E.id)}catch(L){console.error("Failed to fetch graph data:",L)}},I=E=>{switch(E){case"langgraph":return o?"bg-emerald-900 text-emerald-300":"bg-emerald-100 text-emerald-700";case"deepagent":return o?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-700";case"langchain":return o?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700";default:return o?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}},q=[{key:"graph",label:"Graph",icon:Fe},{key:"chat",label:"Chat",icon:fn},{key:"debug",label:"Debug",icon:pe},{key:"pipelines",label:"Pipelines",icon:Fe},{key:"builder",label:"Builder",icon:On},{key:"plugins",label:"Plugins",icon:pe},{key:"ingestion",label:"Ingestors",icon:Fe},{key:"tasks",label:"Tasks",icon:Nn},{key:"control",label:"Control",icon:dn},{key:"endpoints",label:"Endpoints",icon:En},{key:"connections",label:"Connections",icon:xn}];return c.jsxs("header",{className:`flex min-h-16 items-center justify-between gap-2 px-3 py-2 sm:px-6 border-b backdrop-blur-sm transition-colors duration-300 ${o?"bg-gray-800/95 border-gray-700 text-white":"bg-white/95 border-gray-200 text-gray-900"}`,children:[c.jsxs("div",{className:"flex min-w-0 items-center space-x-2 sm:space-x-4",children:[c.jsx("button",{onClick:()=>l(!i),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-gray-300":"hover:bg-gray-100 text-gray-600"}`,title:i?"Show Sidebar":"Hide Sidebar",children:i?c.jsx(un,{className:"w-5 h-5"}):c.jsx(Ln,{className:"w-5 h-5"})}),c.jsxs("div",{className:"flex items-center space-x-2 sm:space-x-3",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-violet-600",children:c.jsx("span",{className:"text-white font-bold text-sm",children:"AS"})}),c.jsxs("div",{className:"hidden sm:block",children:[c.jsx("h1",{className:"text-lg font-semibold",children:"Agentomatic Studio"}),c.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:f==="connected"?"Connected":"Reconnecting…"})]})]}),c.jsx("nav",{className:`hidden 2xl:flex min-w-0 items-center space-x-1 rounded-xl p-1 ml-3 xl:ml-6 overflow-x-auto ${o?"bg-gray-700":"bg-gray-100"}`,children:q.map(({key:E,label:L,icon:D})=>c.jsxs("button",{onClick:()=>a(E),className:`flex shrink-0 items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${n===E?o?"bg-blue-600 text-white shadow-lg transform scale-105":"bg-white text-blue-600 shadow-md transform scale-105":o?"text-gray-300 hover:text-white hover:bg-gray-600":"text-gray-600 hover:text-gray-900 hover:bg-white/50"}`,children:[c.jsx(D,{className:"w-4 h-4 mr-2"}),L]},E))}),c.jsx("select",{value:n,onChange:E=>a(E.target.value),"aria-label":"Select Studio view",className:`max-w-28 rounded-lg border px-2 py-2 text-sm font-medium sm:max-w-36 md:max-w-44 2xl:hidden ${o?"border-gray-600 bg-gray-700 text-white":"border-gray-300 bg-white text-gray-900"}`,children:q.map(({key:E,label:L})=>c.jsx("option",{value:E,children:L},E))})]}),c.jsx("div",{className:"flex flex-1 justify-end sm:justify-center",children:c.jsxs("div",{className:"relative",ref:C,children:[c.jsxs("button",{onClick:()=>g(!y),className:`flex max-w-[13rem] items-center space-x-2 px-2 py-2 sm:max-w-none sm:space-x-3 sm:px-4 rounded-xl border transition-all duration-200 ${o?"bg-gray-700 border-gray-600 text-white hover:bg-gray-600":"bg-white border-gray-300 text-gray-900 hover:bg-gray-50"}`,ref:T,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${o?"bg-blue-600":"bg-blue-100"}`,children:c.jsx(pe,{className:`w-4 h-4 ${o?"text-white":"text-blue-600"}`})}),c.jsxs("div",{className:"min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx("span",{className:"truncate text-sm font-medium",children:e?.name||"Select Agent"}),e?.metadata?.framework&&c.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full font-medium ${I(e.metadata.framework)}`,children:e.metadata.framework})]}),c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:e?.description||"No agent selected"})]}),c.jsx(gn,{className:`w-4 h-4 transition-transform ${y?"rotate-180":""}`})]}),y&&Pt.createPortal(c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fixed inset-0 z-[999998] bg-black/10",onClick:()=>g(!1)}),c.jsx("div",{ref:C,className:`fixed rounded-xl border shadow-2xl z-[999999] ${o?"bg-gray-800 border-gray-600":"bg-white border-gray-200"}`,style:{top:j.top,left:j.left,width:Math.max(j.width,320),maxHeight:"400px"},children:c.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:t.length===0?c.jsxs("div",{className:`p-4 text-center ${o?"text-gray-400":"text-gray-500"}`,children:[c.jsx(pe,{className:`w-8 h-8 mx-auto mb-2 ${o?"text-gray-600":"text-gray-300"}`}),c.jsx("p",{className:"text-sm",children:"No agents available"}),c.jsx("p",{className:"text-xs mt-1",children:"Check your server connection"})]}):t.map(E=>c.jsxs("button",{onClick:()=>A(E),className:`w-full flex items-center space-x-3 p-3 rounded-lg transition-colors ${e?.id===E.id?o?"bg-blue-900 border border-blue-700":"bg-blue-50 border border-blue-200":o?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${e?.id===E.id?"bg-blue-600":o?"bg-gray-600":"bg-gray-200"}`,children:c.jsx(pe,{className:`w-4 h-4 ${e?.id===E.id?"text-white":o?"text-gray-300":"text-gray-600"}`})}),c.jsxs("div",{className:"flex-1 text-left",children:[c.jsx("div",{className:`text-sm font-medium ${o?"text-white":"text-gray-900"}`,children:E.name}),E.description&&c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:E.description}),c.jsxs("div",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:["Graph: ",E.graph_id]})]}),e?.id===E.id&&c.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full"})]},E.id))})})]}),document.body)]})}),c.jsxs("div",{className:"flex items-center space-x-1.5 sm:space-x-3",children:[c.jsxs("div",{className:"hidden items-center space-x-2 xl:flex",children:[c.jsx("div",{className:`w-2 h-2 rounded-full ${f==="connected"?"bg-green-500 animate-pulse":f==="reconnecting"?"bg-yellow-500 animate-spin":f==="failed"?"bg-red-500":"bg-gray-500"}`}),c.jsx("span",{className:`text-sm ${o?"text-gray-300":"text-gray-600"}`,children:f==="connected"?c.jsx("span",{title:d.apiUrl,children:d.apiUrl.replace(/^https?:\/\//,"").slice(0,25)}):f==="reconnecting"?`Reconnecting (${x}/${v})`:f==="failed"?"Connection Failed":"Disconnected"}),(f==="disconnected"||f==="failed")&&c.jsx("button",{onClick:p,className:`px-2 py-1 text-xs rounded transition-colors ${o?"bg-blue-600 text-white hover:bg-blue-700":"bg-blue-500 text-white hover:bg-blue-600"}`,title:"Retry Connection",children:"Retry"})]}),c.jsx("button",{onClick:()=>s(!o),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-yellow-400":"hover:bg-gray-100 text-gray-600"}`,title:o?"Switch to Light Mode":"Switch to Dark Mode",children:o?c.jsx(Dn,{className:"w-5 h-5"}):c.jsx(Tn,{className:"w-5 h-5"})}),c.jsx("div",{className:`hidden text-xs px-2 py-1 rounded 2xl:block ${o?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-500"}`,children:"⌘1-9 to switch views"})]})]})};function ce(t){if(t===null||t===!0||t===!1)return NaN;var e=Number(t);return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}function W(t,e){if(e.length1?"s":"")+" required, but only "+e.length+" present")}function X(t){W(1,arguments);var e=Object.prototype.toString.call(t);return t instanceof Date||Et(t)==="object"&&e==="[object Date]"?new Date(t.getTime()):typeof t=="number"||e==="[object Number]"?new Date(t):((typeof t=="string"||e==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function qn(t,e){W(2,arguments);var r=X(t).getTime(),n=ce(e);return new Date(r+n)}var Vn={};function Oe(){return Vn}function Wn(t){var e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),t.getTime()-e.getTime()}function Bn(t){return W(1,arguments),t instanceof Date||Et(t)==="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Fn(t){if(W(1,arguments),!Bn(t)&&typeof t!="number")return!1;var e=X(t);return!isNaN(Number(e))}function zn(t,e){W(2,arguments);var r=ce(e);return qn(t,-r)}var Yn=864e5;function Hn(t){W(1,arguments);var e=X(t),r=e.getTime();e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);var n=e.getTime(),a=r-n;return Math.floor(a/Yn)+1}function je(t){W(1,arguments);var e=1,r=X(t),n=r.getUTCDay(),a=(n=a.getTime()?r+1:e.getTime()>=s.getTime()?r:r-1}function Gn(t){W(1,arguments);var e=$t(t),r=new Date(0);r.setUTCFullYear(e,0,4),r.setUTCHours(0,0,0,0);var n=je(r);return n}var Kn=6048e5;function Jn(t){W(1,arguments);var e=X(t),r=je(e).getTime()-Gn(e).getTime();return Math.round(r/Kn)+1}function _e(t,e){var r,n,a,o,s,i,l,d;W(1,arguments);var u=Oe(),m=ce((r=(n=(a=(o=e?.weekStartsOn)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.weekStartsOn)!==null&&a!==void 0?a:u.weekStartsOn)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.weekStartsOn)!==null&&r!==void 0?r:0);if(!(m>=0&&m<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var f=X(t),x=f.getUTCDay(),v=(x=1&&x<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var v=new Date(0);v.setUTCFullYear(m+1,0,x),v.setUTCHours(0,0,0,0);var p=_e(v,e),y=new Date(0);y.setUTCFullYear(m,0,x),y.setUTCHours(0,0,0,0);var g=_e(y,e);return u.getTime()>=p.getTime()?m+1:u.getTime()>=g.getTime()?m:m-1}function Xn(t,e){var r,n,a,o,s,i,l,d;W(1,arguments);var u=Oe(),m=ce((r=(n=(a=(o=e?.firstWeekContainsDate)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.firstWeekContainsDate)!==null&&a!==void 0?a:u.firstWeekContainsDate)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&r!==void 0?r:1),f=Ot(t,e),x=new Date(0);x.setUTCFullYear(f,0,m),x.setUTCHours(0,0,0,0);var v=_e(x,e);return v}var Qn=6048e5;function Zn(t,e){W(1,arguments);var r=X(t),n=_e(r,e).getTime()-Xn(r,e).getTime();return Math.round(n/Qn)+1}function $(t,e){for(var r=t<0?"-":"",n=Math.abs(t).toString();n.length0?n:1-n;return $(r==="yy"?a%100:a,r.length)},M:function(e,r){var n=e.getUTCMonth();return r==="M"?String(n+1):$(n+1,2)},d:function(e,r){return $(e.getUTCDate(),r.length)},a:function(e,r){var n=e.getUTCHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h:function(e,r){return $(e.getUTCHours()%12||12,r.length)},H:function(e,r){return $(e.getUTCHours(),r.length)},m:function(e,r){return $(e.getUTCMinutes(),r.length)},s:function(e,r){return $(e.getUTCSeconds(),r.length)},S:function(e,r){var n=r.length,a=e.getUTCMilliseconds(),o=Math.floor(a*Math.pow(10,n-3));return $(o,r.length)}},ue={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},ea={G:function(e,r,n){var a=e.getUTCFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});default:return n.era(a,{width:"wide"})}},y:function(e,r,n){if(r==="yo"){var a=e.getUTCFullYear(),o=a>0?a:1-a;return n.ordinalNumber(o,{unit:"year"})}return ee.y(e,r)},Y:function(e,r,n,a){var o=Ot(e,a),s=o>0?o:1-o;if(r==="YY"){var i=s%100;return $(i,2)}return r==="Yo"?n.ordinalNumber(s,{unit:"year"}):$(s,r.length)},R:function(e,r){var n=$t(e);return $(n,r.length)},u:function(e,r){var n=e.getUTCFullYear();return $(n,r.length)},Q:function(e,r,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"Q":return String(a);case"QQ":return $(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(e,r,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"q":return String(a);case"qq":return $(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(e,r,n){var a=e.getUTCMonth();switch(r){case"M":case"MM":return ee.M(e,r);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(e,r,n){var a=e.getUTCMonth();switch(r){case"L":return String(a+1);case"LL":return $(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(e,r,n,a){var o=Zn(e,a);return r==="wo"?n.ordinalNumber(o,{unit:"week"}):$(o,r.length)},I:function(e,r,n){var a=Jn(e);return r==="Io"?n.ordinalNumber(a,{unit:"week"}):$(a,r.length)},d:function(e,r,n){return r==="do"?n.ordinalNumber(e.getUTCDate(),{unit:"date"}):ee.d(e,r)},D:function(e,r,n){var a=Hn(e);return r==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):$(a,r.length)},E:function(e,r,n){var a=e.getUTCDay();switch(r){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(e,r,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(r){case"e":return String(s);case"ee":return $(s,2);case"eo":return n.ordinalNumber(s,{unit:"day"});case"eee":return n.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(o,{width:"short",context:"formatting"});default:return n.day(o,{width:"wide",context:"formatting"})}},c:function(e,r,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(r){case"c":return String(s);case"cc":return $(s,r.length);case"co":return n.ordinalNumber(s,{unit:"day"});case"ccc":return n.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(o,{width:"narrow",context:"standalone"});case"cccccc":return n.day(o,{width:"short",context:"standalone"});default:return n.day(o,{width:"wide",context:"standalone"})}},i:function(e,r,n){var a=e.getUTCDay(),o=a===0?7:a;switch(r){case"i":return String(o);case"ii":return $(o,r.length);case"io":return n.ordinalNumber(o,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(e,r,n){var a=e.getUTCHours(),o=a/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,r,n){var a=e.getUTCHours(),o;switch(a===12?o=ue.noon:a===0?o=ue.midnight:o=a/12>=1?"pm":"am",r){case"b":case"bb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,r,n){var a=e.getUTCHours(),o;switch(a>=17?o=ue.evening:a>=12?o=ue.afternoon:a>=4?o=ue.morning:o=ue.night,r){case"B":case"BB":case"BBB":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,r,n){if(r==="ho"){var a=e.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return ee.h(e,r)},H:function(e,r,n){return r==="Ho"?n.ordinalNumber(e.getUTCHours(),{unit:"hour"}):ee.H(e,r)},K:function(e,r,n){var a=e.getUTCHours()%12;return r==="Ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,r.length)},k:function(e,r,n){var a=e.getUTCHours();return a===0&&(a=24),r==="ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,r.length)},m:function(e,r,n){return r==="mo"?n.ordinalNumber(e.getUTCMinutes(),{unit:"minute"}):ee.m(e,r)},s:function(e,r,n){return r==="so"?n.ordinalNumber(e.getUTCSeconds(),{unit:"second"}):ee.s(e,r)},S:function(e,r){return ee.S(e,r)},X:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();if(s===0)return"Z";switch(r){case"X":return gt(s);case"XXXX":case"XX":return se(s);default:return se(s,":")}},x:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"x":return gt(s);case"xxxx":case"xx":return se(s);default:return se(s,":")}},O:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},z:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},t:function(e,r,n,a){var o=a._originalDate||e,s=Math.floor(o.getTime()/1e3);return $(s,r.length)},T:function(e,r,n,a){var o=a._originalDate||e,s=o.getTime();return $(s,r.length)}};function ht(t,e){var r=t>0?"-":"+",n=Math.abs(t),a=Math.floor(n/60),o=n%60;if(o===0)return r+String(a);var s=e;return r+String(a)+s+$(o,2)}function gt(t,e){if(t%60===0){var r=t>0?"-":"+";return r+$(Math.abs(t)/60,2)}return se(t,e)}function se(t,e){var r=e||"",n=t>0?"-":"+",a=Math.abs(t),o=$(Math.floor(a/60),2),s=$(a%60,2);return n+o+r+s}var yt=function(e,r){switch(e){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});default:return r.date({width:"full"})}},Rt=function(e,r){switch(e){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});default:return r.time({width:"full"})}},ta=function(e,r){var n=e.match(/(P+)(p+)?/)||[],a=n[1],o=n[2];if(!o)return yt(e,r);var s;switch(a){case"P":s=r.dateTime({width:"short"});break;case"PP":s=r.dateTime({width:"medium"});break;case"PPP":s=r.dateTime({width:"long"});break;default:s=r.dateTime({width:"full"});break}return s.replace("{{date}}",yt(a,r)).replace("{{time}}",Rt(o,r))},ra={p:Rt,P:ta},na=["D","DD"],aa=["YY","YYYY"];function oa(t){return na.indexOf(t)!==-1}function sa(t){return aa.indexOf(t)!==-1}function xt(t,e,r){if(t==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var ia={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},ca=function(e,r,n){var a,o=ia[e];return typeof o=="string"?a=o:r===1?a=o.one:a=o.other.replace("{{count}}",r.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a};function ze(t){return function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=e.width?String(e.width):t.defaultWidth,n=t.formats[r]||t.formats[t.defaultWidth];return n}}var da={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},la={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},ua={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ma={date:ze({formats:da,defaultWidth:"full"}),time:ze({formats:la,defaultWidth:"full"}),dateTime:ze({formats:ua,defaultWidth:"full"})},fa={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},pa=function(e,r,n,a){return fa[e]};function he(t){return function(e,r){var n=r!=null&&r.context?String(r.context):"standalone",a;if(n==="formatting"&&t.formattingValues){var o=t.defaultFormattingWidth||t.defaultWidth,s=r!=null&&r.width?String(r.width):o;a=t.formattingValues[s]||t.formattingValues[o]}else{var i=t.defaultWidth,l=r!=null&&r.width?String(r.width):t.defaultWidth;a=t.values[l]||t.values[i]}var d=t.argumentCallback?t.argumentCallback(e):e;return a[d]}}var ha={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ga={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},ya={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},xa={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},ba={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},va={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},wa=function(e,r){var n=Number(e),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},Ca={ordinalNumber:wa,era:he({values:ha,defaultWidth:"wide"}),quarter:he({values:ga,defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:he({values:ya,defaultWidth:"wide"}),day:he({values:xa,defaultWidth:"wide"}),dayPeriod:he({values:ba,defaultWidth:"wide",formattingValues:va,defaultFormattingWidth:"wide"})};function ge(t){return function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.width,a=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],o=e.match(a);if(!o)return null;var s=o[0],i=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],l=Array.isArray(i)?Ea(i,function(m){return m.test(s)}):Sa(i,function(m){return m.test(s)}),d;d=t.valueCallback?t.valueCallback(l):l,d=r.valueCallback?r.valueCallback(d):d;var u=e.slice(s.length);return{value:d,rest:u}}}function Sa(t,e){for(var r in t)if(t.hasOwnProperty(r)&&e(t[r]))return r}function Ea(t,e){for(var r=0;r1&&arguments[1]!==void 0?arguments[1]:{},n=e.match(t.matchPattern);if(!n)return null;var a=n[0],o=e.match(t.parsePattern);if(!o)return null;var s=t.valueCallback?t.valueCallback(o[0]):o[0];s=r.valueCallback?r.valueCallback(s):s;var i=e.slice(a.length);return{value:s,rest:i}}}var Ta=/^(\d+)(th|st|nd|rd)?/i,Aa=/\d+/i,ja={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},_a={any:[/^b/i,/^(a|c)/i]},Na={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},$a={any:[/1/i,/2/i,/3/i,/4/i]},Oa={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Ra={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Da={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Pa={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Ma={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Ia={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},La={ordinalNumber:ka({matchPattern:Ta,parsePattern:Aa,valueCallback:function(e){return parseInt(e,10)}}),era:ge({matchPatterns:ja,defaultMatchWidth:"wide",parsePatterns:_a,defaultParseWidth:"any"}),quarter:ge({matchPatterns:Na,defaultMatchWidth:"wide",parsePatterns:$a,defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:ge({matchPatterns:Oa,defaultMatchWidth:"wide",parsePatterns:Ra,defaultParseWidth:"any"}),day:ge({matchPatterns:Da,defaultMatchWidth:"wide",parsePatterns:Pa,defaultParseWidth:"any"}),dayPeriod:ge({matchPatterns:Ma,defaultMatchWidth:"any",parsePatterns:Ia,defaultParseWidth:"any"})},Ua={code:"en-US",formatDistance:ca,formatLong:ma,formatRelative:pa,localize:Ca,match:La,options:{weekStartsOn:0,firstWeekContainsDate:1}},qa=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Va=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Wa=/^'([^]*?)'?$/,Ba=/''/g,Fa=/[a-zA-Z]/;function za(t,e,r){var n,a,o,s,i,l,d,u,m,f,x,v,p,y;W(2,arguments);var g=String(e),C=Oe(),T=(n=(a=void 0)!==null&&a!==void 0?a:C.locale)!==null&&n!==void 0?n:Ua,j=ce((o=(s=(i=(l=void 0)!==null&&l!==void 0?l:void 0)!==null&&i!==void 0?i:C.firstWeekContainsDate)!==null&&s!==void 0?s:(d=C.locale)===null||d===void 0||(u=d.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&o!==void 0?o:1);if(!(j>=1&&j<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var N=ce((m=(f=(x=(v=void 0)!==null&&v!==void 0?v:void 0)!==null&&x!==void 0?x:C.weekStartsOn)!==null&&f!==void 0?f:(p=C.locale)===null||p===void 0||(y=p.options)===null||y===void 0?void 0:y.weekStartsOn)!==null&&m!==void 0?m:0);if(!(N>=0&&N<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!T.localize)throw new RangeError("locale must contain localize property");if(!T.formatLong)throw new RangeError("locale must contain formatLong property");var A=X(t);if(!Fn(A))throw new RangeError("Invalid time value");var I=Wn(A),q=zn(A,I),E={firstWeekContainsDate:j,weekStartsOn:N,locale:T,_originalDate:A},L=g.match(Va).map(function(D){var M=D[0];if(M==="p"||M==="P"){var K=ra[M];return K(D,T.formatLong)}return D}).join("").match(qa).map(function(D){if(D==="''")return"'";var M=D[0];if(M==="'")return Ya(D);var K=ea[M];if(K)return sa(D)&&xt(D,e,String(t)),oa(D)&&xt(D,e,String(t)),K(q,D,T.localize,E);if(M.match(Fa))throw new RangeError("Format string contains an unescaped latin alphabet character `"+M+"`");return D}).join("");return L}function Ya(t){var e=t.match(Wa);return e?e[1].replace(Ba,"'"):t}const Ha=()=>{const{threads:t,selectedThread:e,setSelectedThread:r,createPersistentThread:n,deletePersistentThread:a,hydrateThreadMessages:o,selectedAssistant:s,darkMode:i}=me(),[l,d]=h.useState(null),[u,m]=h.useState(null),f=async()=>{if(!s?.id){m("Select a live agent before creating a thread.");return}d("new"),m(null);try{await n(s.id,`Thread ${t.length+1}`)}catch(p){m(p?.message||"Could not create a durable thread.")}finally{d(null)}},x=async p=>{const y=p.agentId||s?.id;d(`load:${p.id}`),m(null);try{const g=y?await o(p.id,y):void 0;r(g||p)}catch(g){m(g?.message||"Could not load this thread’s durable history."),r(p)}finally{d(null)}},v=async(p,y)=>{y.stopPropagation(),d(`delete:${p.id}`),m(null);try{await a(p)}catch(g){m(g?.message||"Could not delete the durable thread.")}finally{d(null)}};return c.jsxs("div",{className:`h-full flex flex-col ${i?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} border-r transition-colors duration-300`,children:[c.jsxs("div",{className:`p-4 border-b ${i?"border-gray-700":"border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(pt,{className:`w-5 h-5 ${i?"text-blue-400":"text-blue-600"}`}),c.jsx("h2",{className:`text-lg font-semibold ${i?"text-white":"text-gray-900"}`,children:"Threads"})]}),c.jsx("div",{className:`px-2 py-1 rounded-full text-xs font-medium ${i?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:t.length})]}),c.jsxs("button",{onClick:()=>{f()},disabled:l!==null,className:`w-full flex items-center justify-center px-4 py-3 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md ${i?"bg-blue-600 hover:bg-blue-700 text-white hover:scale-105":"bg-blue-600 text-white hover:bg-blue-700 hover:scale-105"}`,children:[c.jsx(jn,{className:"w-4 h-4 mr-2"}),l==="new"?"Creating…":"New Thread"]})]}),u&&c.jsx("p",{role:"alert",className:`mx-4 mb-3 rounded-md border p-2 text-xs ${i?"border-red-800 bg-red-950/40 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:u}),c.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:t.length===0?c.jsxs("div",{className:`p-6 text-center ${i?"text-gray-400":"text-gray-500"}`,children:[c.jsx("div",{className:`w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center ${i?"bg-gray-700":"bg-gray-100"}`,children:c.jsx(pt,{className:`w-8 h-8 ${i?"text-gray-500":"text-gray-400"}`})}),c.jsx("h3",{className:`text-sm font-medium mb-2 ${i?"text-gray-300":"text-gray-700"}`,children:"No threads yet"}),c.jsx("p",{className:"text-xs leading-relaxed",children:"Create your first thread to start a conversation with your agent"})]}):c.jsx("div",{className:"p-3 space-y-2",children:t.map(p=>c.jsxs("div",{onClick:()=>{x(p)},className:`group relative p-4 rounded-xl cursor-pointer transition-all duration-200 ${e?.id===p.id?i?"bg-blue-900/50 border-2 border-blue-600 shadow-lg":"bg-blue-50 border-2 border-blue-200 shadow-md":i?"hover:bg-gray-700 border-2 border-transparent hover:border-gray-600":"hover:bg-gray-50 border-2 border-transparent hover:border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-start justify-between",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center space-x-2 mb-2",children:[c.jsx("h3",{className:`text-sm font-semibold truncate ${e?.id===p.id?i?"text-blue-300":"text-blue-700":i?"text-white":"text-gray-900"}`,children:p.name}),p.messages.length>0&&c.jsx("span",{className:`px-2 py-0.5 text-xs rounded-full font-medium ${e?.id===p.id?i?"bg-blue-800 text-blue-200":"bg-blue-100 text-blue-700":i?"bg-gray-600 text-gray-300":"bg-gray-200 text-gray-600"}`,children:p.messages.length})]}),p.messages.length>0?c.jsx("p",{className:`text-xs line-clamp-2 mb-2 ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-400":"text-gray-500"}`,children:p.messages[p.messages.length-1].content}):c.jsx("p",{className:`text-xs italic mb-2 ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:"No messages yet"}),c.jsxs("div",{className:`flex items-center space-x-1 text-xs ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:[c.jsx(vn,{className:"w-3 h-3"}),c.jsx("span",{children:za(p.updatedAt,"MMM d, HH:mm")})]})]}),c.jsx("button",{onClick:y=>{v(p,y)},disabled:l!==null,className:`opacity-0 group-hover:opacity-100 p-1.5 rounded-lg transition-all duration-200 ${i?"hover:bg-red-900 text-gray-400 hover:text-red-300":"hover:bg-red-50 text-gray-400 hover:text-red-600"}`,title:"Delete thread",children:l===`delete:${p.id}`?"…":c.jsx(Mn,{className:"w-4 h-4"})})]}),e?.id===p.id&&c.jsx("div",{className:`absolute left-0 top-1/2 transform -translate-y-1/2 w-1 h-8 rounded-r-full ${i?"bg-blue-400":"bg-blue-600"}`})]},p.id))})}),t.length>0&&c.jsx("div",{className:`p-4 border-t ${i?"border-gray-700":"border-gray-200"}`,children:c.jsxs("div",{className:`text-xs text-center ${i?"text-gray-500":"text-gray-400"}`,children:[t.length," thread",t.length!==1?"s":""," •",t.reduce((p,y)=>p+y.messages.length,0)," total messages"]})})]})},Ga=({children:t})=>{const{darkMode:e}=me();return c.jsx("div",{className:`flex-1 flex flex-col min-h-0 overflow-hidden ${e?"bg-gray-900":"bg-gray-50"}`,style:{height:"100%"},children:t})},Ka=B.lazy(()=>G(async()=>{const{GraphView:t}=await import("./GraphView-CMqOwCTc.js");return{GraphView:t}},__vite__mapDeps([0,1,2,3,4])).then(({GraphView:t})=>({default:t}))),bt=B.lazy(()=>G(async()=>{const{ChatView:t}=await import("./ChatView-C7_FNxo9.js");return{ChatView:t}},__vite__mapDeps([5,1,2,3,4,6])).then(({ChatView:t})=>({default:t}))),Ja=B.lazy(()=>G(async()=>{const{DebugView:t}=await import("./DebugView-Bwa7sy_c.js");return{DebugView:t}},__vite__mapDeps([7,1,6,4])).then(({DebugView:t})=>({default:t}))),Xa=B.lazy(()=>G(async()=>{const{PipelinesView:t}=await import("./PipelinesView-DacXbEMw.js");return{PipelinesView:t}},__vite__mapDeps([8,1,2,3,4])).then(({PipelinesView:t})=>({default:t}))),Qa=B.lazy(()=>G(async()=>{const{BuilderView:t}=await import("./BuilderView-C296ULRo.js");return{BuilderView:t}},__vite__mapDeps([9,1,10,2,4])).then(({BuilderView:t})=>({default:t}))),Za=B.lazy(()=>G(async()=>{const{PluginsView:t}=await import("./PluginsView-COAn7Q5V.js");return{PluginsView:t}},__vite__mapDeps([11,1,2,3,4])).then(({PluginsView:t})=>({default:t}))),eo=B.lazy(()=>G(async()=>{const{IngestorsView:t}=await import("./IngestorsView-Cd56f61k.js");return{IngestorsView:t}},__vite__mapDeps([12,1,2,3,4])).then(({IngestorsView:t})=>({default:t}))),to=B.lazy(()=>G(async()=>{const{TasksView:t}=await import("./TasksView-DAoR0f0z.js");return{TasksView:t}},__vite__mapDeps([13,1,2,3,4])).then(({TasksView:t})=>({default:t}))),ro=B.lazy(()=>G(async()=>{const{ControlPlaneView:t}=await import("./ControlPlaneView-CC__Od52.js");return{ControlPlaneView:t}},__vite__mapDeps([14,1,4])).then(({ControlPlaneView:t})=>({default:t}))),no=B.lazy(()=>G(async()=>{const{EndpointsView:t}=await import("./EndpointsView-fCUdmgxr.js");return{EndpointsView:t}},__vite__mapDeps([15,1,2,3,4])).then(({EndpointsView:t})=>({default:t}))),ao=B.lazy(()=>G(async()=>{const{ConnectionsView:t}=await import("./ConnectionsView-Dvq88oBW.js");return{ConnectionsView:t}},__vite__mapDeps([16,1,3,4])).then(({ConnectionsView:t})=>({default:t})));class oo extends B.Component{constructor(){super(...arguments),this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidUpdate(e){e.view!==this.props.view&&this.state.failed&&this.setState({failed:!1})}render(){return this.state.failed?c.jsxs("div",{role:"alert",className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center ${this.props.darkMode?"text-gray-200":"text-gray-800"}`,children:[c.jsxs("div",{children:[c.jsx("h2",{className:"text-lg font-semibold",children:"Workspace could not load"}),c.jsx("p",{className:`mt-1 max-w-md text-sm ${this.props.darkMode?"text-gray-400":"text-gray-600"}`,children:"A Studio module could not be loaded. Reload to fetch the current deployment assets."})]}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-lg bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700",children:"Reload Studio"})]}):this.props.children}}const so=()=>{const{currentView:t,setCurrentView:e,sidebarCollapsed:r,setSidebarCollapsed:n,darkMode:a}=me();h.useEffect(()=>{t||e("chat")},[t,e]),h.useEffect(()=>{const i=window.matchMedia("(max-width: 767px)"),l=()=>{i.matches&&n(!0)};return l(),i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[n]),h.useEffect(()=>{const i=l=>{if(l.ctrlKey||l.metaKey)switch(l.key){case"1":l.preventDefault(),e("chat");break;case"2":l.preventDefault(),e("graph");break;case"3":l.preventDefault(),e("debug");break;case"4":l.preventDefault(),e("pipelines");break;case"9":l.preventDefault(),e("builder");break;case"5":l.preventDefault(),e("plugins");break;case"0":l.preventDefault(),e("ingestion");break;case"-":l.preventDefault(),e("tasks");break;case"6":l.preventDefault(),e("control");break;case"7":l.preventDefault(),e("endpoints");break;case"8":l.preventDefault(),e("connections");break}};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[e]);const o=()=>{switch(t){case"graph":return c.jsx(Ka,{});case"chat":return c.jsx(bt,{});case"debug":return c.jsx(Ja,{});case"pipelines":return c.jsx(Xa,{});case"builder":return c.jsx(Qa,{});case"plugins":return c.jsx(Za,{});case"ingestion":return c.jsx(eo,{});case"tasks":return c.jsx(to,{});case"control":return c.jsx(ro,{});case"endpoints":return c.jsx(no,{});case"connections":return c.jsx(ao,{});default:return c.jsx(bt,{})}},s=c.jsx("div",{className:`flex h-full items-center justify-center p-6 text-sm ${a?"text-gray-400":"text-gray-600"}`,role:"status",children:"Loading workspace…"});return c.jsxs("div",{className:`h-screen w-screen flex flex-col overflow-hidden ${a?"bg-gray-900":"bg-gray-50"}`,children:[c.jsx("div",{className:"flex-shrink-0",children:c.jsx(Un,{})}),c.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden",children:[!r&&c.jsx("button",{type:"button","aria-label":"Close thread sidebar",className:"absolute inset-0 z-30 bg-black/35 md:hidden",onClick:()=>n(!0)}),c.jsx("div",{className:`flex-shrink-0 transition-all duration-300 ease-in-out overflow-hidden ${r?"w-0":"absolute inset-y-0 left-0 z-40 w-80 shadow-2xl md:static md:w-72 md:shadow-none xl:w-80"}`,style:{height:"100%"},children:c.jsx(Ha,{})}),c.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:c.jsx(Ga,{children:c.jsx(oo,{darkMode:a,view:t,children:c.jsx(h.Suspense,{fallback:s,children:o()})})})})]})]})},io=8e3,J=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=(t,e)=>{const r=t?.[e];return J(r)?r:void 0},co=(t,e)=>{const r=U(t,e);if(r||!t)return{pathItem:r,boundPathParameters:new Set};const n=e.split("/");for(const a of Object.keys(t)){if(!a.includes("{"))continue;const o=a.split("/");if(o.length!==n.length)continue;const s=new Set,i=o.every((d,u)=>{const m=/^\{([^}/]+)\}$/.exec(d);return m?(s.add(m[1]),n[u].length>0):d===n[u]}),l=U(t,a);if(i&&l)return{pathItem:l,boundPathParameters:s}}return{pathItem:void 0,boundPathParameters:new Set}},lo=t=>t!==null&&typeof t.name=="string"&&(t.in==="query"||t.in==="header"||t.in==="path"),Ye=(t,e="")=>typeof t=="string"?t:e,uo=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[];class Xe{constructor(e,r,n=io){this.openApiDocument=null,this.baseUrl=e.replace(/\/$/,""),this.apiKey=r||null,this.timeoutMs=n,this.headers={"Content-Type":"application/json",...this.apiKey?{"X-Api-Key":this.apiKey,Authorization:`Bearer ${this.apiKey}`}:{}}}async request(e,r){const n=`${this.baseUrl}${e}`,a=new AbortController,o=setTimeout(()=>a.abort(),this.timeoutMs),s=r?.signal;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));try{const i=await fetch(n,{...r,signal:a.signal,headers:{...this.headers,...r?.headers}});if(!i.ok){const d=await i.text().catch(()=>"");throw new ye(i.status,i.statusText,d)}if(i.status===204||r?.method?.toUpperCase()==="HEAD")return null;const l=await i.text();return l?JSON.parse(l):null}catch(i){throw J(i)&&i.name==="AbortError"?new ye(408,"Request Timeout",`Timed out after ${this.timeoutMs}ms: ${e}`):i}finally{clearTimeout(o)}}async getServerInfo(){return this.request("/studio/info")}async getOperationContract(e,r="post"){if(!this.openApiDocument){const b=this.request("/openapi.json");this.openApiDocument=b,b.catch(()=>{this.openApiDocument===b&&(this.openApiDocument=null)})}const n=await this.openApiDocument,a=U(n,"components"),{pathItem:o,boundPathParameters:s}=co(U(n,"paths"),e),i=U(o,r.toLowerCase());if(!i)throw new ye(404,"Operation not found",`${r.toUpperCase()} ${e}`);const l=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/schemas/"))return{...b,...a?{components:a}:{}};const k=w.slice(21),S=U(U(a,"schemas"),k);return J(S)?{...S,...a?{components:a}:{}}:null},d=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/parameters/"))return b;const k=w.slice(24),S=U(U(a,"parameters"),k);return J(S)?S:null},u=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/requestBodies/"))return b;const k=w.slice(27),S=U(U(a,"requestBodies"),k);return J(S)?S:null},m=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/responses/"))return b;const k=w.slice(23),S=U(U(a,"responses"),k);return J(S)?S:null},f=u(i.requestBody),x=U(U(f??void 0,"content"),"application/json")?.schema,v=new Map;[...Array.isArray(o?.parameters)?o.parameters:[],...Array.isArray(i.parameters)?i.parameters:[]].map(d).filter(lo).filter(b=>!(b.in==="path"&&s.has(b.name))).forEach(b=>v.set(`${b.in}:${b.name}`,b));const p=Array.from(v.values()),y=l(x),g=!!(y&&(y.type==="object"||y.properties)),C="__body",T=f?.required===!0,j=U(y??void 0,"properties")?U(y??void 0,"properties"):{},N=uo(y?.required),A=new Set(Object.keys(j)),I={},q={},E=[];for(const b of p){const w=b.name;let k=w;if(A.has(k)){k=`${b.in}_${w}`;let O=2;for(;A.has(k);)k=`${b.in}_${w}_${O++}`}A.add(k);const S=l(b.schema)||{};q[k]={...S,title:Ye(S.title,w),description:[Ye(S.description),`${b.in} parameter`].filter(Boolean).join(" · ")},I[k]={name:w,in:b.in},(b.required===!0||b.in==="path")&&E.push(k)}const L=p.length?{type:"object",properties:q,...E.length?{required:E}:{},components:a}:null,D=y&&g?{...y,properties:{...j,...q},...N.length||E.length?{required:Array.from(new Set([...N,...E]))}:{}}:y&&L?{type:"object",properties:{[C]:{...y,title:Ye(y.title,"Request body")},...q},...T||E.length?{required:[...T?[C]:[],...E]}:{}}:y||L,M=U(i,"responses")||{},K=m(M[200]||M[201]||M[202]||Object.values(M)[0]),ne=U(U(K??void 0,"content"),"application/json")?.schema;return{input_schema:D,output_schema:l(ne),method:r.toUpperCase(),path:e,...Object.keys(I).length?{parameters:I}:{},...y&&!g&&L?{body_field:C}:{}}}async getEndpointContract(e){const r=Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.toUpperCase()):[],n=Array.from(new Set(["POST",...r])),a=`/api/v1/endpoints/${encodeURIComponent(e.name)}${e.path}`;let o;for(const s of n)try{return await this.getOperationContract(a,s)}catch(i){if(!(i instanceof ye&&i.status===404))throw i;o=i}throw o instanceof Error?o:new ye(404,"Operation not found",`${e.name} has no documented callable method`)}async listAgents(){const e=await this.request("/studio/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:e?.agents&&typeof e.agents=="object"?Object.entries(e.agents).map(([r,n])=>({name:n?.name||r,slug:n?.slug||r,description:n?.description||"",version:n?.version||"1.0.0",framework:n?.framework||"unknown",capabilities:n?.capabilities||[],has_graph:!!n?.has_graph,has_config:!!n?.has_config,has_prompts:!!n?.has_prompts})):[]}async getGraph(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/graph`)}async getSchemas(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/schemas`)}async getAgentConfig(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/config`)}normalizeThread(e,r){return{id:e?.id||e?.thread_id||"",user_id:e?.user_id||"default-user",agent_name:e?.agent_name||r||"",title:e?.title??null,metadata:e?.metadata||{},created_at:e?.created_at||e?.created||new Date().toISOString(),updated_at:e?.updated_at||e?.updated||e?.created_at||new Date().toISOString()}}normalizeMessage(e,r){return{id:String(e?.id||e?.message_id||`${r}-${e?.timestamp||Date.now()}`),thread_id:e?.thread_id||r,role:e?.role||"assistant",content:typeof e?.content=="string"?e.content:JSON.stringify(e?.content??e?.message??""),metadata:e?.metadata||{},timestamp:e?.timestamp||e?.created_at||new Date().toISOString()}}async createThread(e,r,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`,{method:"POST",body:JSON.stringify({user_id:r||"default-user",title:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async listThreads(e){const r=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`);return(Array.isArray(r)?r:Array.isArray(r?.threads)?r.threads:[]).map(a=>this.normalizeThread(a,e))}async getThread(e,r){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}`);return this.normalizeThread(n,e)}async deleteThread(e,r){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}`,{method:"DELETE"})}async getMessages(e,r){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/messages`);return(Array.isArray(n)?n:Array.isArray(n?.messages)?n.messages:[]).map(o=>this.normalizeMessage(o,r))}async forkThread(e,r,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/fork`,{method:"POST",body:JSON.stringify({message_index:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async createRun(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs`,{method:"POST",body:JSON.stringify(r)})}async listRuns(e,r=50){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs?limit=${r}`)}async getRun(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(r)}`)}async getState(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/state`)}async updateState(e,r,n){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/state`,{method:"POST",body:JSON.stringify({updates:n})})}async getHistory(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/history`)}async getPendingApprovals(e,r){return this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/pending`)}async approve(e,r,n){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({approval_id:n})})}async reject(e,r,n,a){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({approval_id:n,reason:a})})}async healthCheck(){try{return await this.request("/studio/info"),!0}catch{return!1}}async listPipelines(){const e=await this.request("/api/v1/pipelines");return(Array.isArray(e)?e:Array.isArray(e?.pipelines)?e.pipelines:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",steps:Array.isArray(n?.steps)?n.steps:[],agents_used:Array.isArray(n?.agents_used)?n.agents_used:[]}))}async runPipeline(e,r){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(r)})}async validatePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/validate`)}async validatePipelineDraft(e){return this.request("/api/v1/pipelines/validate-draft",{method:"POST",body:JSON.stringify(e)})}async savePipeline(e,r){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(r)})}async deletePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"DELETE"})}async listEndpoints(){const e=await this.request("/api/v1/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listIngestors(){const e=await this.request("/api/v1/ingestors");return(Array.isArray(e)?e:Array.isArray(e?.ingestors)?e.ingestors:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",ready:!!n?.ready,input_schema:n?.input_schema||""}))}async runIngestor(e,r){return this.request(`/api/v1/ingestion/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(r)})}async listTasks(e={}){const r=new URLSearchParams;return Object.entries(e).forEach(([n,a])=>{a!==void 0&&a!==""&&r.set(n,String(a))}),this.request(`/api/v1/tasks${r.size?`?${r}`:""}`)}async submitTask(e){return this.request("/api/v1/tasks",{method:"POST",body:JSON.stringify(e)})}async getTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`)}async getTaskResult(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/result`)}async cancelTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/cancel`,{method:"POST"})}async deleteTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`,{method:"DELETE"})}async getPipelineConfig(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/config`)}async visualizePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/visualize`)}async listPlugins(){const e=await this.request("/api/v1/plugins");return(Array.isArray(e)?e:Array.isArray(e?.plugins)?e.plugins:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",is_loaded:!!n?.is_loaded}))}async getPluginModelCard(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/model_card`)}async reloadPlugin(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/reload`,{method:"POST"})}async runPluginPredict(e,r){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/predict`,{method:"POST",body:JSON.stringify(r)})}async callEndpoint(e,r,n,a="POST",o){const s=a.toUpperCase();let i=`/api/v1/endpoints/${encodeURIComponent(e)}${r}`;const l=new URLSearchParams,d={},u={},m=o?.parameters||{},f=o?.body_field,x=n&&typeof n=="object"&&!Array.isArray(n)?n:null,v=f&&x?x[f]:n;for(const[y,g]of Object.entries(x||{})){if(y===f)continue;const C=m[y],j=C?C.in:s==="GET"||s==="HEAD"?"query":"body",N=C?.name||y;if(j==="body"){d[y]=g;continue}if(!(g==null||g==="")){if(j==="path"){i=i.replace(`{${N}}`,encodeURIComponent(String(g)));continue}if(j==="header"){u[N]=Array.isArray(g)?g.map(A=>typeof A=="string"?A:JSON.stringify(A)).join(", "):typeof g=="object"?JSON.stringify(g):String(g);continue}Array.isArray(g)?g.forEach(A=>l.append(N,typeof A=="string"?A:JSON.stringify(A))):l.set(N,typeof g=="object"?JSON.stringify(g):String(g))}}const p=l.size?`?${l.toString()}`:"";return s==="GET"||s==="HEAD"?this.request(`${i}${p}`,{method:s,headers:u}):this.request(`${i}${p}`,{method:s,headers:u,body:JSON.stringify(f||!x?v:d)})}async getControlInfo(){return this.request("/api/v1/control")}async listControlAgents(){const e=await this.request("/api/v1/control/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]}async getControlAgent(e){return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}`)}async listControlEndpoints(){const e=await this.request("/api/v1/control/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listControlConnections(){const e=await this.request("/api/v1/control/connections");return(Array.isArray(e)?e:Array.isArray(e?.connections)?e.connections:[]).map(n=>({scope:n?.scope||"",connections:n?.connections||{}}))}async probeControlConnection(e,r){return this.request(`/api/v1/control/connections/${encodeURIComponent(e)}/${encodeURIComponent(r)}`)}async getControlMetricsSummary(){return this.request("/api/v1/control/metrics/summary")}async getControlHealth(){return this.request("/api/v1/control/health")}async getControlConfig(){return this.request("/api/v1/control/config")}async setAgentEnabled(e,r,n){const a=r?"enable":"disable";return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}/${a}`,{method:"POST",headers:n?{"X-Control-Token":n}:{}})}async setMaintenance(e,r){return this.request("/api/v1/control/maintenance",{method:"POST",headers:r?{"X-Control-Token":r}:{},body:JSON.stringify({enabled:e})})}getStreamUrl(e){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/runs/stream`}getResumeStreamUrl(e,r){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/resume`}getHeaders(){return{...this.headers}}}class ye extends Error{constructor(e,r,n){super(`API Error ${e}: ${r}`),this.status=e,this.statusText=r,this.body=n,this.name="ApiError"}}const mo="agentomatic-studio:lastUrl",Ne="agentomatic-studio:lastApiKey",vt="agentomatic-studio:lastApiKey",fo=()=>{try{const t=sessionStorage.getItem(Ne);if(t)return t;const e=localStorage.getItem(vt);return e?(sessionStorage.setItem(Ne,e),localStorage.removeItem(vt),e):""}catch{return""}},po={graph:{light:"bg-blue-100 text-blue-700 border-blue-200",dark:"bg-blue-900/40 text-blue-300 border-blue-700"},streaming:{light:"bg-green-100 text-green-700 border-green-200",dark:"bg-green-900/40 text-green-300 border-green-700"},hitl:{light:"bg-amber-100 text-amber-700 border-amber-200",dark:"bg-amber-900/40 text-amber-300 border-amber-700"},checkpoints:{light:"bg-purple-100 text-purple-700 border-purple-200",dark:"bg-purple-900/40 text-purple-300 border-purple-700"}},ho={light:"bg-gray-100 text-gray-700 border-gray-200",dark:"bg-gray-700 text-gray-300 border-gray-600"},go=()=>{const t=Mt(),{setConfig:e,setIsConnected:r,setIsLoading:n,addAssistant:a,clearAssistants:o,fetchGraphData:s,refreshThreads:i,setSelectedAgent:l,darkMode:d}=me(),[u,m]=h.useState(()=>{const S=fo();return{apiUrl:Ae(),agentId:"",apiKey:S||""}}),[f,x]=h.useState({status:"idle",message:"Enter server URL to check connectivity"}),[v,p]=h.useState([]),[y,g]=h.useState(!1),[C,T]=h.useState(!1),[j,N]=h.useState(!1),[,A]=h.useState(null),[I,q]=h.useState({}),E=h.useRef(0),L=h.useCallback((S,O)=>{try{localStorage.setItem(mo,S),O?sessionStorage.setItem(Ne,O):sessionStorage.removeItem(Ne)}catch{}},[]),D=h.useCallback(S=>{const O=po[S]||ho,F=d?O.dark:O.light;return c.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border leading-tight ${F}`,children:S},S)},[d]),M=h.useCallback(async S=>{const O=++E.current,F=mt(S);if(!F||!F.startsWith("http")){x({status:"idle",message:"Enter a valid server URL"}),p([]),q({}),N(!1),g(!1);return}x({status:"checking",message:"Checking server connectivity..."}),p([]),q({}),N(!1),g(!0),m(z=>z.agentId?{...z,agentId:""}:z);try{const z=new Xe(F,u.apiKey||void 0),H=await z.getServerInfo();if(O!==E.current)return;A(H);const ae=await z.listAgents();if(O!==E.current)return;if(ae.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ve=ae.map(_=>({id:_.slug||_.name,name:_.name,description:_.description||`${_.framework} agent`,config:{capabilities:_.capabilities,has_graph:_.has_graph,version:_.version}})),oe={};ae.forEach(_=>{oe[_.slug||_.name]=_.capabilities||[]}),q(oe),p(ve),m(_=>({..._,agentId:ve[0].id})),x({status:"success",message:`Connected to ${H.platform_title||"Agentomatic"} v${H.version} — ${H.agent_count} agent(s)`,lastChecked:new Date}),setTimeout(()=>N(!0),300)}catch(z){if(O!==E.current)return;const H=z?.status===401||z?.status===403?"Studio authorization failed. Provide a valid API key and retry.":`Studio API is unavailable: ${z?.message||"start the platform with Studio enabled."}`;x({status:"error",message:H,lastChecked:new Date}),N(!1)}finally{O===E.current&&g(!1)}},[u.apiKey]);h.useEffect(()=>{const S=setTimeout(()=>{u.apiUrl&&M(u.apiUrl)},1e3);return()=>clearTimeout(S)},[u.apiUrl,M]);const K=async S=>{if(S.preventDefault(),f.status!=="success"){Se.error("Please ensure the server connection is healthy before connecting");return}if(!u.agentId){Se.error("Please select a live agent to use");return}T(!0),n(!0);try{const O=mt(u.apiUrl),F=new Xe(O,u.apiKey||void 0),[z,H]=await Promise.all([F.getServerInfo(),F.listAgents()]);if(H.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ae=H.map(_=>({id:_.slug||_.name,name:_.name,description:_.description||"",type:"chat",model:_.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:_.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:_.capabilities,apiName:_.name,slug:_.slug},graph_id:_.slug||_.name}));Je(F),o(),e({...u,apiUrl:O}),ae.forEach(_=>a(_)),r(!0);const ve=u.agentId||H[0]?.slug||H[0]?.name,oe=ae.find(_=>_.id===ve)||ae[0];oe&&(l(oe),s(oe.id).catch(_=>{console.warn("Background graph load failed:",_)}),i(oe.id).catch(()=>{})),L(O,u.apiKey||""),Se.success(`Connected to ${z.platform_title||"Agentomatic"} v${z.version}!`),setTimeout(()=>t("/studio"),500)}catch(O){console.error("Connection error:",O),Se.error("Failed to connect. Please check your configuration.")}finally{T(!1),n(!1)}},ne=(S,O)=>{m(F=>({...F,[S]:O}))},b=()=>{switch(f.status){case"checking":return c.jsxs("svg",{className:"w-5 h-5 animate-spin text-blue-500",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]});case"success":return c.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})});case"error":return c.jsx("svg",{className:"w-5 h-5 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})});default:return c.jsx("svg",{className:"w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}},w=()=>{switch(f.status){case"checking":return"text-blue-600 bg-blue-50 border-blue-200";case"success":return"text-green-600 bg-green-50 border-green-200";case"error":return"text-red-600 bg-red-50 border-red-200";default:return"text-gray-600 bg-gray-50 border-gray-200"}},k=()=>{switch(f.status){case"checking":return"text-blue-400 bg-blue-900/30 border-blue-700";case"success":return"text-green-400 bg-green-900/30 border-green-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return c.jsxs("div",{className:`min-h-screen w-full flex ${d?"bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900":"bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50"} relative overflow-hidden`,children:[c.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[c.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),c.jsx("div",{className:`absolute top-1/4 left-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse ${d?"bg-blue-600":"bg-blue-400"}`}),c.jsx("div",{className:`absolute bottom-1/4 right-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse delay-1000 ${d?"bg-purple-600":"bg-purple-400"}`}),c.jsx("div",{className:`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 rounded-full blur-3xl opacity-10 animate-pulse delay-500 ${d?"bg-indigo-600":"bg-indigo-400"}`})]}),c.jsxs("div",{className:"relative z-10 w-full flex",children:[c.jsx("div",{className:"hidden lg:flex lg:w-1/2 xl:w-2/5 flex-col justify-center items-center p-12 relative",children:c.jsxs("div",{className:"max-w-md text-center animate-slide-in-left",children:[c.jsx("div",{className:`w-32 h-32 rounded-3xl flex items-center justify-center mx-auto mb-8 ${d?"bg-gradient-to-br from-blue-600 via-purple-600 to-indigo-600":"bg-gradient-to-br from-blue-500 via-indigo-500 to-purple-600"} shadow-2xl animate-pulse-glow`,children:c.jsx("svg",{className:"w-16 h-16 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),c.jsxs("h1",{className:`text-5xl font-bold mb-6 ${d?"text-white":"text-gray-900"}`,children:["Agentomatic",c.jsx("span",{className:`block text-4xl ${d?"text-violet-400":"text-violet-600"}`,children:"Studio"})]}),c.jsx("p",{className:`text-xl leading-relaxed mb-8 ${d?"text-gray-300":"text-gray-600"}`,children:"Build, debug, and deploy intelligent agent workflows with visual graph execution"}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-green-400":"bg-green-500"} animate-pulse`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Real-time graph execution"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-blue-400":"bg-blue-500"} animate-pulse delay-300`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Interactive debugging tools"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-purple-400":"bg-purple-500"} animate-pulse delay-700`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Multi-agent orchestration"})]})]})]})}),c.jsx("div",{className:"w-full lg:w-1/2 xl:w-3/5 flex items-center justify-center p-6 lg:p-12",children:c.jsxs("div",{className:`w-full max-w-md rounded-3xl shadow-2xl backdrop-blur-md border ${d?"bg-gray-800/80 border-gray-700":"bg-white/80 border-gray-200"} animate-slide-in-right`,children:[c.jsxs("div",{className:"p-8 text-center",children:[c.jsx("div",{className:"lg:hidden mb-6",children:c.jsx("div",{className:`w-16 h-16 rounded-2xl flex items-center justify-center mx-auto ${d?"bg-gradient-to-br from-blue-600 to-purple-600":"bg-gradient-to-br from-blue-500 to-indigo-600"} shadow-lg`,children:c.jsx("svg",{className:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})})}),c.jsx("h2",{className:`text-2xl lg:text-3xl font-bold mb-3 ${d?"text-white":"text-gray-900"}`,children:"Get Started"}),c.jsx("p",{className:`text-lg ${d?"text-gray-300":"text-gray-600"}`,children:"Connect to your authenticated Agentomatic server"})]}),c.jsxs("div",{className:"px-8 pb-8",children:[c.jsxs("form",{onSubmit:K,className:"space-y-6",children:[c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsx("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:"Server URL"}),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:"url",value:u.apiUrl,onChange:S=>ne("apiUrl",S.target.value),placeholder:Ae(),className:`w-full px-4 py-4 pr-14 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`,required:!0}),c.jsx("div",{className:"absolute right-4 top-1/2 transform -translate-y-1/2",children:b()})]}),c.jsxs("div",{className:`mt-3 p-4 rounded-xl border text-sm flex items-center space-x-3 transition-all duration-300 ${d?k():w()}`,children:[b(),c.jsxs("div",{className:"flex-1",children:[c.jsx("span",{className:"font-medium",children:f.message}),f.lastChecked&&c.jsxs("div",{className:"text-xs opacity-75 mt-1",children:["Last checked: ",f.lastChecked.toLocaleTimeString()]})]})]})]}),c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsxs("label",{htmlFor:"agentomatic-api-key",className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["API key ",c.jsx("span",{className:"font-normal opacity-70",children:"(optional)"})]}),c.jsx("input",{id:"agentomatic-api-key",type:"password",value:u.apiKey||"",onChange:S=>ne("apiKey",S.target.value),placeholder:"Required when server authentication is enabled",autoComplete:"off",spellCheck:!1,className:`w-full px-4 py-4 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`}),c.jsx("p",{className:`mt-2 text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Kept only for this tab session after a successful connection; closing the tab removes it."})]}),j&&c.jsxs("div",{className:"animate-fade-in-up stagger-2",children:[c.jsxs("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["Available agents",y&&c.jsxs("span",{className:"ml-2 text-xs text-blue-500",children:[c.jsxs("svg",{className:"inline w-3 h-3 animate-spin mr-1",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Loading..."]})]}),v.length>0?c.jsx("div",{className:"space-y-3 max-h-48 overflow-y-auto custom-scrollbar",children:v.map((S,O)=>c.jsxs("label",{className:`flex items-center p-4 rounded-xl border cursor-pointer transition-all duration-300 transform hover:scale-105 ${u.agentId===S.id?d?"bg-blue-900/40 border-blue-500 text-blue-400 shadow-lg":"bg-blue-50 border-blue-500 text-blue-700 shadow-lg":d?"bg-gray-700/50 border-gray-600 hover:bg-gray-600/50 text-gray-200":"bg-white/50 border-gray-200 hover:bg-gray-50 text-gray-700"} animate-slide-in-right`,style:{animationDelay:`${O*100}ms`},children:[c.jsx("input",{type:"radio",name:"agentId",value:S.id,checked:u.agentId===S.id,onChange:F=>ne("agentId",F.target.value),className:"sr-only"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"font-semibold",children:S.name}),I[S.id]?.length>0&&c.jsx("span",{className:"flex flex-wrap gap-1",children:I[S.id].map(D)})]}),S.description&&c.jsx("div",{className:`text-sm mt-1 ${u.agentId===S.id?"opacity-90":d?"text-gray-400":"text-gray-500"}`,children:S.description})]}),c.jsx("div",{className:`w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all duration-200 ${u.agentId===S.id?"border-current scale-110":d?"border-gray-500":"border-gray-300"}`,children:u.agentId===S.id&&c.jsx("div",{className:"w-3 h-3 rounded-full bg-current animate-pulse"})})]},S.id))}):c.jsx("div",{className:`p-6 rounded-xl border text-center ${d?"bg-gray-700/50 border-gray-600 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:y?c.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Loading live agents..."})]}):"No live agents available. Check the Studio API and server connection."})]}),c.jsx("div",{className:"space-y-4 animate-fade-in-up stagger-3",children:c.jsx("button",{type:"submit",disabled:f.status!=="success"||!u.agentId||C,className:`w-full py-4 px-6 rounded-2xl font-semibold text-white transition-all duration-300 transform ${f.status==="success"&&u.agentId&&!C?"bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 hover:scale-105 shadow-lg hover:shadow-2xl":"bg-gray-400 cursor-not-allowed opacity-50"}`,children:C?c.jsxs("div",{className:"flex items-center justify-center space-x-3",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Connecting..."})]}):"Connect to Server"})})]}),c.jsx("div",{className:`mt-8 pt-6 border-t ${d?"border-gray-600":"border-gray-200"} animate-fade-in-up stagger-4`,children:c.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-green-400":"text-green-600"}`,children:"🚀"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Authenticated server"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Verify before entering Studio"})]}),c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-blue-400":"text-blue-600"}`,children:"🔗"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Live execution"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Uses deployed resource contracts"})]})]})})]})]})})]})]})},wt="agentomatic-studio:lastApiKey",Ct="agentomatic-studio:lastApiKey",yo=()=>{try{const t=sessionStorage.getItem(wt);if(t)return t;const e=localStorage.getItem(Ct);return e?(sessionStorage.setItem(wt,e),localStorage.removeItem(Ct),e):""}catch{return""}},xo=t=>({id:t.slug||t.name,name:t.name,description:t.description||"",type:"chat",model:t.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:t.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:t.capabilities,apiName:t.name,slug:t.slug},graph_id:t.slug||t.name,metadata:{version:t.version,framework:t.framework,capabilities:t.capabilities,has_graph:t.has_graph,has_config:t.has_config}});function bo(){const{isConnected:t,darkMode:e,setConfig:r,setIsConnected:n,setConnectionStatus:a,clearAssistants:o,addAssistant:s,setSelectedAssistant:i,fetchGraphData:l,refreshThreads:d}=me(),[u,m]=h.useState(!1),f="/studio/ui/".replace(/\/$/,"");h.useEffect(()=>{e?(document.documentElement.setAttribute("data-theme","dark"),document.documentElement.classList.add("dark")):(document.documentElement.removeAttribute("data-theme"),document.documentElement.classList.remove("dark"))},[e]),h.useEffect(()=>{let v=!1;return(async()=>{const y=Ae();let g="";try{g=yo()}catch{}try{const C=new Xe(y,g||void 0);await C.getServerInfo();const T=await C.listAgents();if(v)return;const j=T.map(xo);Je(C);const N=j[0];r({apiUrl:y,apiKey:g||void 0,agentId:N?.id}),o(),j.forEach(s),N&&(i(N),l(N.id),d(N.id).catch(()=>{})),a("connected"),n(!0)}catch{v||(Je(null),a("disconnected"),n(!1))}finally{v||m(!0)}})(),()=>{v=!0}},[s,o,r,a,n,i,l,d]);const x=u?t?c.jsx(so,{}):c.jsx(et,{to:"/setup",replace:!0}):c.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-gray-500",children:"Restoring Studio session…"});return c.jsxs(It,{basename:f,children:[c.jsx("div",{className:`App ${e?"dark":""}`,children:c.jsxs(Lt,{children:[c.jsx(Re,{path:"/setup",element:c.jsx(go,{})}),c.jsx(Re,{path:"/studio",element:x}),c.jsx(Re,{path:"/",element:c.jsx(et,{to:t&&u?"/studio":"/setup",replace:!0})})]})}),c.jsx(Rr,{position:"top-right",toastOptions:{duration:4e3,style:{background:e?"#374151":"#ffffff",color:e?"#f9fafb":"#111827",border:e?"1px solid #4b5563":"1px solid #e5e7eb"},success:{duration:3e3,iconTheme:{primary:"#10b981",secondary:e?"#374151":"#ffffff"}},error:{duration:5e3,iconTheme:{primary:"#ef4444",secondary:e?"#374151":"#ffffff"}}}})]})}const vo=Bt.createRoot(document.getElementById("root"));vo.render(c.jsx(B.StrictMode,{children:c.jsx(bo,{})}));export{Xe as A,jn as F,Se as V,Nt as a,Ro as b,Do as c,No as d,tn as e,za as f,Mn as g,ko as h,_o as i,c as j,Ao as k,To as l,$o as m,Y as n,jo as o,So as p,Oo as q,Eo as s,me as u}; +Failed to execute: ${v instanceof Error?v.message:"Unknown error"}`,timestamp:new Date};p.addMessageToThread(p.selectedThread.id,y)}}})().catch(v=>{console.error("Failed to execute Agentomatic agent:",v),e().stopExecution()})},addInterrupt:r=>t(n=>(R.emit({type:"INTERRUPT_RECEIVED",data:r}),{activeInterrupts:[...n.activeInterrupts,r]})),resolveInterrupt:(r,n)=>t(a=>(R.emit({type:"INTERRUPT_RESOLVED",data:{interruptId:r,resolution:n}}),{activeInterrupts:a.activeInterrupts.map(o=>o.id===r?{...o,status:n==="approved"?"approved":"rejected",resolvedAt:new Date}:o)})),clearInterrupts:()=>t({activeInterrupts:[]}),addSubAgentResult:r=>t(n=>(R.emit({type:"SUB_AGENT_COMPLETED",data:r}),{subAgentResults:[...n.subAgentResults,r]})),clearSubAgentResults:()=>t({subAgentResults:[]}),reset:()=>t({...We,selectedThread:void 0,selectedAgent:void 0,selectedAssistant:void 0,threads:[],agents:[],assistants:[],runs:[],currentRun:void 0,executionContext:Be,executionContexts:new Map,activeInterrupts:[],subAgentResults:[],agentSchemas:{},schemasLoading:!1,isStreaming:!1,streamingMessage:"",activeAbortController:null})}),{name:"studio-store"})),Ro=(t,e,r=[])=>{const n=h.useRef(e);n.current=e,h.useEffect(()=>R.subscribe(t,o=>{n.current(o)}),[t,...r])},Do=(t,e=[])=>{const r=h.useRef(t);r.current=t,h.useEffect(()=>R.subscribeAll(a=>{r.current(a)}),e)};function cn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"}))}const dn=h.forwardRef(cn);function ln({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"}))}const un=h.forwardRef(ln);function mn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 0 1-.825-.242m9.345-8.334a2.126 2.126 0 0 0-.476-.095 48.64 48.64 0 0 0-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0 0 11.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155"}))}const fn=h.forwardRef(mn);function pn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"}))}const pt=h.forwardRef(pn);function hn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m19.5 8.25-7.5 7.5-7.5-7.5"}))}const gn=h.forwardRef(hn);function yn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 0v3.75m-16.5-3.75v3.75m16.5 0v3.75C20.25 16.153 16.556 18 12 18s-8.25-1.847-8.25-4.125v-3.75m16.5 0c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125"}))}const xn=h.forwardRef(yn);function bn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const vn=h.forwardRef(bn);function wn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4.5 12a7.5 7.5 0 0 0 15 0m-15 0a7.5 7.5 0 1 1 15 0m-15 0H3m16.5 0H21m-1.5 0H12m-8.457 3.077 1.41-.513m14.095-5.13 1.41-.513M5.106 17.785l1.15-.964m11.49-9.642 1.149-.964M7.501 19.795l.75-1.3m7.5-12.99.75-1.3m-6.063 16.658.26-1.477m2.605-14.772.26-1.477m0 17.726-.26-1.477M10.698 4.614l-.26-1.477M16.5 19.794l-.75-1.299M7.5 4.205 12 12m6.894 5.785-1.149-.964M6.256 7.178l-1.15-.964m15.352 8.864-1.41-.513M4.954 9.435l-1.41-.514M12.002 12l-3.75 6.495"}))}const pe=h.forwardRef(wn);function Cn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m6.75 7.5 3 2.25-3 2.25m4.5 0h3m-9 8.25h13.5A2.25 2.25 0 0 0 21 18V6a2.25 2.25 0 0 0-2.25-2.25H5.25A2.25 2.25 0 0 0 3 6v12a2.25 2.25 0 0 0 2.25 2.25Z"}))}const Fe=h.forwardRef(Cn);function Sn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418"}))}const En=h.forwardRef(Sn);function kn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z"}))}const Tn=h.forwardRef(kn);function An({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4.5v15m7.5-7.5h-15"}))}const jn=h.forwardRef(An);function _n({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 0 1 0 3.75H5.625a1.875 1.875 0 0 1 0-3.75Z"}))}const Nn=h.forwardRef(_n);function $n({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"}))}const On=h.forwardRef($n);function Rn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"}))}const Dn=h.forwardRef(Rn);function Pn({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"}))}const Mn=h.forwardRef(Pn);function In({title:t,titleId:e,...r},n){return h.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":e},r),t?h.createElement("title",{id:e},t):null,h.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const Ln=h.forwardRef(In),Un=()=>{const{assistants:t,selectedAssistant:e,setSelectedAssistant:r,currentView:n,setCurrentView:a,darkMode:o,setDarkMode:s,sidebarCollapsed:i,setSidebarCollapsed:l,config:d,fetchGraphData:u,refreshThreads:m,connectionStatus:f,retryAttempts:x,maxRetryAttempts:v,attemptReconnection:p}=me(),[y,g]=h.useState(!1),C=h.useRef(null),T=h.useRef(null),[j,N]=h.useState({top:0,left:0,width:0});h.useEffect(()=>{const E=L=>{C.current&&!C.current.contains(L.target)&&T.current&&!T.current.contains(L.target)&&g(!1)};if(y)return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[y]),h.useEffect(()=>{if(y&&T.current){const E=()=>{const M=T.current.getBoundingClientRect();N({top:M.bottom+8,left:M.left,width:M.width})};E();const L=()=>E(),D=()=>E();return window.addEventListener("scroll",L,!0),window.addEventListener("resize",D),()=>{window.removeEventListener("scroll",L,!0),window.removeEventListener("resize",D)}}},[y]);const A=async E=>{r(E),g(!1);try{await u(E.id),await m(E.id)}catch(L){console.error("Failed to fetch graph data:",L)}},I=E=>{switch(E){case"langgraph":return o?"bg-emerald-900 text-emerald-300":"bg-emerald-100 text-emerald-700";case"deepagent":return o?"bg-purple-900 text-purple-300":"bg-purple-100 text-purple-700";case"langchain":return o?"bg-blue-900 text-blue-300":"bg-blue-100 text-blue-700";default:return o?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}},q=[{key:"graph",label:"Graph",icon:Fe},{key:"chat",label:"Chat",icon:fn},{key:"debug",label:"Debug",icon:pe},{key:"pipelines",label:"Pipelines",icon:Fe},{key:"builder",label:"Builder",icon:On},{key:"plugins",label:"Plugins",icon:pe},{key:"ingestion",label:"Ingestors",icon:Fe},{key:"tasks",label:"Tasks",icon:Nn},{key:"control",label:"Control",icon:dn},{key:"endpoints",label:"Endpoints",icon:En},{key:"connections",label:"Connections",icon:xn}];return c.jsxs("header",{className:`flex min-h-16 items-center justify-between gap-2 px-3 py-2 sm:px-6 border-b backdrop-blur-sm transition-colors duration-300 ${o?"bg-gray-800/95 border-gray-700 text-white":"bg-white/95 border-gray-200 text-gray-900"}`,children:[c.jsxs("div",{className:"flex min-w-0 items-center space-x-2 sm:space-x-4",children:[c.jsx("button",{onClick:()=>l(!i),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-gray-300":"hover:bg-gray-100 text-gray-600"}`,title:i?"Show Sidebar":"Hide Sidebar",children:i?c.jsx(un,{className:"w-5 h-5"}):c.jsx(Ln,{className:"w-5 h-5"})}),c.jsxs("div",{className:"flex items-center space-x-2 sm:space-x-3",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-violet-600",children:c.jsx("span",{className:"text-white font-bold text-sm",children:"AS"})}),c.jsxs("div",{className:"hidden sm:block",children:[c.jsx("h1",{className:"text-lg font-semibold",children:"Agentomatic Studio"}),c.jsx("p",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:f==="connected"?"Connected":"Reconnecting…"})]})]}),c.jsx("nav",{className:`hidden 2xl:flex min-w-0 items-center space-x-1 rounded-xl p-1 ml-3 xl:ml-6 overflow-x-auto ${o?"bg-gray-700":"bg-gray-100"}`,children:q.map(({key:E,label:L,icon:D})=>c.jsxs("button",{onClick:()=>a(E),className:`flex shrink-0 items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${n===E?o?"bg-blue-600 text-white shadow-lg transform scale-105":"bg-white text-blue-600 shadow-md transform scale-105":o?"text-gray-300 hover:text-white hover:bg-gray-600":"text-gray-600 hover:text-gray-900 hover:bg-white/50"}`,children:[c.jsx(D,{className:"w-4 h-4 mr-2"}),L]},E))}),c.jsx("select",{value:n,onChange:E=>a(E.target.value),"aria-label":"Select Studio view",className:`max-w-28 rounded-lg border px-2 py-2 text-sm font-medium sm:max-w-36 md:max-w-44 2xl:hidden ${o?"border-gray-600 bg-gray-700 text-white":"border-gray-300 bg-white text-gray-900"}`,children:q.map(({key:E,label:L})=>c.jsx("option",{value:E,children:L},E))})]}),c.jsx("div",{className:"flex flex-1 justify-end sm:justify-center",children:c.jsxs("div",{className:"relative",ref:C,children:[c.jsxs("button",{onClick:()=>g(!y),className:`flex max-w-[13rem] items-center space-x-2 px-2 py-2 sm:max-w-none sm:space-x-3 sm:px-4 rounded-xl border transition-all duration-200 ${o?"bg-gray-700 border-gray-600 text-white hover:bg-gray-600":"bg-white border-gray-300 text-gray-900 hover:bg-gray-50"}`,ref:T,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${o?"bg-blue-600":"bg-blue-100"}`,children:c.jsx(pe,{className:`w-4 h-4 ${o?"text-white":"text-blue-600"}`})}),c.jsxs("div",{className:"min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx("span",{className:"truncate text-sm font-medium",children:e?.name||"Select Agent"}),e?.metadata?.framework&&c.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full font-medium ${I(e.metadata.framework)}`,children:e.metadata.framework})]}),c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:e?.description||"No agent selected"})]}),c.jsx(gn,{className:`w-4 h-4 transition-transform ${y?"rotate-180":""}`})]}),y&&Pt.createPortal(c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fixed inset-0 z-[999998] bg-black/10",onClick:()=>g(!1)}),c.jsx("div",{ref:C,className:`fixed rounded-xl border shadow-2xl z-[999999] ${o?"bg-gray-800 border-gray-600":"bg-white border-gray-200"}`,style:{top:j.top,left:j.left,width:Math.max(j.width,320),maxHeight:"400px"},children:c.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:t.length===0?c.jsxs("div",{className:`p-4 text-center ${o?"text-gray-400":"text-gray-500"}`,children:[c.jsx(pe,{className:`w-8 h-8 mx-auto mb-2 ${o?"text-gray-600":"text-gray-300"}`}),c.jsx("p",{className:"text-sm",children:"No agents available"}),c.jsx("p",{className:"text-xs mt-1",children:"Check your server connection"})]}):t.map(E=>c.jsxs("button",{onClick:()=>A(E),className:`w-full flex items-center space-x-3 p-3 rounded-lg transition-colors ${e?.id===E.id?o?"bg-blue-900 border border-blue-700":"bg-blue-50 border border-blue-200":o?"hover:bg-gray-700":"hover:bg-gray-50"}`,children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${e?.id===E.id?"bg-blue-600":o?"bg-gray-600":"bg-gray-200"}`,children:c.jsx(pe,{className:`w-4 h-4 ${e?.id===E.id?"text-white":o?"text-gray-300":"text-gray-600"}`})}),c.jsxs("div",{className:"flex-1 text-left",children:[c.jsx("div",{className:`text-sm font-medium ${o?"text-white":"text-gray-900"}`,children:E.name}),E.description&&c.jsx("div",{className:`text-xs ${o?"text-gray-400":"text-gray-500"}`,children:E.description}),c.jsxs("div",{className:`text-xs ${o?"text-gray-500":"text-gray-400"}`,children:["Graph: ",E.graph_id]})]}),e?.id===E.id&&c.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full"})]},E.id))})})]}),document.body)]})}),c.jsxs("div",{className:"flex items-center space-x-1.5 sm:space-x-3",children:[c.jsxs("div",{className:"hidden items-center space-x-2 xl:flex",children:[c.jsx("div",{className:`w-2 h-2 rounded-full ${f==="connected"?"bg-green-500 animate-pulse":f==="reconnecting"?"bg-yellow-500 animate-spin":f==="failed"?"bg-red-500":"bg-gray-500"}`}),c.jsx("span",{className:`text-sm ${o?"text-gray-300":"text-gray-600"}`,children:f==="connected"?c.jsx("span",{title:d.apiUrl,children:d.apiUrl.replace(/^https?:\/\//,"").slice(0,25)}):f==="reconnecting"?`Reconnecting (${x}/${v})`:f==="failed"?"Connection Failed":"Disconnected"}),(f==="disconnected"||f==="failed")&&c.jsx("button",{onClick:p,className:`px-2 py-1 text-xs rounded transition-colors ${o?"bg-blue-600 text-white hover:bg-blue-700":"bg-blue-500 text-white hover:bg-blue-600"}`,title:"Retry Connection",children:"Retry"})]}),c.jsx("button",{onClick:()=>s(!o),className:`p-2 rounded-lg transition-colors ${o?"hover:bg-gray-700 text-yellow-400":"hover:bg-gray-100 text-gray-600"}`,title:o?"Switch to Light Mode":"Switch to Dark Mode",children:o?c.jsx(Dn,{className:"w-5 h-5"}):c.jsx(Tn,{className:"w-5 h-5"})}),c.jsx("div",{className:`hidden text-xs px-2 py-1 rounded 2xl:block ${o?"bg-gray-700 text-gray-400":"bg-gray-100 text-gray-500"}`,children:"⌘1-9 to switch views"})]})]})};function ce(t){if(t===null||t===!0||t===!1)return NaN;var e=Number(t);return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}function W(t,e){if(e.length1?"s":"")+" required, but only "+e.length+" present")}function X(t){W(1,arguments);var e=Object.prototype.toString.call(t);return t instanceof Date||Et(t)==="object"&&e==="[object Date]"?new Date(t.getTime()):typeof t=="number"||e==="[object Number]"?new Date(t):((typeof t=="string"||e==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function qn(t,e){W(2,arguments);var r=X(t).getTime(),n=ce(e);return new Date(r+n)}var Vn={};function Oe(){return Vn}function Wn(t){var e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),t.getTime()-e.getTime()}function Bn(t){return W(1,arguments),t instanceof Date||Et(t)==="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Fn(t){if(W(1,arguments),!Bn(t)&&typeof t!="number")return!1;var e=X(t);return!isNaN(Number(e))}function zn(t,e){W(2,arguments);var r=ce(e);return qn(t,-r)}var Yn=864e5;function Hn(t){W(1,arguments);var e=X(t),r=e.getTime();e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);var n=e.getTime(),a=r-n;return Math.floor(a/Yn)+1}function je(t){W(1,arguments);var e=1,r=X(t),n=r.getUTCDay(),a=(n=a.getTime()?r+1:e.getTime()>=s.getTime()?r:r-1}function Gn(t){W(1,arguments);var e=$t(t),r=new Date(0);r.setUTCFullYear(e,0,4),r.setUTCHours(0,0,0,0);var n=je(r);return n}var Kn=6048e5;function Jn(t){W(1,arguments);var e=X(t),r=je(e).getTime()-Gn(e).getTime();return Math.round(r/Kn)+1}function _e(t,e){var r,n,a,o,s,i,l,d;W(1,arguments);var u=Oe(),m=ce((r=(n=(a=(o=e?.weekStartsOn)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.weekStartsOn)!==null&&a!==void 0?a:u.weekStartsOn)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.weekStartsOn)!==null&&r!==void 0?r:0);if(!(m>=0&&m<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var f=X(t),x=f.getUTCDay(),v=(x=1&&x<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var v=new Date(0);v.setUTCFullYear(m+1,0,x),v.setUTCHours(0,0,0,0);var p=_e(v,e),y=new Date(0);y.setUTCFullYear(m,0,x),y.setUTCHours(0,0,0,0);var g=_e(y,e);return u.getTime()>=p.getTime()?m+1:u.getTime()>=g.getTime()?m:m-1}function Xn(t,e){var r,n,a,o,s,i,l,d;W(1,arguments);var u=Oe(),m=ce((r=(n=(a=(o=e?.firstWeekContainsDate)!==null&&o!==void 0?o:e==null||(s=e.locale)===null||s===void 0||(i=s.options)===null||i===void 0?void 0:i.firstWeekContainsDate)!==null&&a!==void 0?a:u.firstWeekContainsDate)!==null&&n!==void 0?n:(l=u.locale)===null||l===void 0||(d=l.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&r!==void 0?r:1),f=Ot(t,e),x=new Date(0);x.setUTCFullYear(f,0,m),x.setUTCHours(0,0,0,0);var v=_e(x,e);return v}var Qn=6048e5;function Zn(t,e){W(1,arguments);var r=X(t),n=_e(r,e).getTime()-Xn(r,e).getTime();return Math.round(n/Qn)+1}function $(t,e){for(var r=t<0?"-":"",n=Math.abs(t).toString();n.length0?n:1-n;return $(r==="yy"?a%100:a,r.length)},M:function(e,r){var n=e.getUTCMonth();return r==="M"?String(n+1):$(n+1,2)},d:function(e,r){return $(e.getUTCDate(),r.length)},a:function(e,r){var n=e.getUTCHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h:function(e,r){return $(e.getUTCHours()%12||12,r.length)},H:function(e,r){return $(e.getUTCHours(),r.length)},m:function(e,r){return $(e.getUTCMinutes(),r.length)},s:function(e,r){return $(e.getUTCSeconds(),r.length)},S:function(e,r){var n=r.length,a=e.getUTCMilliseconds(),o=Math.floor(a*Math.pow(10,n-3));return $(o,r.length)}},ue={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},ea={G:function(e,r,n){var a=e.getUTCFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});default:return n.era(a,{width:"wide"})}},y:function(e,r,n){if(r==="yo"){var a=e.getUTCFullYear(),o=a>0?a:1-a;return n.ordinalNumber(o,{unit:"year"})}return ee.y(e,r)},Y:function(e,r,n,a){var o=Ot(e,a),s=o>0?o:1-o;if(r==="YY"){var i=s%100;return $(i,2)}return r==="Yo"?n.ordinalNumber(s,{unit:"year"}):$(s,r.length)},R:function(e,r){var n=$t(e);return $(n,r.length)},u:function(e,r){var n=e.getUTCFullYear();return $(n,r.length)},Q:function(e,r,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"Q":return String(a);case"QQ":return $(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(e,r,n){var a=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"q":return String(a);case"qq":return $(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(e,r,n){var a=e.getUTCMonth();switch(r){case"M":case"MM":return ee.M(e,r);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(e,r,n){var a=e.getUTCMonth();switch(r){case"L":return String(a+1);case"LL":return $(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(e,r,n,a){var o=Zn(e,a);return r==="wo"?n.ordinalNumber(o,{unit:"week"}):$(o,r.length)},I:function(e,r,n){var a=Jn(e);return r==="Io"?n.ordinalNumber(a,{unit:"week"}):$(a,r.length)},d:function(e,r,n){return r==="do"?n.ordinalNumber(e.getUTCDate(),{unit:"date"}):ee.d(e,r)},D:function(e,r,n){var a=Hn(e);return r==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):$(a,r.length)},E:function(e,r,n){var a=e.getUTCDay();switch(r){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(e,r,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(r){case"e":return String(s);case"ee":return $(s,2);case"eo":return n.ordinalNumber(s,{unit:"day"});case"eee":return n.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(o,{width:"short",context:"formatting"});default:return n.day(o,{width:"wide",context:"formatting"})}},c:function(e,r,n,a){var o=e.getUTCDay(),s=(o-a.weekStartsOn+8)%7||7;switch(r){case"c":return String(s);case"cc":return $(s,r.length);case"co":return n.ordinalNumber(s,{unit:"day"});case"ccc":return n.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(o,{width:"narrow",context:"standalone"});case"cccccc":return n.day(o,{width:"short",context:"standalone"});default:return n.day(o,{width:"wide",context:"standalone"})}},i:function(e,r,n){var a=e.getUTCDay(),o=a===0?7:a;switch(r){case"i":return String(o);case"ii":return $(o,r.length);case"io":return n.ordinalNumber(o,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(e,r,n){var a=e.getUTCHours(),o=a/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,r,n){var a=e.getUTCHours(),o;switch(a===12?o=ue.noon:a===0?o=ue.midnight:o=a/12>=1?"pm":"am",r){case"b":case"bb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,r,n){var a=e.getUTCHours(),o;switch(a>=17?o=ue.evening:a>=12?o=ue.afternoon:a>=4?o=ue.morning:o=ue.night,r){case"B":case"BB":case"BBB":return n.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(o,{width:"narrow",context:"formatting"});default:return n.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,r,n){if(r==="ho"){var a=e.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return ee.h(e,r)},H:function(e,r,n){return r==="Ho"?n.ordinalNumber(e.getUTCHours(),{unit:"hour"}):ee.H(e,r)},K:function(e,r,n){var a=e.getUTCHours()%12;return r==="Ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,r.length)},k:function(e,r,n){var a=e.getUTCHours();return a===0&&(a=24),r==="ko"?n.ordinalNumber(a,{unit:"hour"}):$(a,r.length)},m:function(e,r,n){return r==="mo"?n.ordinalNumber(e.getUTCMinutes(),{unit:"minute"}):ee.m(e,r)},s:function(e,r,n){return r==="so"?n.ordinalNumber(e.getUTCSeconds(),{unit:"second"}):ee.s(e,r)},S:function(e,r){return ee.S(e,r)},X:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();if(s===0)return"Z";switch(r){case"X":return gt(s);case"XXXX":case"XX":return se(s);default:return se(s,":")}},x:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"x":return gt(s);case"xxxx":case"xx":return se(s);default:return se(s,":")}},O:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},z:function(e,r,n,a){var o=a._originalDate||e,s=o.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+ht(s,":");default:return"GMT"+se(s,":")}},t:function(e,r,n,a){var o=a._originalDate||e,s=Math.floor(o.getTime()/1e3);return $(s,r.length)},T:function(e,r,n,a){var o=a._originalDate||e,s=o.getTime();return $(s,r.length)}};function ht(t,e){var r=t>0?"-":"+",n=Math.abs(t),a=Math.floor(n/60),o=n%60;if(o===0)return r+String(a);var s=e;return r+String(a)+s+$(o,2)}function gt(t,e){if(t%60===0){var r=t>0?"-":"+";return r+$(Math.abs(t)/60,2)}return se(t,e)}function se(t,e){var r=e||"",n=t>0?"-":"+",a=Math.abs(t),o=$(Math.floor(a/60),2),s=$(a%60,2);return n+o+r+s}var yt=function(e,r){switch(e){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});default:return r.date({width:"full"})}},Rt=function(e,r){switch(e){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});default:return r.time({width:"full"})}},ta=function(e,r){var n=e.match(/(P+)(p+)?/)||[],a=n[1],o=n[2];if(!o)return yt(e,r);var s;switch(a){case"P":s=r.dateTime({width:"short"});break;case"PP":s=r.dateTime({width:"medium"});break;case"PPP":s=r.dateTime({width:"long"});break;default:s=r.dateTime({width:"full"});break}return s.replace("{{date}}",yt(a,r)).replace("{{time}}",Rt(o,r))},ra={p:Rt,P:ta},na=["D","DD"],aa=["YY","YYYY"];function oa(t){return na.indexOf(t)!==-1}function sa(t){return aa.indexOf(t)!==-1}function xt(t,e,r){if(t==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var ia={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},ca=function(e,r,n){var a,o=ia[e];return typeof o=="string"?a=o:r===1?a=o.one:a=o.other.replace("{{count}}",r.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a};function ze(t){return function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=e.width?String(e.width):t.defaultWidth,n=t.formats[r]||t.formats[t.defaultWidth];return n}}var da={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},la={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},ua={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ma={date:ze({formats:da,defaultWidth:"full"}),time:ze({formats:la,defaultWidth:"full"}),dateTime:ze({formats:ua,defaultWidth:"full"})},fa={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},pa=function(e,r,n,a){return fa[e]};function he(t){return function(e,r){var n=r!=null&&r.context?String(r.context):"standalone",a;if(n==="formatting"&&t.formattingValues){var o=t.defaultFormattingWidth||t.defaultWidth,s=r!=null&&r.width?String(r.width):o;a=t.formattingValues[s]||t.formattingValues[o]}else{var i=t.defaultWidth,l=r!=null&&r.width?String(r.width):t.defaultWidth;a=t.values[l]||t.values[i]}var d=t.argumentCallback?t.argumentCallback(e):e;return a[d]}}var ha={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ga={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},ya={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},xa={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},ba={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},va={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},wa=function(e,r){var n=Number(e),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},Ca={ordinalNumber:wa,era:he({values:ha,defaultWidth:"wide"}),quarter:he({values:ga,defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:he({values:ya,defaultWidth:"wide"}),day:he({values:xa,defaultWidth:"wide"}),dayPeriod:he({values:ba,defaultWidth:"wide",formattingValues:va,defaultFormattingWidth:"wide"})};function ge(t){return function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.width,a=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],o=e.match(a);if(!o)return null;var s=o[0],i=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],l=Array.isArray(i)?Ea(i,function(m){return m.test(s)}):Sa(i,function(m){return m.test(s)}),d;d=t.valueCallback?t.valueCallback(l):l,d=r.valueCallback?r.valueCallback(d):d;var u=e.slice(s.length);return{value:d,rest:u}}}function Sa(t,e){for(var r in t)if(t.hasOwnProperty(r)&&e(t[r]))return r}function Ea(t,e){for(var r=0;r1&&arguments[1]!==void 0?arguments[1]:{},n=e.match(t.matchPattern);if(!n)return null;var a=n[0],o=e.match(t.parsePattern);if(!o)return null;var s=t.valueCallback?t.valueCallback(o[0]):o[0];s=r.valueCallback?r.valueCallback(s):s;var i=e.slice(a.length);return{value:s,rest:i}}}var Ta=/^(\d+)(th|st|nd|rd)?/i,Aa=/\d+/i,ja={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},_a={any:[/^b/i,/^(a|c)/i]},Na={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},$a={any:[/1/i,/2/i,/3/i,/4/i]},Oa={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Ra={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Da={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Pa={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Ma={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Ia={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},La={ordinalNumber:ka({matchPattern:Ta,parsePattern:Aa,valueCallback:function(e){return parseInt(e,10)}}),era:ge({matchPatterns:ja,defaultMatchWidth:"wide",parsePatterns:_a,defaultParseWidth:"any"}),quarter:ge({matchPatterns:Na,defaultMatchWidth:"wide",parsePatterns:$a,defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:ge({matchPatterns:Oa,defaultMatchWidth:"wide",parsePatterns:Ra,defaultParseWidth:"any"}),day:ge({matchPatterns:Da,defaultMatchWidth:"wide",parsePatterns:Pa,defaultParseWidth:"any"}),dayPeriod:ge({matchPatterns:Ma,defaultMatchWidth:"any",parsePatterns:Ia,defaultParseWidth:"any"})},Ua={code:"en-US",formatDistance:ca,formatLong:ma,formatRelative:pa,localize:Ca,match:La,options:{weekStartsOn:0,firstWeekContainsDate:1}},qa=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Va=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Wa=/^'([^]*?)'?$/,Ba=/''/g,Fa=/[a-zA-Z]/;function za(t,e,r){var n,a,o,s,i,l,d,u,m,f,x,v,p,y;W(2,arguments);var g=String(e),C=Oe(),T=(n=(a=void 0)!==null&&a!==void 0?a:C.locale)!==null&&n!==void 0?n:Ua,j=ce((o=(s=(i=(l=void 0)!==null&&l!==void 0?l:void 0)!==null&&i!==void 0?i:C.firstWeekContainsDate)!==null&&s!==void 0?s:(d=C.locale)===null||d===void 0||(u=d.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&o!==void 0?o:1);if(!(j>=1&&j<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var N=ce((m=(f=(x=(v=void 0)!==null&&v!==void 0?v:void 0)!==null&&x!==void 0?x:C.weekStartsOn)!==null&&f!==void 0?f:(p=C.locale)===null||p===void 0||(y=p.options)===null||y===void 0?void 0:y.weekStartsOn)!==null&&m!==void 0?m:0);if(!(N>=0&&N<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!T.localize)throw new RangeError("locale must contain localize property");if(!T.formatLong)throw new RangeError("locale must contain formatLong property");var A=X(t);if(!Fn(A))throw new RangeError("Invalid time value");var I=Wn(A),q=zn(A,I),E={firstWeekContainsDate:j,weekStartsOn:N,locale:T,_originalDate:A},L=g.match(Va).map(function(D){var M=D[0];if(M==="p"||M==="P"){var K=ra[M];return K(D,T.formatLong)}return D}).join("").match(qa).map(function(D){if(D==="''")return"'";var M=D[0];if(M==="'")return Ya(D);var K=ea[M];if(K)return sa(D)&&xt(D,e,String(t)),oa(D)&&xt(D,e,String(t)),K(q,D,T.localize,E);if(M.match(Fa))throw new RangeError("Format string contains an unescaped latin alphabet character `"+M+"`");return D}).join("");return L}function Ya(t){var e=t.match(Wa);return e?e[1].replace(Ba,"'"):t}const Ha=()=>{const{threads:t,selectedThread:e,setSelectedThread:r,createPersistentThread:n,deletePersistentThread:a,hydrateThreadMessages:o,selectedAssistant:s,darkMode:i}=me(),[l,d]=h.useState(null),[u,m]=h.useState(null),f=async()=>{if(!s?.id){m("Select a live agent before creating a thread.");return}d("new"),m(null);try{await n(s.id,`Thread ${t.length+1}`)}catch(p){m(p?.message||"Could not create a durable thread.")}finally{d(null)}},x=async p=>{const y=p.agentId||s?.id;d(`load:${p.id}`),m(null);try{const g=y?await o(p.id,y):void 0;r(g||p)}catch(g){m(g?.message||"Could not load this thread’s durable history."),r(p)}finally{d(null)}},v=async(p,y)=>{y.stopPropagation(),d(`delete:${p.id}`),m(null);try{await a(p)}catch(g){m(g?.message||"Could not delete the durable thread.")}finally{d(null)}};return c.jsxs("div",{className:`h-full flex flex-col ${i?"bg-gray-800 border-gray-700":"bg-white border-gray-200"} border-r transition-colors duration-300`,children:[c.jsxs("div",{className:`p-4 border-b ${i?"border-gray-700":"border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(pt,{className:`w-5 h-5 ${i?"text-blue-400":"text-blue-600"}`}),c.jsx("h2",{className:`text-lg font-semibold ${i?"text-white":"text-gray-900"}`,children:"Threads"})]}),c.jsx("div",{className:`px-2 py-1 rounded-full text-xs font-medium ${i?"bg-gray-700 text-gray-300":"bg-gray-100 text-gray-600"}`,children:t.length})]}),c.jsxs("button",{onClick:()=>{f()},disabled:l!==null,className:`w-full flex items-center justify-center px-4 py-3 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md ${i?"bg-blue-600 hover:bg-blue-700 text-white hover:scale-105":"bg-blue-600 text-white hover:bg-blue-700 hover:scale-105"}`,children:[c.jsx(jn,{className:"w-4 h-4 mr-2"}),l==="new"?"Creating…":"New Thread"]})]}),u&&c.jsx("p",{role:"alert",className:`mx-4 mb-3 rounded-md border p-2 text-xs ${i?"border-red-800 bg-red-950/40 text-red-200":"border-red-200 bg-red-50 text-red-700"}`,children:u}),c.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:t.length===0?c.jsxs("div",{className:`p-6 text-center ${i?"text-gray-400":"text-gray-500"}`,children:[c.jsx("div",{className:`w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center ${i?"bg-gray-700":"bg-gray-100"}`,children:c.jsx(pt,{className:`w-8 h-8 ${i?"text-gray-500":"text-gray-400"}`})}),c.jsx("h3",{className:`text-sm font-medium mb-2 ${i?"text-gray-300":"text-gray-700"}`,children:"No threads yet"}),c.jsx("p",{className:"text-xs leading-relaxed",children:"Create your first thread to start a conversation with your agent"})]}):c.jsx("div",{className:"p-3 space-y-2",children:t.map(p=>c.jsxs("div",{onClick:()=>{x(p)},className:`group relative p-4 rounded-xl cursor-pointer transition-all duration-200 ${e?.id===p.id?i?"bg-blue-900/50 border-2 border-blue-600 shadow-lg":"bg-blue-50 border-2 border-blue-200 shadow-md":i?"hover:bg-gray-700 border-2 border-transparent hover:border-gray-600":"hover:bg-gray-50 border-2 border-transparent hover:border-gray-200"}`,children:[c.jsxs("div",{className:"flex items-start justify-between",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center space-x-2 mb-2",children:[c.jsx("h3",{className:`text-sm font-semibold truncate ${e?.id===p.id?i?"text-blue-300":"text-blue-700":i?"text-white":"text-gray-900"}`,children:p.name}),p.messages.length>0&&c.jsx("span",{className:`px-2 py-0.5 text-xs rounded-full font-medium ${e?.id===p.id?i?"bg-blue-800 text-blue-200":"bg-blue-100 text-blue-700":i?"bg-gray-600 text-gray-300":"bg-gray-200 text-gray-600"}`,children:p.messages.length})]}),p.messages.length>0?c.jsx("p",{className:`text-xs line-clamp-2 mb-2 ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-400":"text-gray-500"}`,children:p.messages[p.messages.length-1].content}):c.jsx("p",{className:`text-xs italic mb-2 ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:"No messages yet"}),c.jsxs("div",{className:`flex items-center space-x-1 text-xs ${e?.id===p.id?i?"text-blue-400":"text-blue-600":i?"text-gray-500":"text-gray-400"}`,children:[c.jsx(vn,{className:"w-3 h-3"}),c.jsx("span",{children:za(p.updatedAt,"MMM d, HH:mm")})]})]}),c.jsx("button",{onClick:y=>{v(p,y)},disabled:l!==null,className:`opacity-0 group-hover:opacity-100 p-1.5 rounded-lg transition-all duration-200 ${i?"hover:bg-red-900 text-gray-400 hover:text-red-300":"hover:bg-red-50 text-gray-400 hover:text-red-600"}`,title:"Delete thread",children:l===`delete:${p.id}`?"…":c.jsx(Mn,{className:"w-4 h-4"})})]}),e?.id===p.id&&c.jsx("div",{className:`absolute left-0 top-1/2 transform -translate-y-1/2 w-1 h-8 rounded-r-full ${i?"bg-blue-400":"bg-blue-600"}`})]},p.id))})}),t.length>0&&c.jsx("div",{className:`p-4 border-t ${i?"border-gray-700":"border-gray-200"}`,children:c.jsxs("div",{className:`text-xs text-center ${i?"text-gray-500":"text-gray-400"}`,children:[t.length," thread",t.length!==1?"s":""," •",t.reduce((p,y)=>p+y.messages.length,0)," total messages"]})})]})},Ga=({children:t})=>{const{darkMode:e}=me();return c.jsx("div",{className:`flex-1 flex flex-col min-h-0 overflow-hidden ${e?"bg-gray-900":"bg-gray-50"}`,style:{height:"100%"},children:t})},Ka=B.lazy(()=>G(async()=>{const{GraphView:t}=await import("./GraphView-CxhhCL_h.js");return{GraphView:t}},__vite__mapDeps([0,1,2,3,4])).then(({GraphView:t})=>({default:t}))),bt=B.lazy(()=>G(async()=>{const{ChatView:t}=await import("./ChatView-Bc4TZ9mm.js");return{ChatView:t}},__vite__mapDeps([5,1,2,3,4,6])).then(({ChatView:t})=>({default:t}))),Ja=B.lazy(()=>G(async()=>{const{DebugView:t}=await import("./DebugView-BXWYXNI6.js");return{DebugView:t}},__vite__mapDeps([7,1,6,4])).then(({DebugView:t})=>({default:t}))),Xa=B.lazy(()=>G(async()=>{const{PipelinesView:t}=await import("./PipelinesView-Yvdzmlvq.js");return{PipelinesView:t}},__vite__mapDeps([8,1,2,3,4])).then(({PipelinesView:t})=>({default:t}))),Qa=B.lazy(()=>G(async()=>{const{BuilderView:t}=await import("./BuilderView-BChq4Mpg.js");return{BuilderView:t}},__vite__mapDeps([9,1,10,2,4])).then(({BuilderView:t})=>({default:t}))),Za=B.lazy(()=>G(async()=>{const{PluginsView:t}=await import("./PluginsView-BCct6WZb.js");return{PluginsView:t}},__vite__mapDeps([11,1,2,3,4])).then(({PluginsView:t})=>({default:t}))),eo=B.lazy(()=>G(async()=>{const{IngestorsView:t}=await import("./IngestorsView-Be0ZMvN2.js");return{IngestorsView:t}},__vite__mapDeps([12,1,2,3,4])).then(({IngestorsView:t})=>({default:t}))),to=B.lazy(()=>G(async()=>{const{TasksView:t}=await import("./TasksView-B5ml_CT4.js");return{TasksView:t}},__vite__mapDeps([13,1,2,3,4])).then(({TasksView:t})=>({default:t}))),ro=B.lazy(()=>G(async()=>{const{ControlPlaneView:t}=await import("./ControlPlaneView-Vj8HdZgI.js");return{ControlPlaneView:t}},__vite__mapDeps([14,1,4])).then(({ControlPlaneView:t})=>({default:t}))),no=B.lazy(()=>G(async()=>{const{EndpointsView:t}=await import("./EndpointsView-DqDGXNuG.js");return{EndpointsView:t}},__vite__mapDeps([15,1,2,3,4])).then(({EndpointsView:t})=>({default:t}))),ao=B.lazy(()=>G(async()=>{const{ConnectionsView:t}=await import("./ConnectionsView-CD79PtTG.js");return{ConnectionsView:t}},__vite__mapDeps([16,1,3,4])).then(({ConnectionsView:t})=>({default:t})));class oo extends B.Component{constructor(){super(...arguments),this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidUpdate(e){e.view!==this.props.view&&this.state.failed&&this.setState({failed:!1})}render(){return this.state.failed?c.jsxs("div",{role:"alert",className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center ${this.props.darkMode?"text-gray-200":"text-gray-800"}`,children:[c.jsxs("div",{children:[c.jsx("h2",{className:"text-lg font-semibold",children:"Workspace could not load"}),c.jsx("p",{className:`mt-1 max-w-md text-sm ${this.props.darkMode?"text-gray-400":"text-gray-600"}`,children:"A Studio module could not be loaded. Reload to fetch the current deployment assets."})]}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-lg bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700",children:"Reload Studio"})]}):this.props.children}}const so=()=>{const{currentView:t,setCurrentView:e,sidebarCollapsed:r,setSidebarCollapsed:n,darkMode:a}=me();h.useEffect(()=>{t||e("chat")},[t,e]),h.useEffect(()=>{const i=window.matchMedia("(max-width: 767px)"),l=()=>{i.matches&&n(!0)};return l(),i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[n]),h.useEffect(()=>{const i=l=>{if(l.ctrlKey||l.metaKey)switch(l.key){case"1":l.preventDefault(),e("chat");break;case"2":l.preventDefault(),e("graph");break;case"3":l.preventDefault(),e("debug");break;case"4":l.preventDefault(),e("pipelines");break;case"9":l.preventDefault(),e("builder");break;case"5":l.preventDefault(),e("plugins");break;case"0":l.preventDefault(),e("ingestion");break;case"-":l.preventDefault(),e("tasks");break;case"6":l.preventDefault(),e("control");break;case"7":l.preventDefault(),e("endpoints");break;case"8":l.preventDefault(),e("connections");break}};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[e]);const o=()=>{switch(t){case"graph":return c.jsx(Ka,{});case"chat":return c.jsx(bt,{});case"debug":return c.jsx(Ja,{});case"pipelines":return c.jsx(Xa,{});case"builder":return c.jsx(Qa,{});case"plugins":return c.jsx(Za,{});case"ingestion":return c.jsx(eo,{});case"tasks":return c.jsx(to,{});case"control":return c.jsx(ro,{});case"endpoints":return c.jsx(no,{});case"connections":return c.jsx(ao,{});default:return c.jsx(bt,{})}},s=c.jsx("div",{className:`flex h-full items-center justify-center p-6 text-sm ${a?"text-gray-400":"text-gray-600"}`,role:"status",children:"Loading workspace…"});return c.jsxs("div",{className:`h-screen w-screen flex flex-col overflow-hidden ${a?"bg-gray-900":"bg-gray-50"}`,children:[c.jsx("div",{className:"flex-shrink-0",children:c.jsx(Un,{})}),c.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden",children:[!r&&c.jsx("button",{type:"button","aria-label":"Close thread sidebar",className:"absolute inset-0 z-30 bg-black/35 md:hidden",onClick:()=>n(!0)}),c.jsx("div",{className:`flex-shrink-0 transition-all duration-300 ease-in-out overflow-hidden ${r?"w-0":"absolute inset-y-0 left-0 z-40 w-80 shadow-2xl md:static md:w-72 md:shadow-none xl:w-80"}`,style:{height:"100%"},children:c.jsx(Ha,{})}),c.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:c.jsx(Ga,{children:c.jsx(oo,{darkMode:a,view:t,children:c.jsx(h.Suspense,{fallback:s,children:o()})})})})]})]})},io=8e3,J=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=(t,e)=>{const r=t?.[e];return J(r)?r:void 0},co=(t,e)=>{const r=U(t,e);if(r||!t)return{pathItem:r,boundPathParameters:new Set};const n=e.split("/");for(const a of Object.keys(t)){if(!a.includes("{"))continue;const o=a.split("/");if(o.length!==n.length)continue;const s=new Set,i=o.every((d,u)=>{const m=/^\{([^}/]+)\}$/.exec(d);return m?(s.add(m[1]),n[u].length>0):d===n[u]}),l=U(t,a);if(i&&l)return{pathItem:l,boundPathParameters:s}}return{pathItem:void 0,boundPathParameters:new Set}},lo=t=>t!==null&&typeof t.name=="string"&&(t.in==="query"||t.in==="header"||t.in==="path"),Ye=(t,e="")=>typeof t=="string"?t:e,uo=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[];class Xe{constructor(e,r,n=io){this.openApiDocument=null,this.baseUrl=e.replace(/\/$/,""),this.apiKey=r||null,this.timeoutMs=n,this.headers={"Content-Type":"application/json",...this.apiKey?{"X-Api-Key":this.apiKey,Authorization:`Bearer ${this.apiKey}`}:{}}}async request(e,r){const n=`${this.baseUrl}${e}`,a=new AbortController,o=setTimeout(()=>a.abort(),this.timeoutMs),s=r?.signal;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));try{const i=await fetch(n,{...r,signal:a.signal,headers:{...this.headers,...r?.headers}});if(!i.ok){const d=await i.text().catch(()=>"");throw new ye(i.status,i.statusText,d)}if(i.status===204||r?.method?.toUpperCase()==="HEAD")return null;const l=await i.text();return l?JSON.parse(l):null}catch(i){throw J(i)&&i.name==="AbortError"?new ye(408,"Request Timeout",`Timed out after ${this.timeoutMs}ms: ${e}`):i}finally{clearTimeout(o)}}async getServerInfo(){return this.request("/studio/info")}async getOperationContract(e,r="post"){if(!this.openApiDocument){const b=this.request("/openapi.json");this.openApiDocument=b,b.catch(()=>{this.openApiDocument===b&&(this.openApiDocument=null)})}const n=await this.openApiDocument,a=U(n,"components"),{pathItem:o,boundPathParameters:s}=co(U(n,"paths"),e),i=U(o,r.toLowerCase());if(!i)throw new ye(404,"Operation not found",`${r.toUpperCase()} ${e}`);const l=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/schemas/"))return{...b,...a?{components:a}:{}};const k=w.slice(21),S=U(U(a,"schemas"),k);return J(S)?{...S,...a?{components:a}:{}}:null},d=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/parameters/"))return b;const k=w.slice(24),S=U(U(a,"parameters"),k);return J(S)?S:null},u=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/requestBodies/"))return b;const k=w.slice(27),S=U(U(a,"requestBodies"),k);return J(S)?S:null},m=b=>{if(!J(b))return null;const w=typeof b.$ref=="string"?b.$ref:"";if(!w.startsWith("#/components/responses/"))return b;const k=w.slice(23),S=U(U(a,"responses"),k);return J(S)?S:null},f=u(i.requestBody),x=U(U(f??void 0,"content"),"application/json")?.schema,v=new Map;[...Array.isArray(o?.parameters)?o.parameters:[],...Array.isArray(i.parameters)?i.parameters:[]].map(d).filter(lo).filter(b=>!(b.in==="path"&&s.has(b.name))).forEach(b=>v.set(`${b.in}:${b.name}`,b));const p=Array.from(v.values()),y=l(x),g=!!(y&&(y.type==="object"||y.properties)),C="__body",T=f?.required===!0,j=U(y??void 0,"properties")?U(y??void 0,"properties"):{},N=uo(y?.required),A=new Set(Object.keys(j)),I={},q={},E=[];for(const b of p){const w=b.name;let k=w;if(A.has(k)){k=`${b.in}_${w}`;let O=2;for(;A.has(k);)k=`${b.in}_${w}_${O++}`}A.add(k);const S=l(b.schema)||{};q[k]={...S,title:Ye(S.title,w),description:[Ye(S.description),`${b.in} parameter`].filter(Boolean).join(" · ")},I[k]={name:w,in:b.in},(b.required===!0||b.in==="path")&&E.push(k)}const L=p.length?{type:"object",properties:q,...E.length?{required:E}:{},components:a}:null,D=y&&g?{...y,properties:{...j,...q},...N.length||E.length?{required:Array.from(new Set([...N,...E]))}:{}}:y&&L?{type:"object",properties:{[C]:{...y,title:Ye(y.title,"Request body")},...q},...T||E.length?{required:[...T?[C]:[],...E]}:{}}:y||L,M=U(i,"responses")||{},K=m(M[200]||M[201]||M[202]||Object.values(M)[0]),ne=U(U(K??void 0,"content"),"application/json")?.schema;return{input_schema:D,output_schema:l(ne),method:r.toUpperCase(),path:e,...Object.keys(I).length?{parameters:I}:{},...y&&!g&&L?{body_field:C}:{}}}async getEndpointContract(e){const r=Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.toUpperCase()):[],n=Array.from(new Set(["POST",...r])),a=`/api/v1/endpoints/${encodeURIComponent(e.name)}${e.path}`;let o;for(const s of n)try{return await this.getOperationContract(a,s)}catch(i){if(!(i instanceof ye&&i.status===404))throw i;o=i}throw o instanceof Error?o:new ye(404,"Operation not found",`${e.name} has no documented callable method`)}async listAgents(){const e=await this.request("/studio/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:e?.agents&&typeof e.agents=="object"?Object.entries(e.agents).map(([r,n])=>({name:n?.name||r,slug:n?.slug||r,description:n?.description||"",version:n?.version||"1.0.0",framework:n?.framework||"unknown",capabilities:n?.capabilities||[],has_graph:!!n?.has_graph,has_config:!!n?.has_config,has_prompts:!!n?.has_prompts})):[]}async getGraph(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/graph`)}async getSchemas(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/schemas`)}async getAgentConfig(e){return this.request(`/studio/agents/${encodeURIComponent(e)}/config`)}normalizeThread(e,r){return{id:e?.id||e?.thread_id||"",user_id:e?.user_id||"default-user",agent_name:e?.agent_name||r||"",title:e?.title??null,metadata:e?.metadata||{},created_at:e?.created_at||e?.created||new Date().toISOString(),updated_at:e?.updated_at||e?.updated||e?.created_at||new Date().toISOString()}}normalizeMessage(e,r){return{id:String(e?.id||e?.message_id||`${r}-${e?.timestamp||Date.now()}`),thread_id:e?.thread_id||r,role:e?.role||"assistant",content:typeof e?.content=="string"?e.content:JSON.stringify(e?.content??e?.message??""),metadata:e?.metadata||{},timestamp:e?.timestamp||e?.created_at||new Date().toISOString()}}async createThread(e,r,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`,{method:"POST",body:JSON.stringify({user_id:r||"default-user",title:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async listThreads(e){const r=await this.request(`/api/v1/${encodeURIComponent(e)}/threads`);return(Array.isArray(r)?r:Array.isArray(r?.threads)?r.threads:[]).map(a=>this.normalizeThread(a,e))}async getThread(e,r){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}`);return this.normalizeThread(n,e)}async deleteThread(e,r){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}`,{method:"DELETE"})}async getMessages(e,r){const n=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/messages`);return(Array.isArray(n)?n:Array.isArray(n?.messages)?n.messages:[]).map(o=>this.normalizeMessage(o,r))}async forkThread(e,r,n){const a=await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/fork`,{method:"POST",body:JSON.stringify({message_index:n})}),o=a?.thread||a;return this.normalizeThread(o,e)}async createRun(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs`,{method:"POST",body:JSON.stringify(r)})}async listRuns(e,r=50){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs?limit=${r}`)}async getRun(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(r)}`)}async getState(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/state`)}async updateState(e,r,n){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/state`,{method:"POST",body:JSON.stringify({updates:n})})}async getHistory(e,r){return this.request(`/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/history`)}async getPendingApprovals(e,r){return this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/pending`)}async approve(e,r,n){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({approval_id:n})})}async reject(e,r,n,a){await this.request(`/api/v1/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({approval_id:n,reason:a})})}async healthCheck(){try{return await this.request("/studio/info"),!0}catch{return!1}}async listPipelines(){const e=await this.request("/api/v1/pipelines");return(Array.isArray(e)?e:Array.isArray(e?.pipelines)?e.pipelines:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",steps:Array.isArray(n?.steps)?n.steps:[],agents_used:Array.isArray(n?.agents_used)?n.agents_used:[]}))}async runPipeline(e,r){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(r)})}async validatePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/validate`)}async validatePipelineDraft(e){return this.request("/api/v1/pipelines/validate-draft",{method:"POST",body:JSON.stringify(e)})}async savePipeline(e,r){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(r)})}async deletePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}`,{method:"DELETE"})}async listEndpoints(){const e=await this.request("/api/v1/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listIngestors(){const e=await this.request("/api/v1/ingestors");return(Array.isArray(e)?e:Array.isArray(e?.ingestors)?e.ingestors:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",ready:!!n?.ready,input_schema:n?.input_schema||""}))}async runIngestor(e,r){return this.request(`/api/v1/ingestion/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(r)})}async listTasks(e={}){const r=new URLSearchParams;return Object.entries(e).forEach(([n,a])=>{a!==void 0&&a!==""&&r.set(n,String(a))}),this.request(`/api/v1/tasks${r.size?`?${r}`:""}`)}async submitTask(e){return this.request("/api/v1/tasks",{method:"POST",body:JSON.stringify(e)})}async getTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`)}async getTaskResult(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/result`)}async cancelTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}/cancel`,{method:"POST"})}async deleteTask(e){return this.request(`/api/v1/tasks/${encodeURIComponent(e)}`,{method:"DELETE"})}async getPipelineConfig(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/config`)}async visualizePipeline(e){return this.request(`/api/v1/pipelines/${encodeURIComponent(e)}/visualize`)}async listPlugins(){const e=await this.request("/api/v1/plugins");return(Array.isArray(e)?e:Array.isArray(e?.plugins)?e.plugins:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",is_loaded:!!n?.is_loaded}))}async getPluginModelCard(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/model_card`)}async reloadPlugin(e){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/reload`,{method:"POST"})}async runPluginPredict(e,r){return this.request(`/api/v1/plugins/${encodeURIComponent(e)}/predict`,{method:"POST",body:JSON.stringify(r)})}async callEndpoint(e,r,n,a="POST",o){const s=a.toUpperCase();let i=`/api/v1/endpoints/${encodeURIComponent(e)}${r}`;const l=new URLSearchParams,d={},u={},m=o?.parameters||{},f=o?.body_field,x=n&&typeof n=="object"&&!Array.isArray(n)?n:null,v=f&&x?x[f]:n;for(const[y,g]of Object.entries(x||{})){if(y===f)continue;const C=m[y],j=C?C.in:s==="GET"||s==="HEAD"?"query":"body",N=C?.name||y;if(j==="body"){d[y]=g;continue}if(!(g==null||g==="")){if(j==="path"){i=i.replace(`{${N}}`,encodeURIComponent(String(g)));continue}if(j==="header"){u[N]=Array.isArray(g)?g.map(A=>typeof A=="string"?A:JSON.stringify(A)).join(", "):typeof g=="object"?JSON.stringify(g):String(g);continue}Array.isArray(g)?g.forEach(A=>l.append(N,typeof A=="string"?A:JSON.stringify(A))):l.set(N,typeof g=="object"?JSON.stringify(g):String(g))}}const p=l.size?`?${l.toString()}`:"";return s==="GET"||s==="HEAD"?this.request(`${i}${p}`,{method:s,headers:u}):this.request(`${i}${p}`,{method:s,headers:u,body:JSON.stringify(f||!x?v:d)})}async getControlInfo(){return this.request("/api/v1/control")}async listControlAgents(){const e=await this.request("/api/v1/control/agents");return Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]}async getControlAgent(e){return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}`)}async listControlEndpoints(){const e=await this.request("/api/v1/control/endpoints");return(Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:[]).map(n=>({name:n?.name||"",description:n?.description||"",version:n?.version||"1.0.0",path:n?.path||"",methods:Array.isArray(n?.methods)?n.methods:[],aggregation:n?.aggregation||"",upstreams:Array.isArray(n?.upstreams)?n.upstreams:[],ready:!!n?.ready}))}async listControlConnections(){const e=await this.request("/api/v1/control/connections");return(Array.isArray(e)?e:Array.isArray(e?.connections)?e.connections:[]).map(n=>({scope:n?.scope||"",connections:n?.connections||{}}))}async probeControlConnection(e,r){return this.request(`/api/v1/control/connections/${encodeURIComponent(e)}/${encodeURIComponent(r)}`)}async getControlMetricsSummary(){return this.request("/api/v1/control/metrics/summary")}async getControlHealth(){return this.request("/api/v1/control/health")}async getControlConfig(){return this.request("/api/v1/control/config")}async setAgentEnabled(e,r,n){const a=r?"enable":"disable";return this.request(`/api/v1/control/agents/${encodeURIComponent(e)}/${a}`,{method:"POST",headers:n?{"X-Control-Token":n}:{}})}async setMaintenance(e,r){return this.request("/api/v1/control/maintenance",{method:"POST",headers:r?{"X-Control-Token":r}:{},body:JSON.stringify({enabled:e})})}getStreamUrl(e){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/runs/stream`}getResumeStreamUrl(e,r){return`${this.baseUrl}/studio/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(r)}/resume`}getHeaders(){return{...this.headers}}}class ye extends Error{constructor(e,r,n){super(`API Error ${e}: ${r}`),this.status=e,this.statusText=r,this.body=n,this.name="ApiError"}}const mo="agentomatic-studio:lastUrl",Ne="agentomatic-studio:lastApiKey",vt="agentomatic-studio:lastApiKey",fo=()=>{try{const t=sessionStorage.getItem(Ne);if(t)return t;const e=localStorage.getItem(vt);return e?(sessionStorage.setItem(Ne,e),localStorage.removeItem(vt),e):""}catch{return""}},po={graph:{light:"bg-blue-100 text-blue-700 border-blue-200",dark:"bg-blue-900/40 text-blue-300 border-blue-700"},streaming:{light:"bg-green-100 text-green-700 border-green-200",dark:"bg-green-900/40 text-green-300 border-green-700"},hitl:{light:"bg-amber-100 text-amber-700 border-amber-200",dark:"bg-amber-900/40 text-amber-300 border-amber-700"},checkpoints:{light:"bg-purple-100 text-purple-700 border-purple-200",dark:"bg-purple-900/40 text-purple-300 border-purple-700"}},ho={light:"bg-gray-100 text-gray-700 border-gray-200",dark:"bg-gray-700 text-gray-300 border-gray-600"},go=()=>{const t=Mt(),{setConfig:e,setIsConnected:r,setIsLoading:n,addAssistant:a,clearAssistants:o,fetchGraphData:s,refreshThreads:i,setSelectedAgent:l,darkMode:d}=me(),[u,m]=h.useState(()=>{const S=fo();return{apiUrl:Ae(),agentId:"",apiKey:S||""}}),[f,x]=h.useState({status:"idle",message:"Enter server URL to check connectivity"}),[v,p]=h.useState([]),[y,g]=h.useState(!1),[C,T]=h.useState(!1),[j,N]=h.useState(!1),[,A]=h.useState(null),[I,q]=h.useState({}),E=h.useRef(0),L=h.useCallback((S,O)=>{try{localStorage.setItem(mo,S),O?sessionStorage.setItem(Ne,O):sessionStorage.removeItem(Ne)}catch{}},[]),D=h.useCallback(S=>{const O=po[S]||ho,F=d?O.dark:O.light;return c.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border leading-tight ${F}`,children:S},S)},[d]),M=h.useCallback(async S=>{const O=++E.current,F=mt(S);if(!F||!F.startsWith("http")){x({status:"idle",message:"Enter a valid server URL"}),p([]),q({}),N(!1),g(!1);return}x({status:"checking",message:"Checking server connectivity..."}),p([]),q({}),N(!1),g(!0),m(z=>z.agentId?{...z,agentId:""}:z);try{const z=new Xe(F,u.apiKey||void 0),H=await z.getServerInfo();if(O!==E.current)return;A(H);const ae=await z.listAgents();if(O!==E.current)return;if(ae.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ve=ae.map(_=>({id:_.slug||_.name,name:_.name,description:_.description||`${_.framework} agent`,config:{capabilities:_.capabilities,has_graph:_.has_graph,version:_.version}})),oe={};ae.forEach(_=>{oe[_.slug||_.name]=_.capabilities||[]}),q(oe),p(ve),m(_=>({..._,agentId:ve[0].id})),x({status:"success",message:`Connected to ${H.platform_title||"Agentomatic"} v${H.version} — ${H.agent_count} agent(s)`,lastChecked:new Date}),setTimeout(()=>N(!0),300)}catch(z){if(O!==E.current)return;const H=z?.status===401||z?.status===403?"Studio authorization failed. Provide a valid API key and retry.":`Studio API is unavailable: ${z?.message||"start the platform with Studio enabled."}`;x({status:"error",message:H,lastChecked:new Date}),N(!1)}finally{O===E.current&&g(!1)}},[u.apiKey]);h.useEffect(()=>{const S=setTimeout(()=>{u.apiUrl&&M(u.apiUrl)},1e3);return()=>clearTimeout(S)},[u.apiUrl,M]);const K=async S=>{if(S.preventDefault(),f.status!=="success"){Se.error("Please ensure the server connection is healthy before connecting");return}if(!u.agentId){Se.error("Please select a live agent to use");return}T(!0),n(!0);try{const O=mt(u.apiUrl),F=new Xe(O,u.apiKey||void 0),[z,H]=await Promise.all([F.getServerInfo(),F.listAgents()]);if(H.length===0)throw new Error("Studio is available but this deployment has no published agents.");const ae=H.map(_=>({id:_.slug||_.name,name:_.name,description:_.description||"",type:"chat",model:_.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:_.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:_.capabilities,apiName:_.name,slug:_.slug},graph_id:_.slug||_.name}));Je(F),o(),e({...u,apiUrl:O}),ae.forEach(_=>a(_)),r(!0);const ve=u.agentId||H[0]?.slug||H[0]?.name,oe=ae.find(_=>_.id===ve)||ae[0];oe&&(l(oe),s(oe.id).catch(_=>{console.warn("Background graph load failed:",_)}),i(oe.id).catch(()=>{})),L(O,u.apiKey||""),Se.success(`Connected to ${z.platform_title||"Agentomatic"} v${z.version}!`),setTimeout(()=>t("/studio"),500)}catch(O){console.error("Connection error:",O),Se.error("Failed to connect. Please check your configuration.")}finally{T(!1),n(!1)}},ne=(S,O)=>{m(F=>({...F,[S]:O}))},b=()=>{switch(f.status){case"checking":return c.jsxs("svg",{className:"w-5 h-5 animate-spin text-blue-500",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]});case"success":return c.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})});case"error":return c.jsx("svg",{className:"w-5 h-5 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})});default:return c.jsx("svg",{className:"w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}},w=()=>{switch(f.status){case"checking":return"text-blue-600 bg-blue-50 border-blue-200";case"success":return"text-green-600 bg-green-50 border-green-200";case"error":return"text-red-600 bg-red-50 border-red-200";default:return"text-gray-600 bg-gray-50 border-gray-200"}},k=()=>{switch(f.status){case"checking":return"text-blue-400 bg-blue-900/30 border-blue-700";case"success":return"text-green-400 bg-green-900/30 border-green-700";case"error":return"text-red-400 bg-red-900/30 border-red-700";default:return"text-gray-400 bg-gray-800 border-gray-600"}};return c.jsxs("div",{className:`min-h-screen w-full flex ${d?"bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900":"bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50"} relative overflow-hidden`,children:[c.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[c.jsx("div",{className:"absolute inset-0 bg-grid-pattern opacity-5"}),c.jsx("div",{className:`absolute top-1/4 left-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse ${d?"bg-blue-600":"bg-blue-400"}`}),c.jsx("div",{className:`absolute bottom-1/4 right-1/4 w-96 h-96 rounded-full blur-3xl opacity-20 animate-pulse delay-1000 ${d?"bg-purple-600":"bg-purple-400"}`}),c.jsx("div",{className:`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 rounded-full blur-3xl opacity-10 animate-pulse delay-500 ${d?"bg-indigo-600":"bg-indigo-400"}`})]}),c.jsxs("div",{className:"relative z-10 w-full flex",children:[c.jsx("div",{className:"hidden lg:flex lg:w-1/2 xl:w-2/5 flex-col justify-center items-center p-12 relative",children:c.jsxs("div",{className:"max-w-md text-center animate-slide-in-left",children:[c.jsx("div",{className:`w-32 h-32 rounded-3xl flex items-center justify-center mx-auto mb-8 ${d?"bg-gradient-to-br from-blue-600 via-purple-600 to-indigo-600":"bg-gradient-to-br from-blue-500 via-indigo-500 to-purple-600"} shadow-2xl animate-pulse-glow`,children:c.jsx("svg",{className:"w-16 h-16 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),c.jsxs("h1",{className:`text-5xl font-bold mb-6 ${d?"text-white":"text-gray-900"}`,children:["Agentomatic",c.jsx("span",{className:`block text-4xl ${d?"text-violet-400":"text-violet-600"}`,children:"Studio"})]}),c.jsx("p",{className:`text-xl leading-relaxed mb-8 ${d?"text-gray-300":"text-gray-600"}`,children:"Build, debug, and deploy intelligent agent workflows with visual graph execution"}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-green-400":"bg-green-500"} animate-pulse`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Real-time graph execution"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-blue-400":"bg-blue-500"} animate-pulse delay-300`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Interactive debugging tools"})]}),c.jsxs("div",{className:`flex items-center space-x-3 p-4 rounded-xl ${d?"bg-gray-800/50":"bg-white/50"} backdrop-blur-sm`,children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${d?"bg-purple-400":"bg-purple-500"} animate-pulse delay-700`}),c.jsx("span",{className:`text-sm ${d?"text-gray-300":"text-gray-700"}`,children:"Multi-agent orchestration"})]})]})]})}),c.jsx("div",{className:"w-full lg:w-1/2 xl:w-3/5 flex items-center justify-center p-6 lg:p-12",children:c.jsxs("div",{className:`w-full max-w-md rounded-3xl shadow-2xl backdrop-blur-md border ${d?"bg-gray-800/80 border-gray-700":"bg-white/80 border-gray-200"} animate-slide-in-right`,children:[c.jsxs("div",{className:"p-8 text-center",children:[c.jsx("div",{className:"lg:hidden mb-6",children:c.jsx("div",{className:`w-16 h-16 rounded-2xl flex items-center justify-center mx-auto ${d?"bg-gradient-to-br from-blue-600 to-purple-600":"bg-gradient-to-br from-blue-500 to-indigo-600"} shadow-lg`,children:c.jsx("svg",{className:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})})}),c.jsx("h2",{className:`text-2xl lg:text-3xl font-bold mb-3 ${d?"text-white":"text-gray-900"}`,children:"Get Started"}),c.jsx("p",{className:`text-lg ${d?"text-gray-300":"text-gray-600"}`,children:"Connect to your authenticated Agentomatic server"})]}),c.jsxs("div",{className:"px-8 pb-8",children:[c.jsxs("form",{onSubmit:K,className:"space-y-6",children:[c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsx("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:"Server URL"}),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:"url",value:u.apiUrl,onChange:S=>ne("apiUrl",S.target.value),placeholder:Ae(),className:`w-full px-4 py-4 pr-14 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`,required:!0}),c.jsx("div",{className:"absolute right-4 top-1/2 transform -translate-y-1/2",children:b()})]}),c.jsxs("div",{className:`mt-3 p-4 rounded-xl border text-sm flex items-center space-x-3 transition-all duration-300 ${d?k():w()}`,children:[b(),c.jsxs("div",{className:"flex-1",children:[c.jsx("span",{className:"font-medium",children:f.message}),f.lastChecked&&c.jsxs("div",{className:"text-xs opacity-75 mt-1",children:["Last checked: ",f.lastChecked.toLocaleTimeString()]})]})]})]}),c.jsxs("div",{className:"animate-fade-in-up stagger-1",children:[c.jsxs("label",{htmlFor:"agentomatic-api-key",className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["API key ",c.jsx("span",{className:"font-normal opacity-70",children:"(optional)"})]}),c.jsx("input",{id:"agentomatic-api-key",type:"password",value:u.apiKey||"",onChange:S=>ne("apiKey",S.target.value),placeholder:"Required when server authentication is enabled",autoComplete:"off",spellCheck:!1,className:`w-full px-4 py-4 border rounded-2xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300 ${d?"bg-gray-700/50 border-gray-600 text-white placeholder-gray-400":"bg-white/50 border-gray-300 text-gray-900 placeholder-gray-500"} backdrop-blur-sm`}),c.jsx("p",{className:`mt-2 text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Kept only for this tab session after a successful connection; closing the tab removes it."})]}),j&&c.jsxs("div",{className:"animate-fade-in-up stagger-2",children:[c.jsxs("label",{className:`block text-sm font-semibold mb-3 ${d?"text-gray-200":"text-gray-700"}`,children:["Available agents",y&&c.jsxs("span",{className:"ml-2 text-xs text-blue-500",children:[c.jsxs("svg",{className:"inline w-3 h-3 animate-spin mr-1",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Loading..."]})]}),v.length>0?c.jsx("div",{className:"space-y-3 max-h-48 overflow-y-auto custom-scrollbar",children:v.map((S,O)=>c.jsxs("label",{className:`flex items-center p-4 rounded-xl border cursor-pointer transition-all duration-300 transform hover:scale-105 ${u.agentId===S.id?d?"bg-blue-900/40 border-blue-500 text-blue-400 shadow-lg":"bg-blue-50 border-blue-500 text-blue-700 shadow-lg":d?"bg-gray-700/50 border-gray-600 hover:bg-gray-600/50 text-gray-200":"bg-white/50 border-gray-200 hover:bg-gray-50 text-gray-700"} animate-slide-in-right`,style:{animationDelay:`${O*100}ms`},children:[c.jsx("input",{type:"radio",name:"agentId",value:S.id,checked:u.agentId===S.id,onChange:F=>ne("agentId",F.target.value),className:"sr-only"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"font-semibold",children:S.name}),I[S.id]?.length>0&&c.jsx("span",{className:"flex flex-wrap gap-1",children:I[S.id].map(D)})]}),S.description&&c.jsx("div",{className:`text-sm mt-1 ${u.agentId===S.id?"opacity-90":d?"text-gray-400":"text-gray-500"}`,children:S.description})]}),c.jsx("div",{className:`w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all duration-200 ${u.agentId===S.id?"border-current scale-110":d?"border-gray-500":"border-gray-300"}`,children:u.agentId===S.id&&c.jsx("div",{className:"w-3 h-3 rounded-full bg-current animate-pulse"})})]},S.id))}):c.jsx("div",{className:`p-6 rounded-xl border text-center ${d?"bg-gray-700/50 border-gray-600 text-gray-400":"bg-gray-50 border-gray-200 text-gray-500"}`,children:y?c.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Loading live agents..."})]}):"No live agents available. Check the Studio API and server connection."})]}),c.jsx("div",{className:"space-y-4 animate-fade-in-up stagger-3",children:c.jsx("button",{type:"submit",disabled:f.status!=="success"||!u.agentId||C,className:`w-full py-4 px-6 rounded-2xl font-semibold text-white transition-all duration-300 transform ${f.status==="success"&&u.agentId&&!C?"bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 hover:scale-105 shadow-lg hover:shadow-2xl":"bg-gray-400 cursor-not-allowed opacity-50"}`,children:C?c.jsxs("div",{className:"flex items-center justify-center space-x-3",children:[c.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),c.jsx("span",{children:"Connecting..."})]}):"Connect to Server"})})]}),c.jsx("div",{className:`mt-8 pt-6 border-t ${d?"border-gray-600":"border-gray-200"} animate-fade-in-up stagger-4`,children:c.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-green-400":"text-green-600"}`,children:"🚀"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Authenticated server"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Verify before entering Studio"})]}),c.jsxs("div",{className:`p-3 rounded-xl ${d?"bg-gray-700/50":"bg-gray-50"}`,children:[c.jsx("div",{className:`text-2xl mb-1 ${d?"text-blue-400":"text-blue-600"}`,children:"🔗"}),c.jsx("div",{className:`text-xs font-medium ${d?"text-gray-300":"text-gray-700"}`,children:"Live execution"}),c.jsx("div",{className:`text-xs ${d?"text-gray-400":"text-gray-500"}`,children:"Uses deployed resource contracts"})]})]})})]})]})})]})]})},wt="agentomatic-studio:lastApiKey",Ct="agentomatic-studio:lastApiKey",yo=()=>{try{const t=sessionStorage.getItem(wt);if(t)return t;const e=localStorage.getItem(Ct);return e?(sessionStorage.setItem(wt,e),localStorage.removeItem(Ct),e):""}catch{return""}},xo=t=>({id:t.slug||t.name,name:t.name,description:t.description||"",type:"chat",model:t.framework||"unknown",provider:"agentomatic",temperature:.7,maxTokens:1e3,maxIterations:10,tools:[],enableStreaming:t.capabilities?.includes("streaming")||!1,timeout:3e4,config:{capabilities:t.capabilities,apiName:t.name,slug:t.slug},graph_id:t.slug||t.name,metadata:{version:t.version,framework:t.framework,capabilities:t.capabilities,has_graph:t.has_graph,has_config:t.has_config}});function bo(){const{isConnected:t,darkMode:e,setConfig:r,setIsConnected:n,setConnectionStatus:a,clearAssistants:o,addAssistant:s,setSelectedAssistant:i,fetchGraphData:l,refreshThreads:d}=me(),[u,m]=h.useState(!1),f="/studio/ui/".replace(/\/$/,"");h.useEffect(()=>{e?(document.documentElement.setAttribute("data-theme","dark"),document.documentElement.classList.add("dark")):(document.documentElement.removeAttribute("data-theme"),document.documentElement.classList.remove("dark"))},[e]),h.useEffect(()=>{let v=!1;return(async()=>{const y=Ae();let g="";try{g=yo()}catch{}try{const C=new Xe(y,g||void 0);await C.getServerInfo();const T=await C.listAgents();if(v)return;const j=T.map(xo);Je(C);const N=j[0];r({apiUrl:y,apiKey:g||void 0,agentId:N?.id}),o(),j.forEach(s),N&&(i(N),l(N.id),d(N.id).catch(()=>{})),a("connected"),n(!0)}catch{v||(Je(null),a("disconnected"),n(!1))}finally{v||m(!0)}})(),()=>{v=!0}},[s,o,r,a,n,i,l,d]);const x=u?t?c.jsx(so,{}):c.jsx(et,{to:"/setup",replace:!0}):c.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-gray-500",children:"Restoring Studio session…"});return c.jsxs(It,{basename:f,children:[c.jsx("div",{className:`App ${e?"dark":""}`,children:c.jsxs(Lt,{children:[c.jsx(Re,{path:"/setup",element:c.jsx(go,{})}),c.jsx(Re,{path:"/studio",element:x}),c.jsx(Re,{path:"/",element:c.jsx(et,{to:t&&u?"/studio":"/setup",replace:!0})})]})}),c.jsx(Rr,{position:"top-right",toastOptions:{duration:4e3,style:{background:e?"#374151":"#ffffff",color:e?"#f9fafb":"#111827",border:e?"1px solid #4b5563":"1px solid #e5e7eb"},success:{duration:3e3,iconTheme:{primary:"#10b981",secondary:e?"#374151":"#ffffff"}},error:{duration:5e3,iconTheme:{primary:"#ef4444",secondary:e?"#374151":"#ffffff"}}}})]})}const vo=Bt.createRoot(document.getElementById("root"));vo.render(c.jsx(B.StrictMode,{children:c.jsx(bo,{})}));export{Xe as A,jn as F,Se as V,Nt as a,Ro as b,Do as c,No as d,tn as e,za as f,Mn as g,ko as h,_o as i,c as j,Ao as k,To as l,$o as m,Y as n,jo as o,So as p,Oo as q,Eo as s,me as u}; diff --git a/src/agentomatic/studio/static/assets/index-CUex9gTG.css b/src/agentomatic/studio/static/assets/index-CUex9gTG.css new file mode 100644 index 00000000..16c9a0ba --- /dev/null +++ b/src/agentomatic/studio/static/assets/index-CUex9gTG.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:Inter,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Monaco,Consolas,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.inset-3{inset:.75rem}.inset-y-0{top:0;bottom:0}.bottom-1\/4{bottom:25%}.bottom-2{bottom:.5rem}.bottom-4{bottom:1rem}.bottom-full{bottom:100%}.left-0{left:0}.left-1\/2{left:50%}.left-1\/4{left:25%}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-1\/4{right:25%}.right-2{right:.5rem}.right-4{right:1rem}.top-0{top:0}.top-1\/2{top:50%}.top-1\/4{top:25%}.top-2{top:.5rem}.top-4{top:1rem}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[999998\]{z-index:999998}.z-\[999999\]{z-index:999999}.order-1{order:1}.order-2{order:2}.m-2{margin:.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-1{margin-left:.25rem}.ml-1\.5{margin-left:.375rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-1\.5{margin-right:.375rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-20{height:5rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.h-96{height:24rem}.h-full{height:100%}.h-screen{height:100vh}.max-h-32{max-height:8rem}.max-h-36{max-height:9rem}.max-h-40{max-height:10rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-80{max-height:20rem}.max-h-96{max-height:24rem}.max-h-\[85vh\]{max-height:85vh}.min-h-0{min-height:0px}.min-h-14{min-height:3.5rem}.min-h-16{min-height:4rem}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-80{width:20rem}.w-96{width:24rem}.w-\[480px\]{width:480px}.w-auto{width:auto}.w-full{width:100%}.w-px{width:1px}.w-screen{width:100vw}.min-w-0{min-width:0px}.min-w-\[16px\]{min-width:16px}.min-w-\[32rem\]{min-width:32rem}.min-w-\[44rem\]{min-width:44rem}.min-w-\[4rem\]{min-width:4rem}.min-w-max{min-width:max-content}.max-w-28{max-width:7rem}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-\[13rem\]{max-width:13rem}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-\[1\.5\]{flex:1.5}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.animate-fade-in{animation:fadeIn .5s ease-in-out}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-grab{cursor:grab}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;user-select:none}.resize-none{resize:none}.resize-y{resize:vertical}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-1\.5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.375rem * var(--tw-space-x-reverse));margin-left:calc(.375rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1.25rem * var(--tw-space-x-reverse));margin-left:calc(1.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 231 235 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-center{align-self:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-3xl{border-radius:1.5rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-t-xl{border-top-left-radius:.75rem;border-top-right-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-amber-400{--tw-border-opacity: 1;border-color:rgb(251 191 36 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-700{--tw-border-opacity: 1;border-color:rgb(180 83 9 / var(--tw-border-opacity, 1))}.border-amber-800{--tw-border-opacity: 1;border-color:rgb(146 64 14 / var(--tw-border-opacity, 1))}.border-amber-900{--tw-border-opacity: 1;border-color:rgb(120 53 15 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-300{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.border-blue-400{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-blue-700{--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.border-blue-900\/70{border-color:#1e3a8ab3}.border-blue-900\/80{border-color:#1e3a8acc}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-700{--tw-border-opacity: 1;border-color:rgb(4 120 87 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-500{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.border-gray-600{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-600{--tw-border-opacity: 1;border-color:rgb(22 163 74 / var(--tw-border-opacity, 1))}.border-green-700{--tw-border-opacity: 1;border-color:rgb(21 128 61 / var(--tw-border-opacity, 1))}.border-indigo-500{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.border-orange-500{--tw-border-opacity: 1;border-color:rgb(249 115 22 / var(--tw-border-opacity, 1))}.border-pink-500{--tw-border-opacity: 1;border-color:rgb(236 72 153 / var(--tw-border-opacity, 1))}.border-purple-200{--tw-border-opacity: 1;border-color:rgb(233 213 255 / var(--tw-border-opacity, 1))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-700{--tw-border-opacity: 1;border-color:rgb(126 34 206 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-700{--tw-border-opacity: 1;border-color:rgb(185 28 28 / var(--tw-border-opacity, 1))}.border-red-800{--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.border-teal-500{--tw-border-opacity: 1;border-color:rgb(20 184 166 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-violet-200{--tw-border-opacity: 1;border-color:rgb(221 214 254 / var(--tw-border-opacity, 1))}.border-violet-700{--tw-border-opacity: 1;border-color:rgb(109 40 217 / var(--tw-border-opacity, 1))}.border-violet-800\/70{border-color:#5b21b6b3}.border-l-gray-200{--tw-border-opacity: 1;border-left-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-l-gray-600{--tw-border-opacity: 1;border-left-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/95{background-color:#fffbebf2}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-900{--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.bg-amber-900\/40{background-color:#78350f66}.bg-amber-900\/60{background-color:#78350f99}.bg-amber-950\/30{background-color:#451a034d}.bg-amber-950\/40{background-color:#451a0366}.bg-amber-950\/95{background-color:#451a03f2}.bg-black\/10{background-color:#0000001a}.bg-black\/30{background-color:#0000004d}.bg-black\/35{background-color:#00000059}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.bg-blue-300{--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity, 1))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-50\/70{background-color:#eff6ffb3}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-600\/20{background-color:#2563eb33}.bg-blue-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.bg-blue-800{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.bg-blue-900{--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.bg-blue-900\/20{background-color:#1e3a8a33}.bg-blue-900\/30{background-color:#1e3a8a4d}.bg-blue-900\/40{background-color:#1e3a8a66}.bg-blue-900\/50{background-color:#1e3a8a80}.bg-blue-900\/60{background-color:#1e3a8a99}.bg-blue-950\/20{background-color:#17255433}.bg-blue-950\/30{background-color:#1725544d}.bg-blue-950\/60{background-color:#17255499}.bg-current{background-color:currentColor}.bg-cyan-100{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-900{--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.bg-emerald-900\/60{background-color:#064e3b99}.bg-emerald-900\/80{background-color:#064e3bcc}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-50\/50{background-color:#f9fafb80}.bg-gray-50\/70{background-color:#f9fafbb3}.bg-gray-50\/80{background-color:#f9fafbcc}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-700\/50{background-color:#37415180}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/30{background-color:#1f29374d}.bg-gray-800\/40{background-color:#1f293766}.bg-gray-800\/50{background-color:#1f293780}.bg-gray-800\/80{background-color:#1f2937cc}.bg-gray-800\/90{background-color:#1f2937e6}.bg-gray-800\/95{background-color:#1f2937f2}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-900\/40{background-color:#11182766}.bg-gray-900\/50{background-color:#11182780}.bg-gray-950{--tw-bg-opacity: 1;background-color:rgb(3 7 18 / var(--tw-bg-opacity, 1))}.bg-gray-950\/35{background-color:#03071259}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-50\/90{background-color:#f0fdf4e6}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-green-900{--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.bg-green-900\/30{background-color:#14532d4d}.bg-green-900\/40{background-color:#14532d66}.bg-green-900\/60{background-color:#14532d99}.bg-green-900\/90{background-color:#14532de6}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-indigo-400{--tw-bg-opacity: 1;background-color:rgb(129 140 248 / var(--tw-bg-opacity, 1))}.bg-indigo-600{--tw-bg-opacity: 1;background-color:rgb(79 70 229 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-pink-100{--tw-bg-opacity: 1;background-color:rgb(252 231 243 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-900{--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.bg-purple-900\/40{background-color:#581c8766}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-red-700{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.bg-red-900{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.bg-red-900\/30{background-color:#7f1d1d4d}.bg-red-900\/40{background-color:#7f1d1d66}.bg-red-900\/50{background-color:#7f1d1d80}.bg-red-900\/60{background-color:#7f1d1d99}.bg-red-950\/40{background-color:#450a0a66}.bg-red-950\/50{background-color:#450a0a80}.bg-teal-100{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.bg-teal-50{--tw-bg-opacity: 1;background-color:rgb(240 253 250 / var(--tw-bg-opacity, 1))}.bg-teal-950{--tw-bg-opacity: 1;background-color:rgb(4 47 46 / var(--tw-bg-opacity, 1))}.bg-violet-100{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.bg-violet-50{--tw-bg-opacity: 1;background-color:rgb(245 243 255 / var(--tw-bg-opacity, 1))}.bg-violet-50\/50{background-color:#f5f3ff80}.bg-violet-50\/60{background-color:#f5f3ff99}.bg-violet-500{--tw-bg-opacity: 1;background-color:rgb(139 92 246 / var(--tw-bg-opacity, 1))}.bg-violet-600{--tw-bg-opacity: 1;background-color:rgb(124 58 237 / var(--tw-bg-opacity, 1))}.bg-violet-800{--tw-bg-opacity: 1;background-color:rgb(91 33 182 / var(--tw-bg-opacity, 1))}.bg-violet-900{--tw-bg-opacity: 1;background-color:rgb(76 29 149 / var(--tw-bg-opacity, 1))}.bg-violet-950\/20{background-color:#2e106533}.bg-violet-950\/25{background-color:#2e106540}.bg-violet-950\/50{background-color:#2e106580}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/20{background-color:#fff3}.bg-white\/50{background-color:#ffffff80}.bg-white\/60{background-color:#fff9}.bg-white\/75{background-color:#ffffffbf}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-600{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity, 1))}.bg-yellow-900{--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.bg-yellow-900\/30{background-color:#713f124d}.bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.20\)_1px\,transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.2) 1px,transparent 0)}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-100{--tw-gradient-from: #dbeafe var(--tw-gradient-from-position);--tw-gradient-to: rgb(219 234 254 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-800{--tw-gradient-from: #1f2937 var(--tw-gradient-from-position);--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-900{--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-100{--tw-gradient-from: #dcfce7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 252 231 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500{--tw-gradient-from: #22c55e var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-600{--tw-gradient-from: #16a34a var(--tw-gradient-from-position);--tw-gradient-to: rgb(22 163 74 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-600{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-gray-700{--tw-gradient-to: rgb(55 65 81 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #374151 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-gray-800{--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #1f2937 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-50{--tw-gradient-to: rgb(238 242 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #eef2ff var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-500{--tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #6366f1 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-purple-600{--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #9333ea var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-white{--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #fff var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-blue-100{--tw-gradient-to: #dbeafe var(--tw-gradient-to-position)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-blue-600{--tw-gradient-to: #2563eb var(--tw-gradient-to-position)}.to-gray-800{--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.to-gray-900{--tw-gradient-to: #111827 var(--tw-gradient-to-position)}.to-indigo-600{--tw-gradient-to: #4f46e5 var(--tw-gradient-to-position)}.to-purple-100{--tw-gradient-to: #f3e8ff var(--tw-gradient-to-position)}.to-purple-50{--tw-gradient-to: #faf5ff var(--tw-gradient-to-position)}.to-purple-500{--tw-gradient-to: #a855f7 var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.to-red-700{--tw-gradient-to: #b91c1c var(--tw-gradient-to-position)}.bg-\[size\:18px_18px\]{background-size:18px 18px}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pb-6{padding-bottom:1.5rem}.pb-8{padding-bottom:2rem}.pl-0{padding-left:0}.pl-10{padding-left:2.5rem}.pr-1{padding-right:.25rem}.pr-14{padding-right:3.5rem}.pr-4{padding-right:1rem}.pt-2{padding-top:.5rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:JetBrains Mono,Monaco,Consolas,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity, 1))}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-500{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-950{--tw-text-opacity: 1;color:rgb(69 26 3 / var(--tw-text-opacity, 1))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-300\/70{color:#93c5fdb3}.text-blue-300\/80{color:#93c5fdcc}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-700\/70{color:#1d4ed8b3}.text-blue-700\/80{color:#1d4ed8cc}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-cyan-500{--tw-text-opacity: 1;color:rgb(6 182 212 / var(--tw-text-opacity, 1))}.text-cyan-600{--tw-text-opacity: 1;color:rgb(8 145 178 / var(--tw-text-opacity, 1))}.text-cyan-700{--tw-text-opacity: 1;color:rgb(14 116 144 / var(--tw-text-opacity, 1))}.text-emerald-200{--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-500{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-200{--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.text-green-300{--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-indigo-500{--tw-text-opacity: 1;color:rgb(99 102 241 / var(--tw-text-opacity, 1))}.text-indigo-700{--tw-text-opacity: 1;color:rgb(67 56 202 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-500{--tw-text-opacity: 1;color:rgb(236 72 153 / var(--tw-text-opacity, 1))}.text-pink-700{--tw-text-opacity: 1;color:rgb(190 24 93 / var(--tw-text-opacity, 1))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-200{--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-teal-200{--tw-text-opacity: 1;color:rgb(153 246 228 / var(--tw-text-opacity, 1))}.text-teal-500{--tw-text-opacity: 1;color:rgb(20 184 166 / var(--tw-text-opacity, 1))}.text-teal-700{--tw-text-opacity: 1;color:rgb(15 118 110 / var(--tw-text-opacity, 1))}.text-teal-800{--tw-text-opacity: 1;color:rgb(17 94 89 / var(--tw-text-opacity, 1))}.text-violet-200{--tw-text-opacity: 1;color:rgb(221 214 254 / var(--tw-text-opacity, 1))}.text-violet-400{--tw-text-opacity: 1;color:rgb(167 139 250 / var(--tw-text-opacity, 1))}.text-violet-500{--tw-text-opacity: 1;color:rgb(139 92 246 / var(--tw-text-opacity, 1))}.text-violet-600{--tw-text-opacity: 1;color:rgb(124 58 237 / var(--tw-text-opacity, 1))}.text-violet-800{--tw-text-opacity: 1;color:rgb(91 33 182 / var(--tw-text-opacity, 1))}.text-violet-900{--tw-text-opacity: 1;color:rgb(76 29 149 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.no-underline{text-decoration-line:none}.underline-offset-2{text-underline-offset:2px}.placeholder-gray-400::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.accent-blue-500{accent-color:#3b82f6}.accent-blue-600{accent-color:#2563eb}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-25{opacity:.25}.opacity-5{opacity:.05}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-gray-200\/50{--tw-shadow-color: rgb(229 231 235 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-900\/20{--tw-shadow-color: rgb(17 24 39 / .2);--tw-shadow: var(--tw-shadow-colored)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-blue-400{--tw-ring-opacity: 1;--tw-ring-color: rgb(96 165 250 / var(--tw-ring-opacity, 1))}.ring-blue-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-blue-600{--tw-ring-opacity: 1;--tw-ring-color: rgb(37 99 235 / var(--tw-ring-opacity, 1))}.ring-green-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.ring-red-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.blur-3xl{--tw-blur: blur(64px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.delay-1000{transition-delay:1s}.delay-300{transition-delay:.3s}.delay-500{transition-delay:.5s}.delay-700{transition-delay:.7s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}:root{--bg-primary: #ffffff;--bg-secondary: #f9fafb;--text-primary: #111827;--text-secondary: #6b7280;--border-color: #e5e7eb}[data-theme=dark]{--bg-primary: #1f2937;--bg-secondary: #111827;--text-primary: #f9fafb;--text-secondary: #9ca3af;--border-color: #374151}*{box-sizing:border-box}body{margin:0;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:var(--bg-secondary);color:var(--text-primary);transition:background-color .3s ease,color .3s ease}code{font-family:JetBrains Mono,source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:var(--bg-secondary)}::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.dark ::-webkit-scrollbar-track{background:#374151}.dark ::-webkit-scrollbar-thumb{background:#6b7280}.dark ::-webkit-scrollbar-thumb:hover{background:#9ca3af}.graph-svg{background:transparent;border-radius:8px;transition:background-color .3s ease}.graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.1));transition:all .2s ease}.dark .graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.3))}.graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-canvas{background:var(--bg-secondary);position:relative;transition:background-color .3s ease}.dark .graph-canvas{background:#1f2937}.graph-canvas:before{display:none}.minimap{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border-bottom:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.control-panel{transition:all .3s cubic-bezier(.4,0,.2,1)}.control-panel.collapsed{transform:translate(100%)}@keyframes nodeSelect{0%{transform:scale(1)}50%{transform:scale(1.05)}to{transform:scale(1)}}.node-selected{animation:nodeSelect .3s ease-out}@keyframes pathFlow{0%{stroke-dashoffset:20}to{stroke-dashoffset:0}}.execution-path{stroke-dasharray:5,5;animation:pathFlow 1s linear infinite}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);box-shadow:0 2px 4px #3b82f633;transition:all .2s ease}.btn-primary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #3b82f64d}.btn-secondary{background:linear-gradient(135deg,#6b7280,#4b5563);box-shadow:0 2px 4px #6b728033;transition:all .2s ease}.btn-secondary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #6b72804d}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);box-shadow:0 2px 4px #ef444433;transition:all .2s ease}.btn-danger:hover{transform:translateY(-1px);box-shadow:0 4px 8px #ef44444d}.status-indicator{position:relative;overflow:hidden;transition:all .3s ease}.status-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);transition:left .5s}.dark .status-indicator:before{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator.active:before{left:100%}.line-clamp-2{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.monaco-editor{border-radius:8px}@keyframes typing{0%{width:0}to{width:100%}}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .3s ease-out}.typing-animation{overflow:hidden;border-right:2px solid #0ea5e9;white-space:nowrap;animation:typing 2s steps(40,end),blink-caret .75s step-end infinite}@keyframes blink-caret{0%,to{border-color:transparent}50%{border-color:#0ea5e9}}.spinner{border:2px solid var(--bg-secondary);border-top:2px solid #0ea5e9;border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.message-bubble{max-width:80%;word-wrap:break-word;animation:slideUp .3s ease-out;transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#0ea5e9,#0284c7);color:#fff;margin-left:auto}.message-bubble.assistant{background:var(--bg-primary);border:1px solid var(--border-color);color:var(--text-primary);transition:background-color .3s ease,border-color .3s ease,color .3s ease}.graph-node{background:var(--bg-primary);border:2px solid var(--border-color);border-radius:8px;padding:12px;min-width:120px;text-align:center;font-weight:500;transition:all .2s ease}.graph-node:hover{border-color:#0ea5e9;box-shadow:0 4px 12px #0ea5e926}.dark .graph-node:hover{box-shadow:0 4px 12px #0ea5e94d}.graph-node.active{border-color:#0ea5e9;background:#f0f9ff;box-shadow:0 4px 12px #0ea5e940}.dark .graph-node.active{background:#1e3a8a;box-shadow:0 4px 12px #0ea5e966}.graph-node.error{border-color:#ef4444;background:#fef2f2}.dark .graph-node.error{background:#7f1d1d}.Resizer{background:var(--border-color);opacity:.5;z-index:1;box-sizing:border-box;background-clip:padding-box;transition:all .2s ease}.Resizer:hover{opacity:1;background:#0ea5e9}.Resizer.horizontal{height:4px;margin:-2px 0;cursor:row-resize;width:100%}.Resizer.vertical{width:4px;margin:0 -2px;cursor:col-resize;height:100%}.react-json-view{background-color:var(--bg-secondary)!important;border-radius:8px;padding:16px;transition:background-color .3s ease}.mermaid{text-align:center}.mermaid svg{max-width:100%;height:auto}.sidebar-container{transition:width .3s cubic-bezier(.4,0,.2,1)}.sidebar-collapsed{width:0;overflow:hidden}.sidebar-expanded{width:320px}@keyframes slideIn{0%{transform:translate(-100%);opacity:0}to{transform:translate(0);opacity:1}}.graph-canvas{background-image:none;transition:background-color .3s ease}.graph-node-group{transition:opacity .2s ease}.graph-node-group:hover{opacity:.95}.graph-node-group:hover .graph-node-rect{filter:brightness(1.08) drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.2) drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-node-rect{transition:stroke-width .2s ease,filter .2s ease}.selection-ring{animation:selection-dash 3s linear infinite}@keyframes selection-dash{0%{stroke-dashoffset:0}to{stroke-dashoffset:16}}.graph-edge-path{transition:stroke .3s ease-in-out,stroke-width .3s ease-in-out;filter:drop-shadow(0 1px 2px rgba(0,0,0,.1))}.dark .graph-edge-path{filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}.graph-edge-arrow{transition:fill .3s ease-in-out}.status-indicator{transition:all .3s ease-in-out}.status-indicator.active{background:linear-gradient(90deg,#3b82f6,#1d4ed8,#3b82f6);background-size:200px 100%;animation:shimmer 2s infinite linear;color:#fff}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);transition:all .2s ease-in-out}.btn-primary:hover{background:linear-gradient(135deg,#1d4ed8,#1e40af);transform:translateY(-1px);box-shadow:0 4px 12px #3b82f666}.btn-secondary{background:linear-gradient(135deg,#8b5cf6,#7c3aed);transition:all .2s ease-in-out}.btn-secondary:hover{background:linear-gradient(135deg,#7c3aed,#6d28d9);transform:translateY(-1px);box-shadow:0 4px 12px #8b5cf666}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);transition:all .2s ease-in-out}.btn-danger:hover{background:linear-gradient(135deg,#dc2626,#b91c1c);transform:translateY(-1px);box-shadow:0 4px 12px #ef444466}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffffff2}.dark .toolbar{background:#1f2937f2}.message-bubble{transition:all .2s ease-in-out;animation:fadeIn .3s ease-out}.animate-fade-in{animation:fadeIn .5s ease-out}.animate-slide-in{animation:slideIn .3s ease-out}.transition-width{transition:width .3s ease-in-out}.transition-height{transition:height .3s ease-in-out}.message-bubble{transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:#fff}.message-bubble.assistant{background:var(--bg-secondary);color:var(--text-primary);border:1px solid var(--border-color);transition:background-color .3s ease,color .3s ease,border-color .3s ease}@keyframes fade-in{0%{opacity:0}to{opacity:1}}@keyframes slide-in-right{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-left{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}.animate-fade-in{animation:fade-in .3s ease-out}.animate-shimmer{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,transparent,rgba(255,255,255,.2),transparent);background-size:200px 100%}.dark .animate-shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator{transition:all .2s ease}.status-indicator.active{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,#3b82f6,#60a5fa,#3b82f6);background-size:200% 100%;color:#fff}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffc}.dark .toolbar{background:#1f2937cc}.graph-node-group{transition:all .2s ease}.graph-node-group:hover .graph-node-rect{filter:brightness(1.1)}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.3)}.graph-edge-path,.graph-edge-arrow{transition:all .2s ease}.selection-ring{animation:dash 1.5s linear infinite}@keyframes dash{to{stroke-dashoffset:-16}}.graph-canvas{background-image:none}.graph-svg{transition:all .2s ease}.backdrop-blur-sm{-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}.backdrop-blur-md{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.card-hover{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-hover:hover{transform:translateY(-2px);box-shadow:0 10px 25px #0000001a}.dark .card-hover:hover{box-shadow:0 10px 25px #0000004d}.status-badge{position:relative;overflow:hidden}.status-badge:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.3),transparent);transition:left .6s}.status-badge:hover:before{left:100%}.focus-ring:focus{outline:none;ring:2px;ring-color:#3b82f6;ring-offset:2px}.debug-scrollbar::-webkit-scrollbar{width:8px;height:8px}.debug-scrollbar::-webkit-scrollbar-track{background:transparent;border-radius:4px}.debug-scrollbar::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:4px;-webkit-transition:background-color .3s ease;transition:background-color .3s ease}.debug-scrollbar::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.gradient-border{position:relative;background:linear-gradient(45deg,#3b82f6,#8b5cf6,#06b6d4);border-radius:12px;padding:1px}.gradient-border-content{background:var(--bg-primary);border-radius:11px;padding:1rem}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromBottom{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromLeft{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}@keyframes slideInFromRight{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes fadeInScale{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}@keyframes pulseGlow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-slide-in-top{animation:slideInFromTop .4s ease-out}.animate-slide-in-bottom{animation:slideInFromBottom .4s ease-out}.animate-slide-in-left{animation:slideInFromLeft .3s ease-out}.animate-slide-in-right{animation:slideInFromRight .3s ease-out}.animate-fade-in-scale{animation:fadeInScale .3s ease-out}.animate-pulse-glow{animation:pulseGlow 2s ease-in-out infinite}.auto-focus-indicator{animation:fadeInScale .5s ease-out,pulseGlow 2s ease-in-out infinite .5s}.context-switch-notification{animation:slideInFromTop .5s ease-out,fadeInScale .3s ease-out}.graph-node-focused{animation:pulseGlow 1s ease-in-out;filter:drop-shadow(0 0 20px rgba(59,130,246,.6))}.graph-view-transition{transition:all .8s cubic-bezier(.4,0,.2,1)}@keyframes executionFlow{0%{stroke-dashoffset:20;opacity:.5}50%{opacity:1}to{stroke-dashoffset:0;opacity:.8}}.execution-path-animated{stroke-dasharray:10,5;animation:executionFlow 2s ease-in-out infinite}.skeleton{background:linear-gradient(90deg,var(--bg-secondary) 25%,var(--border-color) 50%,var(--bg-secondary) 75%);background-size:200% 100%;animation:skeleton-loading 1.5s infinite}@keyframes skeleton-loading{0%{background-position:200% 0}to{background-position:-200% 0}}.graph-overlay{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);background:#ffffffe6;border:1px solid rgba(255,255,255,.2);box-shadow:0 8px 32px #0000001a}.dark .graph-overlay{background:#1f2937e6;border:1px solid rgba(75,85,99,.3);box-shadow:0 8px 32px #0000004d}.metric-card{background:linear-gradient(135deg,var(--bg-primary) 0%,var(--bg-secondary) 100%);border:1px solid var(--border-color);transition:all .3s ease}.metric-card:hover{transform:translateY(-2px);box-shadow:0 8px 25px #0000001a;border-color:#3b82f6}.dark .metric-card:hover{box-shadow:0 8px 25px #0000004d}.log-level-error{background:linear-gradient(135deg,#fef2f2,#fee2e2);border-color:#fecaca;color:#991b1b}.dark .log-level-error{background:linear-gradient(135deg,#7f1d1d4d,#991b1b33);border-color:#7f1d1d;color:#fca5a5}.log-level-warn{background:linear-gradient(135deg,#fffbeb,#fef3c7);border-color:#fde68a;color:#92400e}.dark .log-level-warn{background:linear-gradient(135deg,#92400e4d,#b4530933);border-color:#92400e;color:#fcd34d}.log-level-info{background:linear-gradient(135deg,#eff6ff,#dbeafe);border-color:#bfdbfe;color:#1e40af}.dark .log-level-info{background:linear-gradient(135deg,#1e40af4d,#2563eb33);border-color:#1e40af;color:#93c5fd}.log-level-debug{background:linear-gradient(135deg,#f9fafb,#f3f4f6);border-color:#e5e7eb;color:#374151}.dark .log-level-debug{background:linear-gradient(135deg,#3741514d,#4b556333);border-color:#374151;color:#d1d5db}@keyframes pulse-glow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-pulse-glow{animation:pulse-glow 3s ease-in-out infinite}@keyframes slide-in-left{0%{opacity:0;transform:translate(-50px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-right{0%{opacity:0;transform:translate(50px)}to{opacity:1;transform:translate(0)}}@keyframes fade-in-up{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.animate-slide-in-left{animation:slide-in-left .8s ease-out}.animate-slide-in-right{animation:slide-in-right .8s ease-out}.animate-fade-in-up{animation:fade-in-up .6s ease-out;animation-fill-mode:both}.stagger-1{animation-delay:.1s}.stagger-2{animation-delay:.3s}.stagger-3{animation-delay:.5s}.stagger-4{animation-delay:.7s}.custom-scrollbar::-webkit-scrollbar{width:6px}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:3px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afcc}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#6b728080}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#6b7280cc}.bg-grid-pattern{background-image:linear-gradient(rgba(0,0,0,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(0,0,0,.1) 1px,transparent 1px);background-size:20px 20px}.dark .bg-grid-pattern{background-image:linear-gradient(rgba(255,255,255,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.1) 1px,transparent 1px)}.btn-hover-lift{transition:all .3s cubic-bezier(.4,0,.2,1)}.btn-hover-lift:hover{transform:translateY(-2px);box-shadow:0 10px 25px #00000026}.dark .btn-hover-lift:hover{box-shadow:0 10px 25px #0000004d}.glass-morphism{-webkit-backdrop-filter:blur(16px) saturate(180%);backdrop-filter:blur(16px) saturate(180%);background-color:#ffffffbf;border:1px solid rgba(255,255,255,.125)}.dark .glass-morphism{background-color:#1f2937bf;border:1px solid rgba(255,255,255,.125)}.status-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes status-glow{0%,to{box-shadow:0 0 5px currentColor}50%{box-shadow:0 0 20px currentColor,0 0 30px currentColor}}.status-glow{animation:status-glow 2s ease-in-out infinite}.input-focus-ring:focus{outline:none;box-shadow:0 0 0 3px #3b82f61a;border-color:#3b82f6}.dark .input-focus-ring:focus{box-shadow:0 0 0 3px #3b82f633}.card-interactive{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-interactive:hover{transform:translateY(-4px);box-shadow:0 20px 25px -5px #0000001a,0 10px 10px -5px #0000000a}.dark .card-interactive:hover{box-shadow:0 20px 25px -5px #00000040,0 10px 10px -5px #0000001a}@keyframes shimmer{0%{background-position:-200px 0}to{background-position:calc(200px + 100%) 0}}.shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);background-size:200px 100%;animation:shimmer 1.5s infinite}.dark .shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}@keyframes float{0%,to{transform:translateY(0)}50%{transform:translateY(-20px)}}.animate-float{animation:float 6s ease-in-out infinite}.animate-float-delayed{animation:float 6s ease-in-out infinite;animation-delay:2s}.radio-custom{appearance:none;width:1.5rem;height:1.5rem;border:2px solid currentColor;border-radius:50%;position:relative;transition:all .2s ease}.radio-custom:checked:before{content:"";position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:.75rem;height:.75rem;background:currentColor;border-radius:50%;animation:radio-check .2s ease-out}@keyframes radio-check{0%{transform:translate(-50%,-50%) scale(0)}to{transform:translate(-50%,-50%) scale(1)}}.gradient-text{background:linear-gradient(135deg,#667eea,#764ba2);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.dark .gradient-text{background:linear-gradient(135deg,#60a5fa,#a78bfa);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.log-entry-selected{transform:scale(1.02);box-shadow:0 8px 25px #3b82f626}.log-entry-hover{transform:translateY(-1px);box-shadow:0 4px 12px #0000001a}.node-highlighted{filter:drop-shadow(0 0 12px rgba(245,158,11,.6));animation:pulse-highlight 2s infinite}@keyframes pulse-highlight{0%,to{filter:drop-shadow(0 0 12px rgba(245,158,11,.6))}50%{filter:drop-shadow(0 0 20px rgba(245,158,11,.8))}}.custom-scrollbar::-webkit-scrollbar{width:8px}.custom-scrollbar::-webkit-scrollbar-track{background:transparent}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afb3}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#4b556380}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#4b5563b3}.log-data-json{background:linear-gradient(135deg,#3b82f60d,#10b9810d)}.dark .log-data-json{background:linear-gradient(135deg,#3b82f61a,#10b9811a)}.performance-card{background:linear-gradient(135deg,#6366f11a,#a855f71a);border:1px solid rgba(99,102,241,.2)}.dark .performance-card{background:linear-gradient(135deg,#6366f126,#a855f726);border:1px solid rgba(99,102,241,.3)}.state-update-indicator{position:relative;overflow:hidden}.state-update-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(59,130,246,.2),transparent);animation:shimmer 2s infinite}@keyframes shimmer{0%{left:-100%}to{left:100%}}.typing-indicator{display:flex;align-items:center;gap:4px;padding:8px 16px}.typing-indicator .dot{width:8px;height:8px;border-radius:50%;background-color:#6b7280;animation:typingBounce 1.4s infinite ease-in-out both}.dark .typing-indicator .dot{background-color:#9ca3af}.typing-indicator .dot:nth-child(1){animation-delay:-.32s}.typing-indicator .dot:nth-child(2){animation-delay:-.16s}.typing-indicator .dot:nth-child(3){animation-delay:0s}@keyframes typingBounce{0%,80%,to{transform:scale(.6);opacity:.4}40%{transform:scale(1);opacity:1}}.copy-btn{opacity:0;transition:all .2s ease;cursor:pointer}.message-bubble:hover .copy-btn,.copy-btn:focus{opacity:1}.copy-btn:active{transform:scale(.9)}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6,#e5e7eb 75%);background-size:200% 100%;animation:skeletonShimmer 1.5s ease-in-out infinite;border-radius:8px}.dark .skeleton{background:linear-gradient(90deg,#374151 25%,#4b5563,#374151 75%);background-size:200% 100%}@keyframes skeletonShimmer{0%{background-position:200% 0}to{background-position:-200% 0}}.zoom-controls{display:flex;align-items:center;gap:4px;padding:4px;border-radius:12px;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);box-shadow:0 2px 8px #00000026}.zoom-controls button{width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:8px;font-size:14px;font-weight:600;transition:all .15s ease;border:none;cursor:pointer}.zoom-controls button:hover{transform:scale(1.1)}.zoom-controls button:active{transform:scale(.95)}@keyframes livePulse{0%{box-shadow:0 0 #10b98166}70%{box-shadow:0 0 0 6px #10b98100}to{box-shadow:0 0 #10b98100}}.live-pulse{animation:livePulse 2s infinite}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-blue-400:hover{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.hover\:border-blue-500:hover{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.hover\:border-gray-200:hover{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.hover\:border-gray-600:hover{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-50:hover{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-900\/60:hover{background-color:#78350f99}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-800:hover{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-900\/60:hover{background-color:#1e3a8a99}.hover\:bg-blue-950\/40:hover{background-color:#17255466}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-500:hover{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600\/50:hover{background-color:#4b556380}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700\/50:hover{background-color:#37415180}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\:bg-red-200:hover{--tw-bg-opacity: 1;background-color:rgb(254 202 202 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-red-800:hover{--tw-bg-opacity: 1;background-color:rgb(153 27 27 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900:hover{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900\/40:hover{background-color:#7f1d1d66}.hover\:bg-violet-100:hover{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-200:hover{--tw-bg-opacity: 1;background-color:rgb(221 214 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-700:hover{--tw-bg-opacity: 1;background-color:rgb(109 40 217 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-900\/70:hover{background-color:#4c1d95b3}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/50:hover{background-color:#ffffff80}.hover\:bg-yellow-700:hover{--tw-bg-opacity: 1;background-color:rgb(161 98 7 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-50:hover{--tw-bg-opacity: .5}.hover\:from-blue-700:hover{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-indigo-700:hover{--tw-gradient-to: #4338ca var(--tw-gradient-to-position)}.hover\:text-blue-300:hover{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-700:hover{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.hover\:text-gray-200:hover{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-red-600:hover{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-2xl:hover{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-xl:hover{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:bg-gray-600:focus{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.focus\:bg-white:focus{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-red-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:transform-none:disabled{transform:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-gray-300:disabled{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-400:disabled{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-600:disabled{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group:hover .group-hover\:opacity-100{opacity:1}.group:hover .group-hover\:shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.dark\:divide-gray-700:is(.dark *)>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(55 65 81 / var(--tw-divide-opacity, 1))}.dark\:border-blue-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(30 64 175 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:bg-amber-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900\/30:is(.dark *){background-color:#1e3a8a4d}.dark\:bg-cyan-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity, 1))}.dark\:bg-emerald-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700\/50:is(.dark *){background-color:#37415180}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800\/75:is(.dark *){background-color:#1f2937bf}.dark\:bg-gray-900\/40:is(.dark *){background-color:#11182766}.dark\:bg-indigo-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(49 46 129 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(124 45 18 / var(--tw-bg-opacity, 1))}.dark\:bg-pink-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(131 24 67 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.dark\:bg-red-950\/40:is(.dark *){background-color:#450a0a66}.dark\:bg-teal-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(19 78 74 / var(--tw-bg-opacity, 1))}.dark\:bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.12\)_1px\,transparent_0\)\]:is(.dark *){background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.12) 1px,transparent 0)}.dark\:text-amber-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-cyan-300:is(.dark *){--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.dark\:text-emerald-300:is(.dark *){--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-indigo-300:is(.dark *){--tw-text-opacity: 1;color:rgb(165 180 252 / var(--tw-text-opacity, 1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.dark\:text-orange-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.dark\:text-pink-300:is(.dark *){--tw-text-opacity: 1;color:rgb(249 168 212 / var(--tw-text-opacity, 1))}.dark\:text-purple-300:is(.dark *){--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-teal-300:is(.dark *){--tw-text-opacity: 1;color:rgb(94 234 212 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-amber-950:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(69 26 3 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:m-4{margin:1rem}.sm\:block{display:block}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:w-52{width:13rem}.sm\:w-56{width:14rem}.sm\:w-auto{width:auto}.sm\:max-w-36{max-width:9rem}.sm\:max-w-none{max-width:none}.sm\:flex-none{flex:none}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-start{align-items:flex-start}.sm\:items-end{align-items:flex-end}.sm\:items-center{align-items:center}.sm\:justify-end{justify-content:flex-end}.sm\:justify-center{justify-content:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:.5rem}.sm\:space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.sm\:p-3{padding:.75rem}.sm\:p-4{padding:1rem}.sm\:p-5{padding:1.25rem}.sm\:p-6{padding:1.5rem}.sm\:px-4{padding-left:1rem;padding-right:1rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}}@media(min-width:768px){.md\:static{position:static}.md\:flex{display:flex}.md\:hidden{display:none}.md\:w-72{width:18rem}.md\:max-w-44{max-width:11rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}@media(min-width:1024px){.lg\:block{display:block}.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:w-1\/2{width:50%}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.lg\:p-12{padding:3rem}.lg\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media(min-width:1280px){.xl\:static{position:static}.xl\:ml-6{margin-left:1.5rem}.xl\:flex{display:flex}.xl\:hidden{display:none}.xl\:w-2\/5{width:40%}.xl\:w-3\/5{width:60%}.xl\:w-80{width:20rem}.xl\:w-96{width:24rem}.xl\:flex-shrink-0{flex-shrink:0}.xl\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.xl\:rounded-none{border-radius:0}.xl\:border-y-0{border-top-width:0px;border-bottom-width:0px}.xl\:border-l{border-left-width:1px}.xl\:border-r-0{border-right-width:0px}}@media(min-width:1536px){.\32xl\:block{display:block}.\32xl\:flex{display:flex}.\32xl\:hidden{display:none}.\32xl\:grid-cols-\[minmax\(26rem\,0\.85fr\)_minmax\(32rem\,1\.15fr\)\]{grid-template-columns:minmax(26rem,.85fr) minmax(32rem,1.15fr)}} diff --git a/src/agentomatic/studio/static/assets/index-Czmh8XoR.css b/src/agentomatic/studio/static/assets/index-Czmh8XoR.css deleted file mode 100644 index 15ea15e9..00000000 --- a/src/agentomatic/studio/static/assets/index-Czmh8XoR.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:Inter,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Monaco,Consolas,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.inset-3{inset:.75rem}.inset-y-0{top:0;bottom:0}.bottom-1\/4{bottom:25%}.bottom-2{bottom:.5rem}.bottom-4{bottom:1rem}.bottom-full{bottom:100%}.left-0{left:0}.left-1\/2{left:50%}.left-1\/4{left:25%}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-1\/4{right:25%}.right-2{right:.5rem}.right-4{right:1rem}.top-0{top:0}.top-1\/2{top:50%}.top-1\/4{top:25%}.top-2{top:.5rem}.top-4{top:1rem}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[999998\]{z-index:999998}.z-\[999999\]{z-index:999999}.order-1{order:1}.order-2{order:2}.m-2{margin:.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-1{margin-left:.25rem}.ml-1\.5{margin-left:.375rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-1\.5{margin-right:.375rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-20{height:5rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.h-96{height:24rem}.h-full{height:100%}.h-screen{height:100vh}.max-h-32{max-height:8rem}.max-h-36{max-height:9rem}.max-h-40{max-height:10rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-80{max-height:20rem}.max-h-96{max-height:24rem}.max-h-\[85vh\]{max-height:85vh}.min-h-0{min-height:0px}.min-h-14{min-height:3.5rem}.min-h-16{min-height:4rem}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-80{width:20rem}.w-96{width:24rem}.w-\[480px\]{width:480px}.w-auto{width:auto}.w-full{width:100%}.w-px{width:1px}.w-screen{width:100vw}.min-w-0{min-width:0px}.min-w-\[16px\]{min-width:16px}.min-w-\[32rem\]{min-width:32rem}.min-w-\[44rem\]{min-width:44rem}.min-w-\[4rem\]{min-width:4rem}.min-w-max{min-width:-webkit-max-content;min-width:max-content}.max-w-28{max-width:7rem}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-\[13rem\]{max-width:13rem}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-\[1\.5\]{flex:1.5}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.animate-fade-in{animation:fadeIn .5s ease-in-out}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-grab{cursor:grab}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;user-select:none}.resize-none{resize:none}.resize-y{resize:vertical}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-1\.5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.375rem * var(--tw-space-x-reverse));margin-left:calc(.375rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-5>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1.25rem * var(--tw-space-x-reverse));margin-left:calc(1.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 231 235 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-center{align-self:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-3xl{border-radius:1.5rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-t-xl{border-top-left-radius:.75rem;border-top-right-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-amber-400{--tw-border-opacity: 1;border-color:rgb(251 191 36 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-700{--tw-border-opacity: 1;border-color:rgb(180 83 9 / var(--tw-border-opacity, 1))}.border-amber-800{--tw-border-opacity: 1;border-color:rgb(146 64 14 / var(--tw-border-opacity, 1))}.border-amber-900{--tw-border-opacity: 1;border-color:rgb(120 53 15 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-300{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.border-blue-400{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-blue-700{--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.border-blue-900\/70{border-color:#1e3a8ab3}.border-blue-900\/80{border-color:#1e3a8acc}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-700{--tw-border-opacity: 1;border-color:rgb(4 120 87 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-500{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.border-gray-600{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-600{--tw-border-opacity: 1;border-color:rgb(22 163 74 / var(--tw-border-opacity, 1))}.border-green-700{--tw-border-opacity: 1;border-color:rgb(21 128 61 / var(--tw-border-opacity, 1))}.border-indigo-500{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.border-orange-500{--tw-border-opacity: 1;border-color:rgb(249 115 22 / var(--tw-border-opacity, 1))}.border-pink-500{--tw-border-opacity: 1;border-color:rgb(236 72 153 / var(--tw-border-opacity, 1))}.border-purple-200{--tw-border-opacity: 1;border-color:rgb(233 213 255 / var(--tw-border-opacity, 1))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-700{--tw-border-opacity: 1;border-color:rgb(126 34 206 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-700{--tw-border-opacity: 1;border-color:rgb(185 28 28 / var(--tw-border-opacity, 1))}.border-red-800{--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.border-teal-500{--tw-border-opacity: 1;border-color:rgb(20 184 166 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-violet-200{--tw-border-opacity: 1;border-color:rgb(221 214 254 / var(--tw-border-opacity, 1))}.border-violet-700{--tw-border-opacity: 1;border-color:rgb(109 40 217 / var(--tw-border-opacity, 1))}.border-violet-800\/70{border-color:#5b21b6b3}.border-l-gray-200{--tw-border-opacity: 1;border-left-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-l-gray-600{--tw-border-opacity: 1;border-left-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/95{background-color:#fffbebf2}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-900{--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.bg-amber-900\/40{background-color:#78350f66}.bg-amber-900\/60{background-color:#78350f99}.bg-amber-950\/30{background-color:#451a034d}.bg-amber-950\/40{background-color:#451a0366}.bg-amber-950\/95{background-color:#451a03f2}.bg-black\/10{background-color:#0000001a}.bg-black\/30{background-color:#0000004d}.bg-black\/35{background-color:#00000059}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.bg-blue-300{--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity, 1))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-50\/70{background-color:#eff6ffb3}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-600\/20{background-color:#2563eb33}.bg-blue-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.bg-blue-800{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.bg-blue-900{--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.bg-blue-900\/20{background-color:#1e3a8a33}.bg-blue-900\/30{background-color:#1e3a8a4d}.bg-blue-900\/40{background-color:#1e3a8a66}.bg-blue-900\/50{background-color:#1e3a8a80}.bg-blue-900\/60{background-color:#1e3a8a99}.bg-blue-950\/20{background-color:#17255433}.bg-blue-950\/30{background-color:#1725544d}.bg-blue-950\/60{background-color:#17255499}.bg-current{background-color:currentColor}.bg-cyan-100{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-900{--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.bg-emerald-900\/60{background-color:#064e3b99}.bg-emerald-900\/80{background-color:#064e3bcc}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-50\/50{background-color:#f9fafb80}.bg-gray-50\/70{background-color:#f9fafbb3}.bg-gray-50\/80{background-color:#f9fafbcc}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-700\/50{background-color:#37415180}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/30{background-color:#1f29374d}.bg-gray-800\/40{background-color:#1f293766}.bg-gray-800\/50{background-color:#1f293780}.bg-gray-800\/80{background-color:#1f2937cc}.bg-gray-800\/90{background-color:#1f2937e6}.bg-gray-800\/95{background-color:#1f2937f2}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-900\/40{background-color:#11182766}.bg-gray-900\/50{background-color:#11182780}.bg-gray-950{--tw-bg-opacity: 1;background-color:rgb(3 7 18 / var(--tw-bg-opacity, 1))}.bg-gray-950\/35{background-color:#03071259}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-50\/90{background-color:#f0fdf4e6}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-green-900{--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.bg-green-900\/30{background-color:#14532d4d}.bg-green-900\/40{background-color:#14532d66}.bg-green-900\/60{background-color:#14532d99}.bg-green-900\/90{background-color:#14532de6}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-indigo-400{--tw-bg-opacity: 1;background-color:rgb(129 140 248 / var(--tw-bg-opacity, 1))}.bg-indigo-600{--tw-bg-opacity: 1;background-color:rgb(79 70 229 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-pink-100{--tw-bg-opacity: 1;background-color:rgb(252 231 243 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-900{--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.bg-purple-900\/40{background-color:#581c8766}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-red-700{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.bg-red-900{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.bg-red-900\/30{background-color:#7f1d1d4d}.bg-red-900\/40{background-color:#7f1d1d66}.bg-red-900\/50{background-color:#7f1d1d80}.bg-red-900\/60{background-color:#7f1d1d99}.bg-red-950\/40{background-color:#450a0a66}.bg-red-950\/50{background-color:#450a0a80}.bg-teal-100{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.bg-teal-50{--tw-bg-opacity: 1;background-color:rgb(240 253 250 / var(--tw-bg-opacity, 1))}.bg-teal-950{--tw-bg-opacity: 1;background-color:rgb(4 47 46 / var(--tw-bg-opacity, 1))}.bg-violet-100{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.bg-violet-50{--tw-bg-opacity: 1;background-color:rgb(245 243 255 / var(--tw-bg-opacity, 1))}.bg-violet-50\/50{background-color:#f5f3ff80}.bg-violet-50\/60{background-color:#f5f3ff99}.bg-violet-500{--tw-bg-opacity: 1;background-color:rgb(139 92 246 / var(--tw-bg-opacity, 1))}.bg-violet-600{--tw-bg-opacity: 1;background-color:rgb(124 58 237 / var(--tw-bg-opacity, 1))}.bg-violet-800{--tw-bg-opacity: 1;background-color:rgb(91 33 182 / var(--tw-bg-opacity, 1))}.bg-violet-900{--tw-bg-opacity: 1;background-color:rgb(76 29 149 / var(--tw-bg-opacity, 1))}.bg-violet-950\/20{background-color:#2e106533}.bg-violet-950\/25{background-color:#2e106540}.bg-violet-950\/50{background-color:#2e106580}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/20{background-color:#fff3}.bg-white\/50{background-color:#ffffff80}.bg-white\/60{background-color:#fff9}.bg-white\/75{background-color:#ffffffbf}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-600{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity, 1))}.bg-yellow-900{--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.bg-yellow-900\/30{background-color:#713f124d}.bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.20\)_1px\,transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.2) 1px,transparent 0)}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-100{--tw-gradient-from: #dbeafe var(--tw-gradient-from-position);--tw-gradient-to: rgb(219 234 254 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-800{--tw-gradient-from: #1f2937 var(--tw-gradient-from-position);--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-900{--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-100{--tw-gradient-from: #dcfce7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 252 231 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500{--tw-gradient-from: #22c55e var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-600{--tw-gradient-from: #16a34a var(--tw-gradient-from-position);--tw-gradient-to: rgb(22 163 74 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-600{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-gray-700{--tw-gradient-to: rgb(55 65 81 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #374151 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-gray-800{--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #1f2937 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-50{--tw-gradient-to: rgb(238 242 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #eef2ff var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-500{--tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #6366f1 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-purple-600{--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #9333ea var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-white{--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #fff var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-blue-100{--tw-gradient-to: #dbeafe var(--tw-gradient-to-position)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-blue-600{--tw-gradient-to: #2563eb var(--tw-gradient-to-position)}.to-gray-800{--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.to-gray-900{--tw-gradient-to: #111827 var(--tw-gradient-to-position)}.to-indigo-600{--tw-gradient-to: #4f46e5 var(--tw-gradient-to-position)}.to-purple-100{--tw-gradient-to: #f3e8ff var(--tw-gradient-to-position)}.to-purple-50{--tw-gradient-to: #faf5ff var(--tw-gradient-to-position)}.to-purple-500{--tw-gradient-to: #a855f7 var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.to-red-700{--tw-gradient-to: #b91c1c var(--tw-gradient-to-position)}.bg-\[size\:18px_18px\]{background-size:18px 18px}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pb-6{padding-bottom:1.5rem}.pb-8{padding-bottom:2rem}.pl-0{padding-left:0}.pl-10{padding-left:2.5rem}.pr-1{padding-right:.25rem}.pr-14{padding-right:3.5rem}.pr-4{padding-right:1rem}.pt-2{padding-top:.5rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:JetBrains Mono,Monaco,Consolas,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity, 1))}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-500{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-950{--tw-text-opacity: 1;color:rgb(69 26 3 / var(--tw-text-opacity, 1))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-300\/70{color:#93c5fdb3}.text-blue-300\/80{color:#93c5fdcc}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-700\/70{color:#1d4ed8b3}.text-blue-700\/80{color:#1d4ed8cc}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-cyan-500{--tw-text-opacity: 1;color:rgb(6 182 212 / var(--tw-text-opacity, 1))}.text-cyan-600{--tw-text-opacity: 1;color:rgb(8 145 178 / var(--tw-text-opacity, 1))}.text-cyan-700{--tw-text-opacity: 1;color:rgb(14 116 144 / var(--tw-text-opacity, 1))}.text-emerald-200{--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-500{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-200{--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.text-green-300{--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-indigo-500{--tw-text-opacity: 1;color:rgb(99 102 241 / var(--tw-text-opacity, 1))}.text-indigo-700{--tw-text-opacity: 1;color:rgb(67 56 202 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-500{--tw-text-opacity: 1;color:rgb(236 72 153 / var(--tw-text-opacity, 1))}.text-pink-700{--tw-text-opacity: 1;color:rgb(190 24 93 / var(--tw-text-opacity, 1))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-200{--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-teal-200{--tw-text-opacity: 1;color:rgb(153 246 228 / var(--tw-text-opacity, 1))}.text-teal-500{--tw-text-opacity: 1;color:rgb(20 184 166 / var(--tw-text-opacity, 1))}.text-teal-700{--tw-text-opacity: 1;color:rgb(15 118 110 / var(--tw-text-opacity, 1))}.text-teal-800{--tw-text-opacity: 1;color:rgb(17 94 89 / var(--tw-text-opacity, 1))}.text-violet-200{--tw-text-opacity: 1;color:rgb(221 214 254 / var(--tw-text-opacity, 1))}.text-violet-400{--tw-text-opacity: 1;color:rgb(167 139 250 / var(--tw-text-opacity, 1))}.text-violet-500{--tw-text-opacity: 1;color:rgb(139 92 246 / var(--tw-text-opacity, 1))}.text-violet-600{--tw-text-opacity: 1;color:rgb(124 58 237 / var(--tw-text-opacity, 1))}.text-violet-800{--tw-text-opacity: 1;color:rgb(91 33 182 / var(--tw-text-opacity, 1))}.text-violet-900{--tw-text-opacity: 1;color:rgb(76 29 149 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.no-underline{-webkit-text-decoration-line:none;text-decoration-line:none}.underline-offset-2{text-underline-offset:2px}.placeholder-gray-400::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.accent-blue-500{accent-color:#3b82f6}.accent-blue-600{accent-color:#2563eb}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-25{opacity:.25}.opacity-5{opacity:.05}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-gray-200\/50{--tw-shadow-color: rgb(229 231 235 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-900\/20{--tw-shadow-color: rgb(17 24 39 / .2);--tw-shadow: var(--tw-shadow-colored)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-blue-400{--tw-ring-opacity: 1;--tw-ring-color: rgb(96 165 250 / var(--tw-ring-opacity, 1))}.ring-blue-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-blue-600{--tw-ring-opacity: 1;--tw-ring-color: rgb(37 99 235 / var(--tw-ring-opacity, 1))}.ring-green-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.ring-red-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.blur-3xl{--tw-blur: blur(64px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,fill,stroke,-webkit-text-decoration-color;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,-webkit-text-decoration-color;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.delay-1000{transition-delay:1s}.delay-300{transition-delay:.3s}.delay-500{transition-delay:.5s}.delay-700{transition-delay:.7s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}:root{--bg-primary: #ffffff;--bg-secondary: #f9fafb;--text-primary: #111827;--text-secondary: #6b7280;--border-color: #e5e7eb}[data-theme=dark]{--bg-primary: #1f2937;--bg-secondary: #111827;--text-primary: #f9fafb;--text-secondary: #9ca3af;--border-color: #374151}*{box-sizing:border-box}body{margin:0;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:var(--bg-secondary);color:var(--text-primary);transition:background-color .3s ease,color .3s ease}code{font-family:JetBrains Mono,source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:var(--bg-secondary)}::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.dark ::-webkit-scrollbar-track{background:#374151}.dark ::-webkit-scrollbar-thumb{background:#6b7280}.dark ::-webkit-scrollbar-thumb:hover{background:#9ca3af}.graph-svg{background:transparent;border-radius:8px;transition:background-color .3s ease}.graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.1));transition:all .2s ease}.dark .graph-node-rect{filter:drop-shadow(0 2px 4px rgba(0,0,0,.3))}.graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-rect:hover{filter:drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-canvas{background:var(--bg-secondary);position:relative;transition:background-color .3s ease}.dark .graph-canvas{background:#1f2937}.graph-canvas:before{display:none}.minimap{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:var(--bg-primary);border-bottom:1px solid var(--border-color);transition:background-color .3s ease,border-color .3s ease}.control-panel{transition:all .3s cubic-bezier(.4,0,.2,1)}.control-panel.collapsed{transform:translate(100%)}@keyframes nodeSelect{0%{transform:scale(1)}50%{transform:scale(1.05)}to{transform:scale(1)}}.node-selected{animation:nodeSelect .3s ease-out}@keyframes pathFlow{0%{stroke-dashoffset:20}to{stroke-dashoffset:0}}.execution-path{stroke-dasharray:5,5;animation:pathFlow 1s linear infinite}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);box-shadow:0 2px 4px #3b82f633;transition:all .2s ease}.btn-primary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #3b82f64d}.btn-secondary{background:linear-gradient(135deg,#6b7280,#4b5563);box-shadow:0 2px 4px #6b728033;transition:all .2s ease}.btn-secondary:hover{transform:translateY(-1px);box-shadow:0 4px 8px #6b72804d}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);box-shadow:0 2px 4px #ef444433;transition:all .2s ease}.btn-danger:hover{transform:translateY(-1px);box-shadow:0 4px 8px #ef44444d}.status-indicator{position:relative;overflow:hidden;transition:all .3s ease}.status-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);transition:left .5s}.dark .status-indicator:before{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator.active:before{left:100%}.line-clamp-2{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.monaco-editor{border-radius:8px}@keyframes typing{0%{width:0}to{width:100%}}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .3s ease-out}.typing-animation{overflow:hidden;border-right:2px solid #0ea5e9;white-space:nowrap;animation:typing 2s steps(40,end),blink-caret .75s step-end infinite}@keyframes blink-caret{0%,to{border-color:transparent}50%{border-color:#0ea5e9}}.spinner{border:2px solid var(--bg-secondary);border-top:2px solid #0ea5e9;border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.message-bubble{max-width:80%;word-wrap:break-word;animation:slideUp .3s ease-out;transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#0ea5e9,#0284c7);color:#fff;margin-left:auto}.message-bubble.assistant{background:var(--bg-primary);border:1px solid var(--border-color);color:var(--text-primary);transition:background-color .3s ease,border-color .3s ease,color .3s ease}.graph-node{background:var(--bg-primary);border:2px solid var(--border-color);border-radius:8px;padding:12px;min-width:120px;text-align:center;font-weight:500;transition:all .2s ease}.graph-node:hover{border-color:#0ea5e9;box-shadow:0 4px 12px #0ea5e926}.dark .graph-node:hover{box-shadow:0 4px 12px #0ea5e94d}.graph-node.active{border-color:#0ea5e9;background:#f0f9ff;box-shadow:0 4px 12px #0ea5e940}.dark .graph-node.active{background:#1e3a8a;box-shadow:0 4px 12px #0ea5e966}.graph-node.error{border-color:#ef4444;background:#fef2f2}.dark .graph-node.error{background:#7f1d1d}.Resizer{background:var(--border-color);opacity:.5;z-index:1;box-sizing:border-box;background-clip:padding-box;transition:all .2s ease}.Resizer:hover{opacity:1;background:#0ea5e9}.Resizer.horizontal{height:4px;margin:-2px 0;cursor:row-resize;width:100%}.Resizer.vertical{width:4px;margin:0 -2px;cursor:col-resize;height:100%}.react-json-view{background-color:var(--bg-secondary)!important;border-radius:8px;padding:16px;transition:background-color .3s ease}.mermaid{text-align:center}.mermaid svg{max-width:100%;height:auto}.sidebar-container{transition:width .3s cubic-bezier(.4,0,.2,1)}.sidebar-collapsed{width:0;overflow:hidden}.sidebar-expanded{width:320px}@keyframes slideIn{0%{transform:translate(-100%);opacity:0}to{transform:translate(0);opacity:1}}.graph-canvas{background-image:none;transition:background-color .3s ease}.graph-node-group{transition:opacity .2s ease}.graph-node-group:hover{opacity:.95}.graph-node-group:hover .graph-node-rect{filter:brightness(1.08) drop-shadow(0 4px 8px rgba(0,0,0,.15))}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.2) drop-shadow(0 4px 8px rgba(0,0,0,.4))}.graph-node-rect{transition:stroke-width .2s ease,filter .2s ease}.selection-ring{animation:selection-dash 3s linear infinite}@keyframes selection-dash{0%{stroke-dashoffset:0}to{stroke-dashoffset:16}}.graph-edge-path{transition:stroke .3s ease-in-out,stroke-width .3s ease-in-out;filter:drop-shadow(0 1px 2px rgba(0,0,0,.1))}.dark .graph-edge-path{filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}.graph-edge-arrow{transition:fill .3s ease-in-out}.status-indicator{transition:all .3s ease-in-out}.status-indicator.active{background:linear-gradient(90deg,#3b82f6,#1d4ed8,#3b82f6);background-size:200px 100%;animation:shimmer 2s infinite linear;color:#fff}.btn-primary{background:linear-gradient(135deg,#3b82f6,#1d4ed8);transition:all .2s ease-in-out}.btn-primary:hover{background:linear-gradient(135deg,#1d4ed8,#1e40af);transform:translateY(-1px);box-shadow:0 4px 12px #3b82f666}.btn-secondary{background:linear-gradient(135deg,#8b5cf6,#7c3aed);transition:all .2s ease-in-out}.btn-secondary:hover{background:linear-gradient(135deg,#7c3aed,#6d28d9);transform:translateY(-1px);box-shadow:0 4px 12px #8b5cf666}.btn-danger{background:linear-gradient(135deg,#ef4444,#dc2626);transition:all .2s ease-in-out}.btn-danger:hover{background:linear-gradient(135deg,#dc2626,#b91c1c);transform:translateY(-1px);box-shadow:0 4px 12px #ef444466}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffffff2}.dark .toolbar{background:#1f2937f2}.message-bubble{transition:all .2s ease-in-out;animation:fadeIn .3s ease-out}.animate-fade-in{animation:fadeIn .5s ease-out}.animate-slide-in{animation:slideIn .3s ease-out}.transition-width{transition:width .3s ease-in-out}.transition-height{transition:height .3s ease-in-out}.message-bubble{transition:all .2s ease}.message-bubble.user{background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:#fff}.message-bubble.assistant{background:var(--bg-secondary);color:var(--text-primary);border:1px solid var(--border-color);transition:background-color .3s ease,color .3s ease,border-color .3s ease}@keyframes fade-in{0%{opacity:0}to{opacity:1}}@keyframes slide-in-right{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-left{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}.animate-fade-in{animation:fade-in .3s ease-out}.animate-shimmer{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,transparent,rgba(255,255,255,.2),transparent);background-size:200px 100%}.dark .animate-shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}.status-indicator{transition:all .2s ease}.status-indicator.active{animation:shimmer 2s infinite linear;background:linear-gradient(90deg,#3b82f6,#60a5fa,#3b82f6);background-size:200% 100%;color:#fff}.toolbar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#fffc}.dark .toolbar{background:#1f2937cc}.graph-node-group{transition:all .2s ease}.graph-node-group:hover .graph-node-rect{filter:brightness(1.1)}.dark .graph-node-group:hover .graph-node-rect{filter:brightness(1.3)}.graph-edge-path,.graph-edge-arrow{transition:all .2s ease}.selection-ring{animation:dash 1.5s linear infinite}@keyframes dash{to{stroke-dashoffset:-16}}.graph-canvas{background-image:none}.graph-svg{transition:all .2s ease}.backdrop-blur-sm{-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}.backdrop-blur-md{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.card-hover{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-hover:hover{transform:translateY(-2px);box-shadow:0 10px 25px #0000001a}.dark .card-hover:hover{box-shadow:0 10px 25px #0000004d}.status-badge{position:relative;overflow:hidden}.status-badge:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.3),transparent);transition:left .6s}.status-badge:hover:before{left:100%}.focus-ring:focus{outline:none;ring:2px;ring-color:#3b82f6;ring-offset:2px}.debug-scrollbar::-webkit-scrollbar{width:8px;height:8px}.debug-scrollbar::-webkit-scrollbar-track{background:transparent;border-radius:4px}.debug-scrollbar::-webkit-scrollbar-thumb{background:var(--text-secondary);border-radius:4px;-webkit-transition:background-color .3s ease;transition:background-color .3s ease}.debug-scrollbar::-webkit-scrollbar-thumb:hover{background:var(--text-primary)}.gradient-border{position:relative;background:linear-gradient(45deg,#3b82f6,#8b5cf6,#06b6d4);border-radius:12px;padding:1px}.gradient-border-content{background:var(--bg-primary);border-radius:11px;padding:1rem}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromBottom{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideInFromLeft{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}@keyframes slideInFromRight{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes fadeInScale{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}@keyframes pulseGlow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-slide-in-top{animation:slideInFromTop .4s ease-out}.animate-slide-in-bottom{animation:slideInFromBottom .4s ease-out}.animate-slide-in-left{animation:slideInFromLeft .3s ease-out}.animate-slide-in-right{animation:slideInFromRight .3s ease-out}.animate-fade-in-scale{animation:fadeInScale .3s ease-out}.animate-pulse-glow{animation:pulseGlow 2s ease-in-out infinite}.auto-focus-indicator{animation:fadeInScale .5s ease-out,pulseGlow 2s ease-in-out infinite .5s}.context-switch-notification{animation:slideInFromTop .5s ease-out,fadeInScale .3s ease-out}.graph-node-focused{animation:pulseGlow 1s ease-in-out;filter:drop-shadow(0 0 20px rgba(59,130,246,.6))}.graph-view-transition{transition:all .8s cubic-bezier(.4,0,.2,1)}@keyframes executionFlow{0%{stroke-dashoffset:20;opacity:.5}50%{opacity:1}to{stroke-dashoffset:0;opacity:.8}}.execution-path-animated{stroke-dasharray:10,5;animation:executionFlow 2s ease-in-out infinite}.skeleton{background:linear-gradient(90deg,var(--bg-secondary) 25%,var(--border-color) 50%,var(--bg-secondary) 75%);background-size:200% 100%;animation:skeleton-loading 1.5s infinite}@keyframes skeleton-loading{0%{background-position:200% 0}to{background-position:-200% 0}}.graph-overlay{-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);background:#ffffffe6;border:1px solid rgba(255,255,255,.2);box-shadow:0 8px 32px #0000001a}.dark .graph-overlay{background:#1f2937e6;border:1px solid rgba(75,85,99,.3);box-shadow:0 8px 32px #0000004d}.metric-card{background:linear-gradient(135deg,var(--bg-primary) 0%,var(--bg-secondary) 100%);border:1px solid var(--border-color);transition:all .3s ease}.metric-card:hover{transform:translateY(-2px);box-shadow:0 8px 25px #0000001a;border-color:#3b82f6}.dark .metric-card:hover{box-shadow:0 8px 25px #0000004d}.log-level-error{background:linear-gradient(135deg,#fef2f2,#fee2e2);border-color:#fecaca;color:#991b1b}.dark .log-level-error{background:linear-gradient(135deg,#7f1d1d4d,#991b1b33);border-color:#7f1d1d;color:#fca5a5}.log-level-warn{background:linear-gradient(135deg,#fffbeb,#fef3c7);border-color:#fde68a;color:#92400e}.dark .log-level-warn{background:linear-gradient(135deg,#92400e4d,#b4530933);border-color:#92400e;color:#fcd34d}.log-level-info{background:linear-gradient(135deg,#eff6ff,#dbeafe);border-color:#bfdbfe;color:#1e40af}.dark .log-level-info{background:linear-gradient(135deg,#1e40af4d,#2563eb33);border-color:#1e40af;color:#93c5fd}.log-level-debug{background:linear-gradient(135deg,#f9fafb,#f3f4f6);border-color:#e5e7eb;color:#374151}.dark .log-level-debug{background:linear-gradient(135deg,#3741514d,#4b556333);border-color:#374151;color:#d1d5db}@keyframes pulse-glow{0%,to{box-shadow:0 0 20px #3b82f64d}50%{box-shadow:0 0 40px #3b82f699}}.animate-pulse-glow{animation:pulse-glow 3s ease-in-out infinite}@keyframes slide-in-left{0%{opacity:0;transform:translate(-50px)}to{opacity:1;transform:translate(0)}}@keyframes slide-in-right{0%{opacity:0;transform:translate(50px)}to{opacity:1;transform:translate(0)}}@keyframes fade-in-up{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.animate-slide-in-left{animation:slide-in-left .8s ease-out}.animate-slide-in-right{animation:slide-in-right .8s ease-out}.animate-fade-in-up{animation:fade-in-up .6s ease-out;animation-fill-mode:both}.stagger-1{animation-delay:.1s}.stagger-2{animation-delay:.3s}.stagger-3{animation-delay:.5s}.stagger-4{animation-delay:.7s}.custom-scrollbar::-webkit-scrollbar{width:6px}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:3px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afcc}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#6b728080}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#6b7280cc}.bg-grid-pattern{background-image:linear-gradient(rgba(0,0,0,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(0,0,0,.1) 1px,transparent 1px);background-size:20px 20px}.dark .bg-grid-pattern{background-image:linear-gradient(rgba(255,255,255,.1) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.1) 1px,transparent 1px)}.btn-hover-lift{transition:all .3s cubic-bezier(.4,0,.2,1)}.btn-hover-lift:hover{transform:translateY(-2px);box-shadow:0 10px 25px #00000026}.dark .btn-hover-lift:hover{box-shadow:0 10px 25px #0000004d}.glass-morphism{-webkit-backdrop-filter:blur(16px) saturate(180%);backdrop-filter:blur(16px) saturate(180%);background-color:#ffffffbf;border:1px solid rgba(255,255,255,.125)}.dark .glass-morphism{background-color:#1f2937bf;border:1px solid rgba(255,255,255,.125)}.status-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes status-glow{0%,to{box-shadow:0 0 5px currentColor}50%{box-shadow:0 0 20px currentColor,0 0 30px currentColor}}.status-glow{animation:status-glow 2s ease-in-out infinite}.input-focus-ring:focus{outline:none;box-shadow:0 0 0 3px #3b82f61a;border-color:#3b82f6}.dark .input-focus-ring:focus{box-shadow:0 0 0 3px #3b82f633}.card-interactive{transition:all .3s cubic-bezier(.4,0,.2,1)}.card-interactive:hover{transform:translateY(-4px);box-shadow:0 20px 25px -5px #0000001a,0 10px 10px -5px #0000000a}.dark .card-interactive:hover{box-shadow:0 20px 25px -5px #00000040,0 10px 10px -5px #0000001a}@keyframes shimmer{0%{background-position:-200px 0}to{background-position:calc(200px + 100%) 0}}.shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.4),transparent);background-size:200px 100%;animation:shimmer 1.5s infinite}.dark .shimmer{background:linear-gradient(90deg,transparent,rgba(255,255,255,.1),transparent)}@keyframes float{0%,to{transform:translateY(0)}50%{transform:translateY(-20px)}}.animate-float{animation:float 6s ease-in-out infinite}.animate-float-delayed{animation:float 6s ease-in-out infinite;animation-delay:2s}.radio-custom{-webkit-appearance:none;appearance:none;width:1.5rem;height:1.5rem;border:2px solid currentColor;border-radius:50%;position:relative;transition:all .2s ease}.radio-custom:checked:before{content:"";position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:.75rem;height:.75rem;background:currentColor;border-radius:50%;animation:radio-check .2s ease-out}@keyframes radio-check{0%{transform:translate(-50%,-50%) scale(0)}to{transform:translate(-50%,-50%) scale(1)}}.gradient-text{background:linear-gradient(135deg,#667eea,#764ba2);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.dark .gradient-text{background:linear-gradient(135deg,#60a5fa,#a78bfa);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.log-entry-selected{transform:scale(1.02);box-shadow:0 8px 25px #3b82f626}.log-entry-hover{transform:translateY(-1px);box-shadow:0 4px 12px #0000001a}.node-highlighted{filter:drop-shadow(0 0 12px rgba(245,158,11,.6));animation:pulse-highlight 2s infinite}@keyframes pulse-highlight{0%,to{filter:drop-shadow(0 0 12px rgba(245,158,11,.6))}50%{filter:drop-shadow(0 0 20px rgba(245,158,11,.8))}}.custom-scrollbar::-webkit-scrollbar{width:8px}.custom-scrollbar::-webkit-scrollbar-track{background:transparent}.custom-scrollbar::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#9ca3afb3}.dark .custom-scrollbar::-webkit-scrollbar-thumb{background:#4b556380}.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#4b5563b3}.log-data-json{background:linear-gradient(135deg,#3b82f60d,#10b9810d)}.dark .log-data-json{background:linear-gradient(135deg,#3b82f61a,#10b9811a)}.performance-card{background:linear-gradient(135deg,#6366f11a,#a855f71a);border:1px solid rgba(99,102,241,.2)}.dark .performance-card{background:linear-gradient(135deg,#6366f126,#a855f726);border:1px solid rgba(99,102,241,.3)}.state-update-indicator{position:relative;overflow:hidden}.state-update-indicator:before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(59,130,246,.2),transparent);animation:shimmer 2s infinite}@keyframes shimmer{0%{left:-100%}to{left:100%}}.typing-indicator{display:flex;align-items:center;gap:4px;padding:8px 16px}.typing-indicator .dot{width:8px;height:8px;border-radius:50%;background-color:#6b7280;animation:typingBounce 1.4s infinite ease-in-out both}.dark .typing-indicator .dot{background-color:#9ca3af}.typing-indicator .dot:nth-child(1){animation-delay:-.32s}.typing-indicator .dot:nth-child(2){animation-delay:-.16s}.typing-indicator .dot:nth-child(3){animation-delay:0s}@keyframes typingBounce{0%,80%,to{transform:scale(.6);opacity:.4}40%{transform:scale(1);opacity:1}}.copy-btn{opacity:0;transition:all .2s ease;cursor:pointer}.message-bubble:hover .copy-btn,.copy-btn:focus{opacity:1}.copy-btn:active{transform:scale(.9)}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6,#e5e7eb 75%);background-size:200% 100%;animation:skeletonShimmer 1.5s ease-in-out infinite;border-radius:8px}.dark .skeleton{background:linear-gradient(90deg,#374151 25%,#4b5563,#374151 75%);background-size:200% 100%}@keyframes skeletonShimmer{0%{background-position:200% 0}to{background-position:-200% 0}}.zoom-controls{display:flex;align-items:center;gap:4px;padding:4px;border-radius:12px;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);box-shadow:0 2px 8px #00000026}.zoom-controls button{width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:8px;font-size:14px;font-weight:600;transition:all .15s ease;border:none;cursor:pointer}.zoom-controls button:hover{transform:scale(1.1)}.zoom-controls button:active{transform:scale(.95)}@keyframes livePulse{0%{box-shadow:0 0 #10b98166}70%{box-shadow:0 0 0 6px #10b98100}to{box-shadow:0 0 #10b98100}}.live-pulse{animation:livePulse 2s infinite}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-blue-400:hover{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.hover\:border-blue-500:hover{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.hover\:border-gray-200:hover{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.hover\:border-gray-600:hover{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-50:hover{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-900\/60:hover{background-color:#78350f99}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-800:hover{--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-900\/60:hover{background-color:#1e3a8a99}.hover\:bg-blue-950\/40:hover{background-color:#17255466}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-500:hover{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600\/50:hover{background-color:#4b556380}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700\/50:hover{background-color:#37415180}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\:bg-red-200:hover{--tw-bg-opacity: 1;background-color:rgb(254 202 202 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-red-800:hover{--tw-bg-opacity: 1;background-color:rgb(153 27 27 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900:hover{--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.hover\:bg-red-900\/40:hover{background-color:#7f1d1d66}.hover\:bg-violet-100:hover{--tw-bg-opacity: 1;background-color:rgb(237 233 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-200:hover{--tw-bg-opacity: 1;background-color:rgb(221 214 254 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-700:hover{--tw-bg-opacity: 1;background-color:rgb(109 40 217 / var(--tw-bg-opacity, 1))}.hover\:bg-violet-900\/70:hover{background-color:#4c1d95b3}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/50:hover{background-color:#ffffff80}.hover\:bg-yellow-700:hover{--tw-bg-opacity: 1;background-color:rgb(161 98 7 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-50:hover{--tw-bg-opacity: .5}.hover\:from-blue-700:hover{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-indigo-700:hover{--tw-gradient-to: #4338ca var(--tw-gradient-to-position)}.hover\:text-blue-300:hover{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-700:hover{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.hover\:text-gray-200:hover{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-red-600:hover{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{-webkit-text-decoration-line:underline;text-decoration-line:underline}.hover\:shadow-2xl:hover{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-xl:hover{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:bg-gray-600:focus{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.focus\:bg-white:focus{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-red-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:transform-none:disabled{transform:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-gray-300:disabled{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-400:disabled{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.disabled\:bg-gray-600:disabled{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group:hover .group-hover\:opacity-100{opacity:1}.group:hover .group-hover\:shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.dark\:divide-gray-700:is(.dark *)>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(55 65 81 / var(--tw-divide-opacity, 1))}.dark\:border-blue-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(30 64 175 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:bg-amber-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900\/30:is(.dark *){background-color:#1e3a8a4d}.dark\:bg-cyan-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity, 1))}.dark\:bg-emerald-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(6 78 59 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700\/50:is(.dark *){background-color:#37415180}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800\/75:is(.dark *){background-color:#1f2937bf}.dark\:bg-gray-900\/40:is(.dark *){background-color:#11182766}.dark\:bg-indigo-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(49 46 129 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(124 45 18 / var(--tw-bg-opacity, 1))}.dark\:bg-pink-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(131 24 67 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.dark\:bg-red-950\/40:is(.dark *){background-color:#450a0a66}.dark\:bg-teal-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(19 78 74 / var(--tw-bg-opacity, 1))}.dark\:bg-\[radial-gradient\(circle_at_1px_1px\,rgba\(148\,163\,184\,0\.12\)_1px\,transparent_0\)\]:is(.dark *){background-image:radial-gradient(circle at 1px 1px,rgba(148,163,184,.12) 1px,transparent 0)}.dark\:text-amber-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-cyan-300:is(.dark *){--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.dark\:text-emerald-300:is(.dark *){--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-indigo-300:is(.dark *){--tw-text-opacity: 1;color:rgb(165 180 252 / var(--tw-text-opacity, 1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.dark\:text-orange-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.dark\:text-pink-300:is(.dark *){--tw-text-opacity: 1;color:rgb(249 168 212 / var(--tw-text-opacity, 1))}.dark\:text-purple-300:is(.dark *){--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-teal-300:is(.dark *){--tw-text-opacity: 1;color:rgb(94 234 212 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-amber-950:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(69 26 3 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:m-4{margin:1rem}.sm\:block{display:block}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:w-52{width:13rem}.sm\:w-56{width:14rem}.sm\:w-auto{width:auto}.sm\:max-w-36{max-width:9rem}.sm\:max-w-none{max-width:none}.sm\:flex-none{flex:none}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-start{align-items:flex-start}.sm\:items-end{align-items:flex-end}.sm\:items-center{align-items:center}.sm\:justify-end{justify-content:flex-end}.sm\:justify-center{justify-content:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:.5rem}.sm\:space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.sm\:p-3{padding:.75rem}.sm\:p-4{padding:1rem}.sm\:p-5{padding:1.25rem}.sm\:p-6{padding:1.5rem}.sm\:px-4{padding-left:1rem;padding-right:1rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}}@media(min-width:768px){.md\:static{position:static}.md\:flex{display:flex}.md\:hidden{display:none}.md\:w-72{width:18rem}.md\:max-w-44{max-width:11rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}@media(min-width:1024px){.lg\:block{display:block}.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:w-1\/2{width:50%}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.lg\:p-12{padding:3rem}.lg\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media(min-width:1280px){.xl\:static{position:static}.xl\:ml-6{margin-left:1.5rem}.xl\:flex{display:flex}.xl\:hidden{display:none}.xl\:w-2\/5{width:40%}.xl\:w-3\/5{width:60%}.xl\:w-80{width:20rem}.xl\:w-96{width:24rem}.xl\:flex-shrink-0{flex-shrink:0}.xl\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.xl\:rounded-none{border-radius:0}.xl\:border-y-0{border-top-width:0px;border-bottom-width:0px}.xl\:border-l{border-left-width:1px}.xl\:border-r-0{border-right-width:0px}}@media(min-width:1536px){.\32xl\:block{display:block}.\32xl\:flex{display:flex}.\32xl\:hidden{display:none}.\32xl\:grid-cols-\[minmax\(26rem\,0\.85fr\)_minmax\(32rem\,1\.15fr\)\]{grid-template-columns:minmax(26rem,.85fr) minmax(32rem,1.15fr)}} diff --git a/src/agentomatic/studio/static/index.html b/src/agentomatic/studio/static/index.html index de2d9502..44591304 100644 --- a/src/agentomatic/studio/static/index.html +++ b/src/agentomatic/studio/static/index.html @@ -14,10 +14,10 @@ /> Agentomatic Studio - + - + From 54ce4a0acac89176e979dfff70938d1ab57bd381 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 20:51:14 +0000 Subject: [PATCH 13/16] ci: keep pre-commit fixers off the synced Studio bundle The PR gate runs pre-commit on changed files. `trailing-whitespace` rewrote minified Studio chunks, which failed the gate. It would also have made the shipped files differ from the agentomatic-studio release tarball that sync-studio.yml installs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- .pre-commit-config.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 03466351..c91567db 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,8 @@ +# The Studio UI bundle is a build artifact synced from agentomatic-studio +# releases (sync-studio.yml). Whitespace fixers would rewrite its minified +# chunks, so the shipped files would no longer match the release tarball. +exclude: ^src/agentomatic/studio/static/ + repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 From 20eb8ae7ae6601bdb58761b2cf7590b23924af00 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 20:57:16 +0000 Subject: [PATCH 14/16] fix(deps): upgrade locked anyio, PyJWT, urllib3 and virtualenv past advisories MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `pip-audit` (the CI audit job and the release gate) failed on the locked set with 21 known vulnerabilities: * anyio 4.13.0 → 4.14.2 / 4.15.1 * PyJWT 2.13.0 → 2.15.1 * urllib3 2.7.0 → 2.8.0 * virtualenv 21.4.3 → 21.14.1 (python-discovery follows) PyJWT >= 2.14 fetches a JWKS through its own `build_opener(...)`, which refuses redirects, instead of `urllib.request.urlopen`. The JWT end-to-end test therefore stubs `OpenerDirector.open`, which both paths use. Production code is unaffected. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- tests/test_jwt_signature_e2e.py | 6 ++- uv.lock | 81 ++++++++++++++++++++++----------- 2 files changed, 59 insertions(+), 28 deletions(-) diff --git a/tests/test_jwt_signature_e2e.py b/tests/test_jwt_signature_e2e.py index 41769612..6a616656 100644 --- a/tests/test_jwt_signature_e2e.py +++ b/tests/test_jwt_signature_e2e.py @@ -87,12 +87,14 @@ def __enter__(self): def __exit__(self, *exc: object) -> None: return None - def _urlopen(url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003 + def _open(_opener, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003 target = getattr(url, "full_url", url) assert target == JWKS_URL, f"unexpected JWKS fetch: {target}" return _Response() - monkeypatch.setattr(urllib.request, "urlopen", _urlopen) + # Every urllib fetch goes through an opener: ``urlopen`` builds one, and + # PyJWT >= 2.14 builds its own (redirects refused) instead of calling it. + monkeypatch.setattr(urllib.request.OpenerDirector, "open", _open) class _HttpxResponse: status_code = 200 diff --git a/uv.lock b/uv.lock index f40cb16e..3a060f72 100644 --- a/uv.lock +++ b/uv.lock @@ -458,15 +458,35 @@ wheels = [ [[package]] name = "anyio" -version = "4.13.0" +version = "4.14.2" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version == '3.14.*'", + "python_full_version == '3.13.*'", + "python_full_version < '3.13'", +] dependencies = [ - { name = "idna" }, + { name = "idna", marker = "python_full_version < '3.15'" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/19/14/2c5dd9f512b66549ae92767a9c7b330ae88e1932ca57876909410251fe13/anyio-4.13.0.tar.gz", hash = "sha256:334b70e641fd2221c1505b3890c69882fe4a2df910cba14d97019b90b24439dc", size = 231622, upload-time = "2026-03-24T12:59:09.671Z" } +sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" }, + { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, +] + +[[package]] +name = "anyio" +version = "4.15.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.15'", +] +dependencies = [ + { name = "idna", marker = "python_full_version >= '3.15'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, ] [[package]] @@ -523,7 +543,8 @@ name = "asyncer" version = "0.0.17" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "sniffio" }, { name = "typing-extensions", marker = "python_full_version < '3.15'" }, ] @@ -1706,7 +1727,8 @@ name = "google-genai" version = "2.8.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "distro" }, { name = "google-auth", extra = ["requests"] }, { name = "httpx" }, @@ -1993,7 +2015,8 @@ name = "httpx" version = "0.28.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "certifi" }, { name = "httpcore" }, { name = "idna" }, @@ -2520,7 +2543,8 @@ name = "langsmith" version = "0.11.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "distro" }, { name = "httpx" }, { name = "orjson", marker = "platform_python_implementation != 'PyPy'" }, @@ -2772,7 +2796,8 @@ name = "mcp" version = "1.29.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "httpx" }, { name = "httpx-sse" }, { name = "jsonschema" }, @@ -3353,7 +3378,8 @@ name = "openai" version = "2.41.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "distro" }, { name = "httpx" }, { name = "jiter" }, @@ -4846,11 +4872,11 @@ wheels = [ [[package]] name = "pyjwt" -version = "2.13.0" +version = "2.15.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" } +sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, + { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" }, ] [package.optional-dependencies] @@ -5058,15 +5084,14 @@ wheels = [ [[package]] name = "python-discovery" -version = "1.4.2" +version = "1.6.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "filelock" }, - { name = "platformdirs" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0b/1a/cbbaf13b730abb0a16b964d984e19f2fe520c21a4dc664051359a3f5a9e7/python_discovery-1.4.2.tar.gz", hash = "sha256:8f3746c4b4968d22afbb97d36e1a0e5b66e6c0f297290f2e95f05b9b8bf18690", size = 70277, upload-time = "2026-06-11T16:10:42.383Z" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/57/250bd238b966cece44328235eb85290045d059265fdaf7527a3a958123db/python_discovery-1.6.1.tar.gz", hash = "sha256:cf87d3627dfb4412437fdd5b13eae402607722998d21567993aedbc59b23c15e", size = 84338, upload-time = "2026-09-18T01:31:53.971Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/82/a70006589557f267f15bd384c0642ad49f0d97b690c3a05b166b9dcbad3b/python_discovery-1.4.2-py3-none-any.whl", hash = "sha256:475803f53b7b2ed6e490e27373f9d8340f7d2eebf9acdaf645d7d714c97bb500", size = 33886, upload-time = "2026-06-11T16:10:41.192Z" }, + { url = "https://files.pythonhosted.org/packages/16/7d/e9ffbadfbf89c93848412d04594135c4ae8c1d37d9e053b9c3ed718fabc4/python_discovery-1.6.1-py3-none-any.whl", hash = "sha256:d43fcdef879fe795352bd13ccf8d185ba5a9f86f36cfcd00529f596e737442b3", size = 38664, upload-time = "2026-09-18T01:31:52.448Z" }, ] [[package]] @@ -5752,7 +5777,8 @@ name = "sse-starlette" version = "3.4.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "starlette" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f7/2b/58abc2d1fd397e7dde08e947e05c884d8ef2f78d5e2588c17a12d42d6994/sse_starlette-3.4.4.tar.gz", hash = "sha256:07e0fa0460138baf25cdd5fb28683472c3995dc1642225191b3832d62526bcb0", size = 31819, upload-time = "2026-05-12T17:37:17.019Z" } @@ -5765,7 +5791,8 @@ name = "starlette" version = "1.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b5/b4/205b0d5241d934e8add0c38aa924c4f9fb7330834ff11e5444db964ec3f9/starlette-1.6.0.tar.gz", hash = "sha256:d4e3ac5e546444960c710297a3c9fc3f7ebae1b7e963f3d36173b49da535be9b", size = 2716969, upload-time = "2026-08-08T18:27:57.512Z" } @@ -6075,11 +6102,11 @@ wheels = [ [[package]] name = "urllib3" -version = "2.7.0" +version = "2.8.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, ] [[package]] @@ -6264,17 +6291,18 @@ wheels = [ [[package]] name = "virtualenv" -version = "21.4.3" +version = "21.14.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "distlib" }, { name = "filelock" }, + { name = "packaging" }, { name = "platformdirs" }, { name = "python-discovery" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/4b/50/7564c805bb8966d9771caaba8a143fa5e57c848ce4e7fdf2d55a1feb2ead/virtualenv-21.4.3.tar.gz", hash = "sha256:938ff0fd3f4e0f0d3a025f67a3d2f25e3c3aabbcd5857ea6170619138d72d141", size = 7644454, upload-time = "2026-06-11T16:47:04.843Z" } +sdist = { url = "https://files.pythonhosted.org/packages/50/67/b5d37693e5e666b68100db8fe34f00db28279330db55f739a3c799ff2449/virtualenv-21.14.1.tar.gz", hash = "sha256:719b189804e66678017d9f63bbfc590c44f6b96ab4829513806394f9b375929c", size = 5462838, upload-time = "2026-09-29T23:33:33.991Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a2/8d/84b0d07c6b5f685f85ddf6c87a59d3a8a895a3dfd89e759666fabe951b94/virtualenv-21.4.3-py3-none-any.whl", hash = "sha256:75f4127d4067397c64f38579ce918fec6bf9ca2cd4f48685e82952cc3c035840", size = 7625544, upload-time = "2026-06-11T16:47:01.78Z" }, + { url = "https://files.pythonhosted.org/packages/85/a8/22be2d14ef0d7b1e9e7dc1d839a85073fc20917be1747d6f1347d1cfc8c3/virtualenv-21.14.1-py3-none-any.whl", hash = "sha256:6fd04089fc0dc33549e7abdff70fc3b63d4e15799f2dbf3281f80d13b9fce522", size = 5486534, upload-time = "2026-09-29T23:33:32.333Z" }, ] [[package]] @@ -6309,7 +6337,8 @@ name = "watchfiles" version = "1.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/cd/41/5e1a4bb12aac5f1493fa1bdc11154eca3b258ca4eba65d39c473fe19d8e9/watchfiles-1.2.0.tar.gz", hash = "sha256:c995fba777f1ea992f090f9236e9284cf7a5d1a0130dd5a3d82c598cacd76838", size = 108252, upload-time = "2026-05-18T04:32:04.251Z" } wheels = [ From 921a97d5cf05b4a1d577cc05e59d80925eef8cd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 20:58:26 +0000 Subject: [PATCH 15/16] chore: ignore ModelCheckpoint's default output directory optimization_results/checkpoints/ is where ModelCheckpoint() writes by default; test runs and local fits leave files there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 0de049ad..7ec53c40 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,5 @@ site/ poetry.lock inspiration/ examples/prompt_optimization/out/ +# ModelCheckpoint default output (runtime artefacts, never committed) +optimization_results/checkpoints/ From 69e16366ae302aca7a8d906af06b7059937690c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 21:00:23 +0000 Subject: [PATCH 16/16] ci(sync-studio): do not fail the sync when PR labels are missing `gh pr create --label automated,studio-ui` exits 1 when a label does not exist on the repository, so the v0.4.0 and v0.4.1 syncs pushed their branch but never opened a PR. Create the PR first and add the labels best-effort. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011gEMypXBosTqaEh3QFVXCX --- .github/workflows/sync-studio.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/sync-studio.yml b/.github/workflows/sync-studio.yml index e73b626e..b18d8a64 100644 --- a/.github/workflows/sync-studio.yml +++ b/.github/workflows/sync-studio.yml @@ -165,8 +165,10 @@ jobs: --- *This PR was automatically created by the [sync-studio workflow](https://github.com/UnicoLab/agentomatic/actions/workflows/sync-studio.yml).*" \ - --label "automated,studio-ui" \ --base main echo "✅ Pull request created successfully" + # Labels are best-effort: a missing label must not fail the sync. + gh pr edit "${BRANCH}" --add-label "automated,studio-ui" \ + || echo "::warning::Could not add labels (create 'automated' and 'studio-ui')" fi