diff --git a/CHANGELOG.md b/CHANGELOG.md index 535655ad..97b0eff4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased](https://github.com/microsoft/conductor/compare/v0.1.37...HEAD) +### Added + +- **Direct MCP workflow steps (`type: mcp`)** (#392): calls a tool on a + configured `runtime.mcp_servers` stdio server directly without an LLM. + Arguments are rendered recursively with Jinja2 and auto-coerced to + JSON-native types; the result envelope (`content`, `structured`, `is_error`) + merges structured keys directly onto the output dict so routes and downstream + steps can branch on `output.is_error` or individual fields. Calls serialize + per server process to maintain stdio stream integrity while distinct servers + execute concurrently in parallel groups. Output text payload is bounded by + `runtime.tool_output` with spill-to-file support while structured data is + preserved intact. Step and result values are excluded from all lifecycle + events (`mcp_started`, `mcp_completed`, `mcp_failed`), with failure messages + redacted to a safe category and full exception traces written only to a + private per-run `*.mcp-diagnostics.log` file (named by the redacted + message). See + [`docs/workflow-syntax.md`](docs/workflow-syntax.md#mcp-steps) and + [`examples/mcp-step.yaml`](examples/mcp-step.yaml). + ## [0.1.37](https://github.com/microsoft/conductor/compare/v0.1.36...v0.1.37) - 2026-09-09 ### Added diff --git a/README.md b/README.md index 8306380e..f15e95dd 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Conductor makes multi-agent workflows — code review pipelines, research-then-s - **Sub-workflow composition** - Reusable sub-workflows with templated `input_mapping`, usable inside `for_each` groups for dynamic fan-out - **Script steps** - Run shell commands and route on exit code or parsed JSON stdout - **Set steps** - Bind one or more Jinja2-evaluated values into the context (no LLM, no subprocess) for derived flags, computed defaults, and constants reused by many later prompts +- **MCP steps** - Call MCP server tools directly without an LLM (deterministic execution, zero prompt tokens, and structured envelope routing) - **Terminate steps** - Explicit terminal step with `status` (`success`/`failed`) and structured `reason` — distinguishable from the default `$end` path in CLI exit codes, dashboard state, and event logs - **Dialog mode** - Agents can pause for multi-turn conversation when uncertain - **Reasoning effort** - Unified `reasoning.effort` (low/medium/high/xhigh/max) per agent or workflow-wide, translated to each provider's native API @@ -546,6 +547,7 @@ See the [`examples/`](./examples/) directory for complete workflows: | [design-review.yaml](./examples/design-review.yaml) | Human gate with loop pattern | | [script-step.yaml](./examples/script-step.yaml) | Script step with exit_code routing | | [set-step.yaml](./examples/set-step.yaml) | Set step deriving named values + boolean-routed branching | +| [mcp-step.yaml](./examples/mcp-step.yaml) | Direct MCP tool execution with structured routing and error handling | | [wait-step.yaml](./examples/wait-step.yaml) | Wait step + script for a polling loop-back pattern | | [wait-smoke.yaml](./examples/wait-smoke.yaml) | Minimal wait-only smoke test (no provider required) | | [terminate.yaml](./examples/terminate.yaml) | Explicit `type: terminate` with success and failure paths | diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index f1f797af..6eadfc83 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -96,6 +96,31 @@ The configuration fields are the same as `http`. > **Provider note:** The Claude provider only supports `stdio` servers. The `http` and `sse` types are supported by the Copilot and Claude Agent SDK providers. +## Direct MCP Steps + +Conductor supports two distinct ways to execute MCP tools: + +1. **LLM-driven tool calling:** An AI agent receives tool definitions from configured `mcp_servers` and autonomously chooses which tools to call and what arguments to supply. +2. **Direct MCP steps (`type: mcp`):** A deterministic workflow step invokes an MCP tool directly with authored arguments, without involving an LLM. + +Direct MCP steps run deterministically, spend zero LLM tokens, and capture structured result envelopes (`content`, `structured`, `is_error`) directly into the workflow context. This enables explicit routing on tool outputs and errors. + +```yaml +agents: + - name: fetch_file + type: mcp + server: filesystem + tool: read_file + arguments: + path: "config.json" + routes: + - to: handle_error + when: "{{ output.is_error }}" + - to: parse_config +``` + +Direct MCP steps are provider-independent (they work with any provider or even without an LLM provider configured) and execute on `stdio` MCP servers. See [Workflow Syntax: MCP Steps](workflow-syntax.md#mcp-steps) for the complete reference on arguments, envelope merging, and routing semantics. + ## Configuration Reference ### Full Schema diff --git a/docs/workflow-syntax.md b/docs/workflow-syntax.md index 499b3617..8fdb3824 100644 --- a/docs/workflow-syntax.md +++ b/docs/workflow-syntax.md @@ -1147,6 +1147,136 @@ Per-key typing on multi `values:` is not supported. **Events** — set steps emit `set_started` / `set_completed` / `set_failed` (mirroring the script-step lifecycle) in all three positions: linear main loop, parallel group member, and for-each iteration. The `set_completed` payload carries `output_type`, `output_keys` (sorted, empty for scalars), and `value_repr` (a JSON-safe preview, truncated at 512 chars). +### MCP Steps + +MCP steps call a tool on a configured MCP server directly without invoking an LLM. There is no model call, no prompt tokens are spent, and execution is deterministic. Use them to fetch files, query databases, invoke APIs, or perform external tool operations where the exact tool and arguments are known in advance. + +```yaml +agents: + - name: read_spec + type: mcp + server: filesystem # Server name in runtime.mcp_servers (required, literal) + tool: read_file # Tool name on the MCP server (required, literal) + arguments: # Tool arguments (optional, Jinja2-rendered) + path: "docs/spec.md" + timeout: 30 # Per-call timeout in seconds (optional) + routes: + - to: handle_error + when: "{{ output.is_error }}" + - to: analyze_spec +``` + +**Fields:** + +| Field | Type | Description | +|-------|------|-------------| +| `server` | `string` | **Required.** MCP server name declared in `workflow.runtime.mcp_servers`. Literal string only; templates are rejected. | +| `tool` | `string` | **Required.** Tool name as exposed by the server. Literal string only; templates are rejected. | +| `arguments` | `mapping` | Optional tool arguments dict. Recursively Jinja2-rendered against workflow context. | +| `timeout` | `integer` | Optional per-call timeout in seconds. Raises `ExecutionError` if exceeded. | +| `output` | `mapping` | Optional output schema for validating the merged result envelope. | +| `routes` | `list` | Optional route list evaluated against the merged result envelope. | +| `input` | `list` | Optional input reference declarations used in explicit context mode. | + +**Argument rendering and type coercion:** + +Dicts and lists inside `arguments` are walked recursively. String leaves are Jinja2-rendered against the workflow context, and each *fully rendered string* is then parsed as YAML (the `set` step's `auto` rule) — whatever the rendered text parses as becomes the argument value: + +- Whole-string scalars: `"105"` -> `int`, `"true"` -> `bool`, `"null"` -> `None`. +- Collections: `"[1, 2]"` -> `list`, `"key: value"` -> `dict`. +- Embedded templates are parsed the same way — `"1{{ x }}"` with `x=2` renders `"12"` and becomes the integer `12`, and `"label: {{ x }}"` becomes a mapping. Only renders whose text parses as a plain string (e.g. `"pre-{{ x }}"` -> `"pre-2"`, multi-word prose) stay strings. +- Empty or whitespace-only renders become `""`; a render that parses as `null` through anything but an explicit null marker (`null`, `~`) keeps its raw string form. +- Native YAML scalars (integers, floats, booleans, `None`) pass through without change. + +If an argument's exact type matters, keep the rendered text unambiguous (e.g. quote it in a way that cannot parse as another type, or build the value in a `set` step where you can assert `output_type`). + +**Result envelope and merge rule:** + +An MCP tool execution produces a result envelope with three base keys: + +```json +{ + "content": [ + {"type": "text", "text": "..."} + ], + "structured": {"record_id": 42, "status": "ok"}, + "is_error": false +} +``` + +When the tool returns structured content (a dictionary under `structured`), its top-level keys are merged directly into the agent's output dictionary alongside the envelope. Downstream templates and route conditions can access these fields directly: + +```jinja2 +{{ read_spec.output.content }} # Content blocks list +{{ read_spec.output.structured }} # Raw structured dict (or null) +{{ read_spec.output.is_error }} # Boolean error flag +{{ read_spec.output.record_id }} # Merged structured field +``` + +The base keys `content`, `structured`, and `is_error` are reserved by the envelope, and `outputs` / `errors` are additionally reserved because the workflow engine recognizes parallel/for-each group outputs by exactly those two top-level keys — a structured result flattening them would make the step's output indistinguishable from a group output. If the structured dictionary contains colliding keys, the envelope wins, the colliding keys are omitted from the merge with a debug-level log message, and they stay reachable under `output.structured.`. + +**`is_error` semantics and routing:** + +When an MCP tool reports a logical tool failure (`isError: true` in the MCP protocol), the step sets `output.is_error = True` and completes normally. The workflow engine does not treat this as a workflow crash, allowing you to handle tool failures via routing: + +```yaml +routes: + - to: handle_tool_error + when: "{{ output.is_error }}" + - to: process_success +``` + +In contrast, transport failures, unknown server names, unlisted tools, server launch failures, call timeouts, and output schema validation mismatches raise exceptions and fail the step. + +**Server transport:** + +MCP steps currently support `stdio` servers only. Configuring an `http` or `sse` server for an MCP step is rejected during validation and runtime with an explicit error: `type: mcp supports stdio servers only (http/sse support is not implemented yet)`. + +**Concurrency and slot serialization:** + +Calls to the same MCP server process are serialized via an internal per-server slot lock to protect the stdio stream. Calls to different MCP servers run in parallel when placed in parallel groups. The engine pools one server process per `(server, working_dir)` pair, bounded by `_MCP_STEP_POOL_MAX` (16) as a *soft* threshold: when the pool is at the cap, the oldest entry not currently serving a call is closed to make room, so a for_each rendering many unique working directories cannot spawn unbounded server processes within a single run. If every entry is busy serving a call, the overflow is allowed rather than blocking or failing the step — the cap bounds idle connections, not in-flight work. + +**Timeouts:** + +The step-level `timeout` field sets a per-call timeout in seconds for the MCP tool invocation. It is independent of the overall `workflow.limits.timeout_seconds`, which bounds the entire workflow execution. + +**Composition:** + +- **Parallel groups:** MCP steps can run inside `parallel` groups. Invocations targeting distinct servers execute concurrently; invocations targeting the same server serialize on the server slot lock. +- **For-each groups:** MCP steps can serve as the inline agent of a `for_each` group. +- **Working directory:** The server process inherits the workflow's `runtime.working_dir`, rendered dynamically per execution. Step-level `working_dir` is not allowed on MCP steps. + +**Validation rules:** + +- **Static validation (`conductor validate`):** Validates workflows offline without connecting to servers. Checks that the referenced server is declared in `runtime.mcp_servers`, has `type: stdio`, allows the tool in its `tools:` filter (a `"*"` member means unrestricted), that every Jinja template in `arguments` parses, and that no template references a sibling member of the same parallel group. +- **Runtime validation (`conductor run`):** Repeats the *target* checks at execution time — the server is declared, the transport is stdio, the tool is allowlisted, and (only possible live) the tool actually exists on the connected server. Runtime does **not** repeat the offline-only diagnostics: template syntax checking and same-parallel-group reference analysis run exclusively under `conductor validate`, so skipping validation forfeits those two guarantees. + +**Limits and truncation policy:** + +`runtime.tool_output` bounds the total text length across all text blocks in `content`. When text output exceeds `max_chars`, blocks are truncated in order. Truncated blocks receive `"truncated": true` and a `"spill_path"` pointing to the full spilled output file when spilling is enabled. The `structured` dictionary represents structured application data and is never truncated. + +**Events, errors, and secrets policy:** + +MCP steps emit three lifecycle events: +- `mcp_started`: contains `agent_name`, `iteration`, `server`, `tool`, and `argument_keys` (sorted list of key names only). +- `mcp_completed`: contains `agent_name`, `elapsed`, `server`, `tool`, `is_error`, `result_bytes`, `truncated`, and optional `spill_path` (only ever a Conductor-generated spill file path — server-supplied `truncated`/`spill_path` block fields are stripped at ingestion and never forwarded; on a resumed run the synthetic replay does not republish markers stored in a checkpoint at all, since a checkpoint written before the stripping existed can carry server-supplied ones). +- `mcp_failed`: contains `agent_name`, `elapsed`, `server`, `tool`, `error_type`, and a `message` that is either authored and value-free (unknown server, non-stdio transport, disallowed/missing tool, a timeout with its duration) or a generic redacted pointer (see below). + +**Argument values and result payloads are never included in MCP step event payloads** — this guarantee covers exactly the tool arguments and the tool result bodies, nothing else. Two things stay visible *by design*, so plan around them: + +- `for_each` item identifiers: the `key_by` value of each item is copied onto that item's `mcp_*` events as `item_key`. Do not use a sensitive value as `key_by` (e.g. a token that is also a tool argument) — it will appear in event streams and the dashboard. +- Anything you *explicitly* surface: writing an MCP result into the workflow's final `output:` publishes it in `workflow_completed`, and referencing it in a later step's `prompt`/`arguments` sends it onward. The redaction governs automatic event metadata, not data you route yourself. + +When a call fails with anything but an authored value-free error, the step's raw exception (which can embed argument or result values) is written only to a private per-run diagnostic file — `*.mcp-diagnostics.log` next to the run's `*.events.jsonl` log — and the `mcp_failed` event plus the raised error point at that path. The redaction extends downstream: the step re-raises a generic error, so `workflow_failed` and group failure events (`parallel_agent_failed`, `for_each_item_failed`) also carry only the sanitized message. The diagnostic file may contain secrets; it is not deleted automatically and is covered by the same temp-directory hygiene as `runtime.tool_output` spill files. + +**Cancellation and interrupt semantics:** + +MCP steps do not support automatic retries (`retry:` is forbidden). A dashboard **Stop** (or Esc in the terminal) during a main-loop MCP step cancels the in-flight call — across the slot wait, the lazy connect, and the call itself — and enters the usual pause flow (`agent_paused`, then Resume/Kill). A cancelled call is never replayed transparently: its external side effects are unknown, so the step is re-entered from the top only on an *explicit* resume decision — a dashboard **Resume**/guidance, or the terminal interrupt menu. If the pause resolves without anyone making that decision (every browser client disconnects mid-pause, or the dashboard has no connected clients at all), the run stops as a resumable failure flagged `stopped_by_user` with a checkpoint, and `conductor resume` becomes the explicit re-execution boundary — unlike LLM agents, which auto-resume on disconnect because re-running one only costs tokens. **Kill** unwinds the workflow. Within parallel and for-each groups, MCP members behave like LLM members: a Stop reaches them through the group's cancellation/drain, not through a mid-call interrupt signal. When a run is cancelled or the workflow-level `limits.timeout_seconds` fires, the engine stops waiting for the call. Any external side effects already performed by the MCP server process are not rolled back, providing at-least-once execution semantics on workflow resume. + +**Restrictions:** + +MCP steps cannot have `prompt`, `system_prompt`, `provider`, `model`, `tools`, `reasoning`, `context_tier`, `skills`, `plugins`, `validator`, `dialog`, `sandbox`, `session_key`, `max_agent_iterations`, `max_session_seconds`, `output_mode`, `retry`, `timeout_seconds` (use `timeout`), `command`, `args`, `env`, `working_dir`, `settings_dir`, `options`, `workflow`, `input_mapping`, `max_depth`, `value`, `values`, or `output_type`. + ### Sub-Workflow Steps Sub-workflow steps reference external workflow YAML files, enabling composable and reusable workflow building blocks. The sub-workflow runs as a black box — its internal agents are not visible to the parent. diff --git a/examples/README.md b/examples/README.md index bf9b05c4..8bea6ddf 100644 --- a/examples/README.md +++ b/examples/README.md @@ -75,6 +75,22 @@ conductor run examples/set-step.yaml \ --input model=claude-haiku-4.5 ``` +## MCP Step Examples + +### mcp-step.yaml + +Call an MCP server tool directly without an LLM. Demonstrates: + +- `type: mcp` step executing a tool on a configured stdio MCP server +- Passing Jinja2-templated arguments to the tool +- Capturing the result envelope (`content`, `structured`, `is_error`) in context +- Routing conditionally on `output.is_error` to handle tool errors +- Zero LLM tokens spent on tool execution + +```bash +conductor run examples/mcp-step.yaml +``` + ## Human-in-the-Loop Examples ### design-review.yaml @@ -283,6 +299,19 @@ Demonstrates: conductor run examples/script-step.yaml ``` +### mcp-step.yaml + +Direct MCP step with tool execution and `is_error`-based routing. Demonstrates: +- `type: mcp` agents calling stdio MCP server tools directly +- Passing Jinja2-templated arguments to the tool +- Capturing structured content and error flags +- Routing on `is_error` (`when: "{{ output.is_error }}"`) +- Passing MCP step output to downstream steps + +```bash +conductor run examples/mcp-step.yaml +``` + ### script-stdin.yaml Hand a structured payload to a script step via **stdin** instead of diff --git a/examples/mcp-step.yaml b/examples/mcp-step.yaml new file mode 100644 index 00000000..2714f341 --- /dev/null +++ b/examples/mcp-step.yaml @@ -0,0 +1,69 @@ +# MCP Step Example +# +# Demonstrates `type: mcp` steps that call MCP server tools directly without +# an LLM. Direct MCP steps run deterministically, cost zero LLM tokens, and +# capture structured tool outputs and error flags into the workflow context. +# +# This workflow: +# 1. read_project_readme: calls the `read_file` tool on a configured stdio +# MCP server (`filesystem`). +# 2. Routes on `output.is_error` to handle tool errors versus success. +# 3. On success, inspects the retrieved content in a downstream step. +# +# Try it: +# uv run conductor run examples/mcp-step.yaml +# +# Validate offline: +# uv run conductor validate examples/mcp-step.yaml + +workflow: + name: mcp-step-demo + description: "Demonstrates deterministic type: mcp steps calling an MCP server" + version: "1.0.0" + entry_point: read_project_readme + + runtime: + provider: copilot + mcp_servers: + filesystem: + type: stdio + command: npx + args: ["-y", "@modelcontextprotocol/server-filesystem", "."] + tools: ["read_file", "list_directory"] + + limits: + max_iterations: 10 + +agents: + - name: read_project_readme + type: mcp + description: Read the project README file via the filesystem MCP server + server: filesystem + tool: read_file + arguments: + path: "README.md" + timeout: 30 + routes: + - to: handle_error + when: "{{ output.is_error }}" + - to: inspect_content + + - name: inspect_content + type: script + description: Process the file content returned by the MCP step + command: python3 + args: ["-c", "import sys; print('Successfully read file via direct MCP step')"] + routes: + - to: $end + + - name: handle_error + type: script + description: Handle tool-reported execution failure + command: python3 + args: ["-c", "import sys; print('MCP tool execution reported an error')"] + routes: + - to: $end + +output: + content_blocks: "{{ read_project_readme.output.content }}" + is_error: "{{ read_project_readme.output.is_error }}" diff --git a/plugins/conductor/skills/conductor/references/authoring.md b/plugins/conductor/skills/conductor/references/authoring.md index 365d4458..85a80a68 100644 --- a/plugins/conductor/skills/conductor/references/authoring.md +++ b/plugins/conductor/skills/conductor/references/authoring.md @@ -95,7 +95,7 @@ event + console warning. See ```yaml agents: - name: my_agent # Required: unique identifier - type: agent # agent (default), human_gate, script, workflow, wait, or terminate + type: agent # agent (default), human_gate, script, workflow, wait, terminate, or mcp description: What it does model: gpt-5.2 # Override workflow default provider: claude # Optional: per-agent provider override @@ -569,6 +569,68 @@ Set agents **cannot** have: `prompt`, `provider`, `model`, `tools`, `system_prom `output:` schema validation is permitted only when the rendered output is a dict (always for `values:`, sometimes for `value:`). A single-`value:` step with a declared schema that produces a scalar raises a `ValidationError` pointing to `values:`. +## MCP Steps (`type: mcp`) + +Directly invoke tools on configured MCP servers (`workflow.runtime.mcp_servers`) without an LLM. MCP steps run deterministically, spend zero prompt tokens, and capture structured output into the workflow context. + +```yaml +agents: + - name: read_spec + type: mcp + server: filesystem # Required: literal server name in runtime.mcp_servers + tool: read_file # Required: literal tool name on the server + arguments: # Optional: dict of Jinja2-templated arguments + path: "docs/spec.md" + timeout: 30 # Optional: per-call timeout in seconds + routes: + - to: handle_error + when: "{{ output.is_error }}" + - to: analyze_spec +``` + +### Argument Rendering and Type Coercion + +Dict and list structures in `arguments:` are traversed recursively. String leaves are Jinja2-rendered against workflow context, and each **fully rendered string** is then YAML-parsed (the `set` step's `auto` rule) — whatever the rendered text parses as becomes the argument value: `"105"` -> `105`, `"true"` -> `True`, `"null"` -> `None`, and also collections (`"[1, 2]"` -> a list, `"a: 1"` -> a mapping). This applies to templates too: `"1{{ x }}"` with `x=2` renders `"12"` and becomes the integer `12`; only renders whose text parses as a plain string (e.g. `"pre-{{ x }}"` -> `"pre-2"`, multi-word prose) stay strings. YAML-native scalars (integers, floats, booleans, `None`) pass through untouched. Quote and type-check values where the exact type matters. + +### Output Envelope and Merging + +MCP steps produce an output envelope: + +```json +{ + "content": [ + {"type": "text", "text": "..."} + ], + "structured": {"record_id": 42, "status": "ok"}, + "is_error": false +} +``` + +When `structured` is a dictionary, its top-level keys are merged onto the step output dict. Reserved keys are never overridden by the merge: the envelope's own `content`, `structured`, `is_error`, plus `outputs` and `errors` (the workflow engine duck-types parallel/for-each group outputs by those two keys — a structured result flattening them would corrupt how the step's output is addressed downstream). Colliding structured keys are dropped with a debug-level log and stay reachable under `output.structured.`. + +### Error Handling and `is_error` Routing + +Logical tool errors reported by the server set `output.is_error = True` and complete the step normally without raising an error, enabling conditional routing: + +```yaml +routes: + - to: handle_error + when: "{{ output.is_error }}" + - to: next_step +``` + +Transport failures, unlisted tools, unknown servers, timeouts, and output schema validation failures raise exceptions and fail the step. + +### Concurrency and Server Serialization + +Calls to the same MCP server process are serialized via a per-server slot lock. Calls to distinct MCP servers in parallel groups run concurrently. + +### MCP Step Restrictions + +MCP agents **cannot** have: `prompt`, `system_prompt`, `provider`, `model`, `tools`, `reasoning`, `context_tier`, `skills`, `plugins`, `validator`, `dialog`, `sandbox`, `session_key`, `max_agent_iterations`, `max_session_seconds`, `output_mode`, `retry`, `timeout_seconds` (use `timeout`), `command`, `args`, `env`, `working_dir`, `settings_dir`, `options`, `workflow`, `input_mapping`, `max_depth`, `value`, `values`, or `output_type`. + +MCP steps currently support `stdio` servers only. + ## Sub-Workflow Agents (`type: workflow`) Reference an external workflow YAML file as a black-box step. The sub-workflow runs with its own engine and inherits the parent's provider configuration. diff --git a/plugins/conductor/skills/conductor/references/yaml-schema.md b/plugins/conductor/skills/conductor/references/yaml-schema.md index b84dbeb5..c2f5b2e8 100644 --- a/plugins/conductor/skills/conductor/references/yaml-schema.md +++ b/plugins/conductor/skills/conductor/references/yaml-schema.md @@ -155,7 +155,7 @@ agents: name: string # Unique agent identifier # Optional fields - type: string # "agent" (default), "human_gate", "script", "workflow", "wait", or "terminate" + type: string # "agent" (default), "human_gate", "script", "workflow", "wait", "terminate", or "mcp" description: string # What this agent does model: string # Override default_model provider: string # Per-agent provider override ("copilot", "claude", "claude-agent-sdk", or "hermes") @@ -274,12 +274,20 @@ agents: output_template: # Optional: replaces workflow-level output: for this path : string # Each value Jinja2-templated, then JSON-coerced # ("true" -> True, "42" -> 42, JSON literals parsed) + + # MCP-only fields (type: mcp) + server: string # Server name from runtime.mcp_servers (literal string, required) + tool: string # Tool name on the MCP server (literal string, required) + arguments: {string: any} # Tool arguments (Jinja2-templated recursively) + timeout: integer # Per-call timeout in seconds ``` **Script agent restrictions:** Cannot have `prompt`, `provider`, `model`, `tools`, `output`, `system_prompt`, `options`, `retry`, `reasoning`, `dialog`, `validator`, `max_session_seconds`, `max_agent_iterations`, `session_key`, `timeout_seconds` (use `timeout`), `input_mapping`, or `max_depth`. Output is always `{stdout, stderr, exit_code}`. If `stdout` is valid JSON, its top-level keys are auto-merged into the output dict. **Set agent restrictions:** Cannot have `prompt`, `provider`, `model`, `tools`, `system_prompt`, `options`, `command`, `args`, `env`, `working_dir`, `timeout`, `workflow`, `input_mapping`, `max_depth`, `retry`, `dialog`, `validator`, `reasoning`, `timeout_seconds`, `max_session_seconds`, `max_agent_iterations`, or `session_key`. Requires exactly one of `value:` or `values:`. `output_type:` is forbidden with `values:` (per-key typing not yet supported). `output:` schema validation is permitted only when the rendered output is a dict (always for `values:`, sometimes for `value:`); a scalar with a declared schema raises `ValidationError`. Set agents are allowed inside `parallel` groups and as `for_each` inline agents, and count toward `limits.max_iterations` like any other step. +**MCP agent restrictions (`type: mcp`):** Cannot have `prompt`, `system_prompt`, `provider`, `model`, `tools`, `reasoning`, `context_tier`, `skills`, `plugins`, `validator`, `dialog`, `sandbox`, `session_key`, `max_agent_iterations`, `max_session_seconds`, `output_mode`, `retry`, `timeout_seconds` (use `timeout`), `command`, `args`, `env`, `working_dir`, `settings_dir`, `options`, `workflow`, `input_mapping`, `max_depth`, `value`, `values`, or `output_type`. Requires `server` and `tool`. Output is `{content, structured, is_error}` with top-level `structured` keys merged on top. Logical tool errors set `is_error: true` and complete normally, allowing `when: "{{ output.is_error }}"` routing. Stdio servers only. Calls to the same server serialize on a slot lock. + **Workflow agent restrictions (`type: workflow`):** Cannot have `prompt`, `model`, `provider`, `tools`, `system_prompt`, `command`, `options`, `retry`, `reasoning`, `dialog`, `validator`, `max_session_seconds`, `max_agent_iterations`, `session_key`, or `timeout_seconds`. Requires `workflow:` path. Supports `input_mapping` and `max_depth`. Allowed inside `for_each` groups for dynamic fan-out. **Terminate agent restrictions (`type: terminate`):** Requires `status` (`success` | `failed`) and a non-empty `reason`. Cannot have `routes`, `tools`, `output`, `prompt`, `model`, `provider`, `system_prompt`, `command`, `args`, `env`, `working_dir`, `timeout`, `timeout_seconds`, `max_session_seconds`, `max_agent_iterations`, `session_key`, `max_depth`, `retry`, `dialog`, `validator`, `reasoning`, `workflow`, `input_mapping`, or `options`. Cannot be used as a parallel-group member or as a `for_each` inline agent — route to a terminate step from those groups' `routes:` instead. Reaching a terminate step ends the workflow immediately (no routes evaluated after) and produces a distinguishable event payload: `workflow_completed` (for `success`) or `workflow_failed` (for `failed`) with `termination_reason`, `terminated_by`, `is_explicit: true`, and `status`. `status: failed` raises `WorkflowTerminated` (an `ExecutionError` subclass), gives the CLI a non-zero exit code, and is intentionally NOT resumable (no on-failure checkpoint saved). Inside a sub-workflow, a `status: failed` terminate is downgraded at the parent boundary to `SubworkflowTerminatedError` (also an `ExecutionError`), preserving the child's rendered `terminated_output`/`terminated_reason`/`terminated_by` as attributes on the wrapper. @@ -441,6 +449,61 @@ routes: - Allowed as the inline agent of a `for_each` group (one bound value per item). - Each invocation emits `set_started` / `set_completed` / `set_failed` events with `output_type`, `output_keys`, and a 512-char-truncated `value_repr`. +## MCP Agent Schema + +MCP agents directly call tools on configured MCP servers without an LLM: + +```yaml +agents: + - name: string + type: mcp # Required + description: string # Optional + server: string # Required: server name in runtime.mcp_servers (literal string) + tool: string # Required: tool name on the MCP server (literal string) + arguments: # Optional: tool arguments dict (Jinja2-rendered recursively) + : any + timeout: integer # Optional: per-call timeout in seconds + input: [string] # Optional: context dependencies for explicit context mode + output: # Optional: output schema for result validation + : + type: string + routes: # Optional: routing rules + - to: string + when: string +``` + +### MCP Output + +MCP steps produce an envelope containing `content`, `structured`, and `is_error`. When `structured` is a dictionary, its top-level keys are merged directly into the output dictionary: + +```jinja2 +{{ step.output.content }} # List of content blocks +{{ step.output.structured }} # Raw structured dictionary (or null) +{{ step.output.is_error }} # Boolean flag indicating logical tool error +{{ step.output.custom_field }} # Directly accessible merged structured field +``` + +Envelope keys (`content`, `structured`, `is_error`) take precedence over colliding structured keys, and `outputs` / `errors` are likewise reserved (the engine recognizes group outputs by those two keys); colliding structured keys stay reachable under `output.structured.`. + +### Routing on MCP Output + +Logical tool errors set `output.is_error = True` and complete the step normally, enabling conditional error routing: + +```yaml +routes: + - to: handle_error + when: "{{ output.is_error }}" + - to: process_success +``` + +### MCP Step Composition and Concurrency + +- Allowed inside `parallel` groups. Calls to the same MCP server serialize via a slot lock; calls to different servers run concurrently. +- Allowed as the inline agent of `for_each` groups. +- `runtime.tool_output` bounds summed text characters across `content` blocks. `structured` data is never truncated. +- Stdio servers only. +- Events (`mcp_started`, `mcp_completed`, `mcp_failed`) exclude argument values and result data; error messages in events are redacted, and full exception details land only in the run's private `*.mcp-diagnostics.log` file (next to the `*.events.jsonl` log), which the redacted message names. + ## File Includes (`!file` Tag) Include external file content anywhere in YAML: diff --git a/src/conductor/cli/run.py b/src/conductor/cli/run.py index c9c94100..f46abc7f 100644 --- a/src/conductor/cli/run.py +++ b/src/conductor/cli/run.py @@ -1053,6 +1053,34 @@ def on_event(self, event: WorkflowEvent) -> None: style="red", ) + elif t == "mcp_completed": + # Mirror of the wait_completed branch: one line naming the step's + # server/tool and elapsed. `mcp_started` is deliberately not + # printed — started events never reach the console. + verbose_log( + styled( + " MCP call done: {} {} after {:.2f}s", + d.get("server", "?"), + d.get("tool", "?"), + d.get("elapsed", 0.0), + ) + ) + + elif t == "mcp_failed": + # Unlike script_failed (which has no branch), an mcp failure must + # be visible here: a connect failure is otherwise silent until the + # run terminates with workflow_failed. + verbose_log( + styled( + " MCP call failed: {} {} — {}: {}", + d.get("server", "?"), + d.get("tool", "?"), + d.get("error_type", "Error"), + d.get("message", "unknown"), + ), + style="red", + ) + elif t == "agent_validator_start": verbose_log(f" Validating '{_validator_label(d)}' output…", style="cyan") diff --git a/src/conductor/config/schema.py b/src/conductor/config/schema.py index 34805c9b..3bfeabae 100644 --- a/src/conductor/config/schema.py +++ b/src/conductor/config/schema.py @@ -17,6 +17,7 @@ Field, SecretStr, StringConstraints, + ValidationInfo, ValidatorFunctionWrapHandler, field_validator, model_serializer, @@ -1185,6 +1186,10 @@ class AgentDef(BaseModel): ``args``, ``env``, ``working_dir``, ``timeout``. Output is always ``{stdout, stderr, exit_code}`` with parsed-JSON keys merged on top when ``stdout`` is valid JSON. + - ``mcp``: Direct MCP tool call (no LLM). Requires ``server`` (a name + from ``runtime.mcp_servers``) and ``tool``; supports ``arguments``, + ``output``, ``routes``, and ``timeout``. Both ``server`` and ``tool`` + must be literal — Jinja2 templates are rejected at load time. - ``workflow``: Sub-workflow black-box step. Requires ``workflow:`` (path or registry reference); supports ``input_mapping`` and ``max_depth``. @@ -1214,6 +1219,7 @@ class AgentDef(BaseModel): Literal[ "agent", "human_gate", + "mcp", "questions", "script", "set", @@ -1484,7 +1490,31 @@ class AgentDef(BaseModel): """ timeout: int | None = None - """Per-script timeout in seconds.""" + """Per-call timeout in seconds (script subprocess or MCP tool call).""" + + server: str | None = None + """MCP server name to call (required for ``type='mcp'`` steps). + + Must name a server declared in ``workflow.runtime.mcp_servers``. Never + Jinja2-rendered — a template is rejected at load time (see + :meth:`validate_mcp_fields_are_literal`), because static validation of + the server/tool pair is only possible on literal values. + """ + + tool: str | None = None + """Tool name to invoke on the MCP server (required for ``type='mcp'`` steps). + + Never Jinja2-rendered — a template is rejected at load time for the same + reason as :attr:`server`. + """ + + arguments: dict[str, Any] | None = None + """Optional argument mapping passed to the MCP tool (``type='mcp'`` only). + + String values (at any nesting depth) are Jinja2-rendered recursively + against the workflow context before the call; other JSON scalars pass + through unchanged. ``None`` calls the tool with no arguments. + """ duration: str | int | float | None = None """Duration to pause for ``type='wait'`` steps. @@ -1935,6 +1965,24 @@ def validate_timeout(cls, v: int | None) -> int | None: raise ValueError("timeout must be a positive integer") return v + @field_validator("server", "tool", mode="before") + @classmethod + def validate_mcp_fields_are_literal(cls, v: Any, info: ValidationInfo) -> Any: + """Reject a Jinja2 template in ``server`` / ``tool`` (type: mcp steps). + + Neither field is ever rendered, and static validation of the + server/tool pair (declared server exists, tool is on its allowlist) + is only possible on literal values — a template would defer that + check entirely to runtime. + """ + if isinstance(v, str) and ("{{" in v or "{%" in v): + raise ValueError( + f"{info.field_name} {v!r} looks like a Jinja2 template, but " + f"{info.field_name} is never rendered — static validation of the " + f"server/tool pair requires a literal value. Use a static name." + ) + return v + @field_validator("session_key") @classmethod def validate_session_key_is_literal(cls, v: str | None) -> str | None: @@ -2051,6 +2099,18 @@ def validate_agent_type(self) -> AgentDef: "(only 'script' agents support this field)" ) + # Fields exclusive to ``type: mcp`` — a standalone guard, like the + # terminate/script/questions ones above, so it also covers types with + # no branch of their own (the ``mcp`` branch below only rejects + # fields, it cannot reject its own required ones on other types). + if self.type != "mcp": + for field_name in ("server", "tool", "arguments"): + if getattr(self, field_name) is not None: + raise ValueError( + f"'{self.type or 'agent'}' agents cannot have '{field_name}' " + "(only 'mcp' agents support this field)" + ) + # Fields exclusive to ``type: questions``. A standalone guard, like the # terminate/script ones above, so it also covers types with no branch # of their own. The nav flags are tri-state (``bool | None``) precisely @@ -2280,6 +2340,94 @@ def validate_agent_type(self) -> AgentDef: raise ValueError("workflow agents cannot have 'working_dir'") if self.settings_dir is not None: raise ValueError("workflow agents cannot have 'settings_dir'") + elif self.type == "mcp": + # Required fields. + if not self.server: + raise ValueError("mcp agents require 'server'") + if not self.tool: + raise ValueError("mcp agents require 'tool'") + # Field matrix for ``type: mcp`` — every AgentDef field is + # accounted for below so future fields cannot silently leak: + # ALLOWED (no check): name, description, type, input, output, + # routes, timeout (per-call seconds — unlike wait/set, + # an MCP call has no other timeout knob), server, tool, + # arguments + # FORBIDDEN (checked here): prompt, system_prompt, provider, + # model, tools, reasoning, context_tier, skills, plugins, + # validator, dialog, sandbox, session_key, + # max_agent_iterations, max_session_seconds, output_mode, + # retry, timeout_seconds, command, args, env, working_dir, + # settings_dir, options, workflow, input_mapping, max_depth, + # value, values, output_type + # COVERED BY STANDALONE GUARDS (no check needed here): + # stdin (script guard above), duration + reason + # (wait/terminate guard at the bottom of this method), + # status + output_template (terminate guard above), + # questions/source/allow_*/abort_route (questions guard + # above), server/tool/arguments on non-mcp types (guard + # above) + if self.prompt: + raise ValueError("mcp agents cannot have 'prompt'") + if self.provider: + raise ValueError("mcp agents cannot have 'provider'") + if self.model: + raise ValueError("mcp agents cannot have 'model'") + if self.tools is not None: + raise ValueError("mcp agents cannot have 'tools'") + if self.system_prompt: + raise ValueError("mcp agents cannot have 'system_prompt'") + if self.options: + raise ValueError("mcp agents cannot have 'options'") + if self.command: + raise ValueError("mcp agents cannot have 'command'") + if self.args: + raise ValueError("mcp agents cannot have 'args'") + if self.env: + raise ValueError("mcp agents cannot have 'env'") + if self.working_dir: + raise ValueError("mcp agents cannot have 'working_dir'") + if self.settings_dir is not None: + raise ValueError("mcp agents cannot have 'settings_dir'") + if self.workflow: + raise ValueError("mcp agents cannot have 'workflow'") + if self.input_mapping is not None: + raise ValueError("mcp agents cannot have 'input_mapping'") + if self.max_depth is not None: + raise ValueError("mcp agents cannot have 'max_depth'") + if self.max_session_seconds: + raise ValueError("mcp agents cannot have 'max_session_seconds'") + if self.max_agent_iterations is not None: + raise ValueError("mcp agents cannot have 'max_agent_iterations'") + if self.session_key is not None: + raise ValueError("mcp agents cannot have 'session_key'") + if self.retry is not None: + raise ValueError("mcp agents cannot have 'retry'") + if self.dialog is not None: + raise ValueError("mcp agents cannot have 'dialog'") + if self.validator is not None: + raise ValueError("mcp agents cannot have 'validator'") + if self.sandbox is not None: + raise ValueError("mcp agents cannot have 'sandbox'") + if self.reasoning is not None: + raise ValueError("mcp agents cannot have 'reasoning'") + if self.context_tier is not None: + raise ValueError("mcp agents cannot have 'context_tier'") + if self.skills is not None: + raise ValueError("mcp agents cannot have 'skills'") + if self.plugins is not None: + raise ValueError("mcp agents cannot have 'plugins'") + if self.timeout_seconds is not None: + raise ValueError( + "mcp agents cannot have 'timeout_seconds' (use 'timeout' for mcp call timeouts)" + ) + if self.output_mode is not None: + raise ValueError("mcp agents cannot have 'output_mode'") + if self.value is not None: + raise ValueError("mcp agents cannot have 'value' (only 'set' agents do)") + if self.values is not None: + raise ValueError("mcp agents cannot have 'values' (only 'set' agents do)") + if self.output_type is not None: + raise ValueError("mcp agents cannot have 'output_type' (only 'set' agents do)") elif self.type == "wait": if self.duration is None: raise ValueError("wait agents require 'duration'") diff --git a/src/conductor/config/validator.py b/src/conductor/config/validator.py index 1442cf15..853243f2 100644 --- a/src/conductor/config/validator.py +++ b/src/conductor/config/validator.py @@ -436,6 +436,12 @@ def validate_workflow_config( # Unconditional: default-on exposure means every workflow is a candidate. errors.extend(_validate_mcp_exposure(config)) + # Static half of the ``type: mcp`` step checks. ``conductor run`` never + # calls this validator, so the same rules (plus actual tool existence on + # the server) are enforced again at runtime; this is early off-network + # diagnostics for ``conductor validate`` only. + errors.extend(_validate_mcp_steps(config)) + if errors: raise ConfigurationError( "Workflow configuration validation failed:\n - " + "\n - ".join(errors), @@ -654,6 +660,82 @@ def _validate_mcp_exposure(config: WorkflowConfig) -> list[str]: return errors +def _validate_mcp_steps(config: WorkflowConfig) -> list[str]: + """Validate ``type: mcp`` step server/tool references. + + Checks that each mcp step's ``server`` is declared in + ``workflow.runtime.mcp_servers``, that the server's ``tools`` filter + allows the step's ``tool``, and that the server is a stdio server + (http/sse support is not implemented yet). Inline for-each agents are + walked explicitly since they are absent from ``config.agents``; + parallel-group members are names into ``config.agents`` and covered by + that list. This is the static half of the checks only — ``conductor + run`` never calls this validator, so the engine repeats them at runtime + (plus actual tool existence on the server). + + Returns: + List of error messages. + """ + errors: list[str] = [] + servers = config.workflow.runtime.mcp_servers + + # (agent, enclosing for_each group name or None) + mcp_agents: list[tuple[AgentDef, str | None]] = [ + (agent, None) for agent in config.agents if agent.type == "mcp" + ] + mcp_agents += [(fe.agent, fe.name) for fe in config.for_each if fe.agent.type == "mcp"] + + for agent, for_each_group in mcp_agents: + label = ( + f"Agent '{agent.name}'" + if for_each_group is None + else f"Agent '{agent.name}' in for-each group '{for_each_group}'" + ) + if agent.server is None or agent.tool is None: + # Schema validation already rejects mcp agents without + # server/tool; this guard only narrows the types below. + continue + server_def = servers.get(agent.server) + if server_def is None: + available = ", ".join(sorted(servers)) or "(none declared)" + errors.append( + f"{label} references unknown MCP server '{agent.server}'. " + f"Available servers: {available}" + ) + continue + if "*" not in server_def.tools and agent.tool not in server_def.tools: + errors.append( + f"{label} uses tool '{agent.tool}' which is not allowed by " + f"server '{agent.server}' tools filter " + f"({', '.join(server_def.tools)}). Add the tool to the server's " + 'tools list or use ["*"] to allow all tools.' + ) + if server_def.type != "stdio": + errors.append( + f"{label}: type: mcp supports stdio servers only " + f"(got '{server_def.type}'); http/sse support is not implemented yet" + ) + + # Syntax-check every argument template explicitly. Reference + # analysis (_extract_template_refs) deliberately swallows + # TemplateSyntaxError (semantic validation must not hard-fail on + # templates render-time would report), so without this pass a + # malformed nested argument like '{{ workflow.input.foo' would pass + # `conductor validate` and only fail at execution. + for source_label, template_str in _collect_argument_strings( + f"{label} arguments", agent.arguments + ): + try: + _JINJA_ENV.parse(template_str) + except jinja2.TemplateSyntaxError as exc: + errors.append( + f"{source_label}: invalid Jinja2 template syntax: {exc.message} " + f"(line {exc.lineno})" + ) + + return errors + + def _validate_output_references( output: dict[str, str], valid_names: set[str], @@ -813,11 +895,12 @@ def _validate_parallel_groups(config: WorkflowConfig) -> list[str]: "on each other." ) - # For 'set' steps, also walk value/values.* templates — they can - # reference siblings directly without declaring them in input:. + # For 'set' and 'mcp' steps, also walk their value/values.* + # (resp. arguments.*) templates — they can reference siblings + # directly without declaring them in input:. # Parallel execution uses a pre-group snapshot, so any reference # to a same-group member would silently miss its output. - if agent.type == "set": + if agent.type in ("set", "mcp"): for source_label, template_str in _collect_template_strings(agent): refs = _extract_template_refs(template_str) cross_refs = refs.agent_refs & pg_agents_set @@ -1252,6 +1335,25 @@ def _validate_output_path_coverage(config: WorkflowConfig) -> list[str]: return warnings +def _collect_argument_strings(label: str, value: Any) -> list[tuple[str, str]]: + """Recursively collect string leaves of an ``arguments`` value. + + Dict keys extend the dot-joined label (``arguments.``); list items + use index labels (``arguments.[]``). Non-string scalars pass + through untouched — only rendered strings can carry template references. + """ + collected: list[tuple[str, str]] = [] + if isinstance(value, dict): + for key, item in value.items(): + collected.extend(_collect_argument_strings(f"{label}.{key}", item)) + elif isinstance(value, list): + for i, item in enumerate(value): + collected.extend(_collect_argument_strings(f"{label}[{i}]", item)) + elif isinstance(value, str): + collected.append((label, value)) + return collected + + def _collect_template_strings( agent: AgentDef, ) -> list[tuple[str, str]]: @@ -1289,6 +1391,13 @@ def _collect_template_strings( for key, expr in values.items(): templates.append((f"agent '{agent.name}' values.{key}", expr)) + # 'mcp' step arguments — values are Jinja2-rendered at runtime, including + # string leaves nested in dicts/lists, so collect them recursively to + # catch stale references at validate-time like every other rendered field. + arguments: dict[str, Any] | None = getattr(agent, "arguments", None) + if arguments: + templates.extend(_collect_argument_strings(f"agent '{agent.name}' arguments", arguments)) + # input_mapping is on AgentDef in main (added by #109 closing #101) but may not # exist on the schema in branches that haven't merged that yet. getattr keeps # this forward-compatible without coupling validate semantics to schema timing. @@ -1768,7 +1877,7 @@ def _validate_template_references( elif ( is_explicit and agent.type - not in ("script", "set", "workflow", "human_gate", "questions", "wait") + not in ("script", "set", "workflow", "human_gate", "questions", "wait", "mcp") and input_name not in declared_workflow_inputs ): warnings.append( diff --git a/src/conductor/engine/context.py b/src/conductor/engine/context.py index 62cb9305..26fcef98 100644 --- a/src/conductor/engine/context.py +++ b/src/conductor/engine/context.py @@ -26,8 +26,12 @@ # mode, because workflow inputs are the workflow's external interface — set # once at startup and present for the lifetime of the run. Per-step agent # outputs remain explicitly declared in ``input:`` for traceability, even for -# local renders. -_LOCAL_RENDER_AGENT_TYPES = frozenset({"script", "set", "wait", "workflow"}) +# local renders. ``mcp`` joins set/script/wait/workflow because the static +# validator's explicit-mode warning exclusion covers mcp arguments +# (``workflow.input.*`` references pass validation), so the runtime context +# must make those references renderable in every mode — a reference that +# passes ``conductor validate`` must render at ``conductor run``. +_LOCAL_RENDER_AGENT_TYPES = frozenset({"script", "set", "wait", "workflow", "mcp"}) def estimate_tokens(text: str) -> int: diff --git a/src/conductor/engine/workflow.py b/src/conductor/engine/workflow.py index 97c64db1..39ca5ac6 100644 --- a/src/conductor/engine/workflow.py +++ b/src/conductor/engine/workflow.py @@ -13,7 +13,9 @@ import logging import os import sys +import tempfile import time as _time +import traceback import uuid from dataclasses import dataclass, field from pathlib import Path @@ -45,6 +47,12 @@ from conductor.executor import questions as questions_mod from conductor.executor.agent import AgentExecutor from conductor.executor.linkify import linkify_markdown +from conductor.executor.mcp_step import ( + McpStepExecutor, + McpStepTimeoutError, + mcp_result_bytes, + mcp_truncation_metadata, +) from conductor.executor.output import validate_output from conductor.executor.script import ScriptExecutor, ScriptOutput from conductor.executor.set_step import ( @@ -65,6 +73,7 @@ option_for_value, ) from conductor.gates.interrupt import InterruptAction, InterruptHandler, InterruptResult +from conductor.mcp_auth import resolve_mcp_server_config from conductor.providers.base import AgentOutput, EventCallback logger = logging.getLogger(__name__) @@ -75,10 +84,11 @@ if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Coroutine, Mapping from conductor.config.schema import AgentDef, ForEachDef, ParallelGroup, WorkflowConfig from conductor.interrupt.listener import KeyboardListener + from conductor.mcp.manager import MCPManager from conductor.plugins.marketplace import Marketplace from conductor.providers.base import AgentProvider from conductor.providers.registry import ProviderRegistry @@ -124,6 +134,16 @@ class WebPauseOutcome: """Guidance text(s) submitted while paused, in submission order. Empty when the pause was resolved by a plain Resume click or disconnect.""" + reason: Literal["resume", "guidance", "disconnect", "unavailable"] = "unavailable" + """Why the pause resolved (or didn't). ``resume`` / ``guidance`` are + explicit user decisions; ``disconnect`` means every browser client went + away mid-pause; ``unavailable`` means no pause was presented (no + dashboard, or a dashboard with zero connected clients). Callers whose + interrupted work has unknown external side effects (an in-flight + ``type: mcp`` tool call) must re-execute only on ``resume`` / + ``guidance`` and park the run on the other two; the LLM path keeps its + auto-resume behaviour on all of them.""" + @dataclass class ParallelAgentError: @@ -287,6 +307,126 @@ class ExecutionPlan: _ANSWER_SOURCES = frozenset({"choice", "free_text", "default", "skipped"}) """Legal ``AnswerRecord.source`` values, for validating restored checkpoints.""" +_MCP_STEP_POOL_MAX = 16 +"""Upper bound on engine-owned MCP managers pooled for ``type: mcp`` steps. + +One pool entry is a live server process keyed by ``(server_name, cwd)``; a +for_each whose ``runtime.working_dir`` renders a unique directory per item +would otherwise spawn an unbounded number of processes within a single run. +When the pool is at this cap and a new key needs connecting, the oldest +evictable entry is closed to make room: entries of the server that is +connecting are always evictable (the per-server slot lock the caller holds +serializes every use of that server's entries), then the oldest entry of any +other server whose slot lock is free. If every entry is locked, the overflow +is allowed rather than blocking a call. +""" + + +class _McpStepRuntimeCheckError(ExecutionError): + """Authored mcp-step runtime-check failure. + + Raised only by the runtime checks inside ``_run_mcp_step`` whose messages + name literal configuration only (unknown server, non-stdio transport, + tool not allowlisted, tool missing on the connected server) — server and + tool names come from the step's own literal config, never from the + execution context, so these may propagate verbatim through failure + events and the checkpoint message. Every other failure — manager/SDK + errors, output-schema mismatches, argument rendering, the cwd check + (whose rendered path and template can carry context values, so it raises + :class:`_McpStepRedactedCheckError` instead) — is wrapped in a generic + redacted ``ExecutionError`` or carries an authored value-free message. + """ + + +class _McpStepRedactedCheckError(ExecutionError): + """Authored mcp-step failure whose message is value-free by construction. + + The runtime ``working_dir`` not-a-directory check renders its path and + template from the execution context, so unlike the name-only runtime + checks the propagated message must not quote either — the full resolved + path and raw template land only in the run's private diagnostic file + (:meth:`WorkflowEngine._write_mcp_diagnostic`). ``_run_mcp_step`` + re-raises this verbatim like the runtime checks; every other exception + is wrapped in the generic redacted error. + """ + + +class _McpStepInterrupted(Exception): + """Control-flow signal: the user interrupted an in-flight mcp tool call. + + Raised by ``_run_mcp_step`` when ``interrupt_event`` fires while the step + waits on the per-server slot, the lazy connect, or the tool call itself. + The in-flight call is cancelled and NOT replayed inside this execution — + its external side effects are unknown. This is not a step failure: no + ``mcp_failed`` is emitted, and the main-loop caller routes into the same + pause flow an interrupted LLM agent gets (dashboard Resume/Kill or the + CLI interrupt menu). It deliberately derives from ``Exception`` (not + ``asyncio.CancelledError``): task cancellation tears the workflow down, + while this asks the caller to pause. + """ + + +class _McpStepOutcomeUncertain(InterruptError): + """Terminal, resumable stop: an interrupted mcp call had no one to resume it. + + Raised by the main-loop mcp dispatch when a Stop cancelled the in-flight + tool call and the pause then resolved WITHOUT an explicit resume decision + (every dashboard client disconnected mid-pause, or the dashboard has no + connected clients at all). Repeating the call transparently would risk + duplicating unknown external side effects, so the run stops instead: + deriving from ``InterruptError`` flags ``stopped_by_user`` on + ``workflow_failed``, and the failure checkpoint makes ``conductor + resume`` the explicit at-least-once re-execution boundary. No + ``mcp_failed`` is emitted — the tool reported no failure; the call's + outcome is simply unknown. + """ + + def __init__(self, agent_name: str) -> None: + super().__init__( + f"MCP step '{agent_name}' was interrupted and not resumed: the " + "tool call's external outcome is unknown. Resume the workflow to " + "re-run the step (at-least-once semantics).", + agent_name=agent_name, + ) + + +async def _cancel_and_drain_group_tasks(tasks: list[asyncio.Task[Any]]) -> None: + """Cancel every child task and await their teardown, re-cancellation-proof. + + Used by the parallel / for-each fail-fast drains. Mirrors the + re-shielding loop in ``MCPManager.connect_server()`` / ``close()``: the + drain runs as its own gather future awaited under ``asyncio.shield`` + inside a loop, so a repeated ``cancel()`` of the waiting task lands on + the shield instead of the drain — a sibling delayed in cancellation + cleanup (or temporarily suppressing cancellation) always finishes before + this returns and cannot race the pool close in ``run()``'s finally. + Cancellation requests that arrive during the drain are noted at debug + level; the caller re-raises the exception that entered its except arm, + so the original exception is the one that propagates (an extra cancel + during the drain never replaces it). + """ + for task in tasks: + # gather already cancelled the children when it was THIS task's own + # cancellation that entered the except arm — a second cancel() would + # land on a sibling that is mid-cleanup (CancelledError already + # delivered, cancelling() > 0) and kill its cleanup via _must_cancel. + # Only children with no pending cancellation still need cancelling + # (a sibling still running because another child raised). + if task.cancelling() == 0: + task.cancel() + cleanup = asyncio.gather(*tasks, return_exceptions=True) + while not cleanup.done(): + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError: + logger.debug( + "group drain received a cancellation request; continuing until all " + "sibling tasks finish their cleanup" + ) + # With return_exceptions=True the gather only completes normally; surface + # anything else rather than swallow it. + cleanup.result() + def _answer_counts(output: dict[str, Any]) -> dict[str, int]: """Project a questions output down to the counts events carry. @@ -425,7 +565,23 @@ def __init__( self.max_iterations_handler = MaxIterationsHandler(skip_gates=skip_gates) self.script_executor = ScriptExecutor() self.set_executor = SetExecutor() + self.mcp_step_executor = McpStepExecutor() self.wait_executor = WaitExecutor() + # Engine-owned MCP manager pool for `type: mcp` steps (lazy connect, + # keyed by (server_name, resolved_cwd) — a server-only key would + # silently reuse the first for_each item's cwd for the rest, since + # runtime.working_dir Jinja-renders per execution). The pool guard + # only ever covers dict mutation and the admission reservation, never + # I/O, so distinct servers connect concurrently; the per-server slot + # lock is held across the lazy connect + call by _run_mcp_step. + self._mcp_step_managers: dict[tuple[str, str], MCPManager] = {} + self._mcp_step_locks: dict[str, asyncio.Lock] = {} + self._mcp_step_pool_guard: asyncio.Lock = asyncio.Lock() + # Count of in-flight pool connects (reserved slots). Checked together + # with the pool size under the guard so two concurrent first-time + # connects cannot both pass a size-only capacity check and overshoot + # _MCP_STEP_POOL_MAX with nothing evicted. + self._mcp_step_pending: int = 0 self.usage_tracker = UsageTracker( pricing_overrides=self._build_pricing_overrides(), ) @@ -593,6 +749,197 @@ def _workflow_dir(self) -> Path | None: """Resolved parent directory of the workflow file, or None if unset.""" return Path(self.workflow_path).resolve().parent if self.workflow_path else None + async def _mcp_step_slot(self, server_name: str) -> asyncio.Lock: + """Return the per-server slot lock for an MCP step, creating it if needed. + + Creation/lookup runs under the short pool guard, which never spans + I/O — otherwise distinct servers would serialize their connects. + The returned lock is held by ``_run_mcp_step`` across lazy + connect, runtime tool checks, and the call, keyed by server name + (all cwds for one server are serialized — conservative). + """ + async with self._mcp_step_pool_guard: + lock = self._mcp_step_locks.get(server_name) + if lock is None: + lock = asyncio.Lock() + self._mcp_step_locks[server_name] = lock + return lock + + async def _get_mcp_step_manager(self, server_name: str, resolved_cwd: str) -> MCPManager: + """Return the pooled MCPManager for ``(server_name, resolved_cwd)``, connecting lazily. + + Call only under the per-server slot lock from :meth:`_mcp_step_slot`. + + Admission is atomic under the pool guard: the double-checked lookup + AND a reservation for the in-flight connect (``_mcp_step_pending``) + happen in the same critical section, so two concurrent first-time + connects (distinct servers or cwds) cannot both pass a size-only + capacity check and overshoot :data:`_MCP_STEP_POOL_MAX` with nothing + evicted. The connection I/O itself runs OUTSIDE the guard; the + reservation is released on failure/cancellation and folded into the + pool on success. A failed ``connect_server`` propagates and leaves + nothing in the pool, so the next call retries the connect. + + Args: + server_name: Key into ``runtime.mcp_servers``. + resolved_cwd: Working directory the server process is spawned + in; arrives as a parameter because ``runtime.working_dir`` + Jinja-renders per execution and can differ between + for_each items. + """ + # Lazy import: conductor.mcp.__init__ eagerly imports the MCP SDK, and + # this module is imported by cli/app.py on every conductor invocation. + from conductor.mcp.manager import MCPManager + + key = (server_name, resolved_cwd) + + while True: + async with self._mcp_step_pool_guard: + manager = self._mcp_step_managers.get(key) + if manager is not None: + return manager + if len(self._mcp_step_managers) + self._mcp_step_pending < _MCP_STEP_POOL_MAX: + self._mcp_step_pending += 1 + break + target = self._pick_mcp_eviction_target(server_name) + if target is None: + # Soft cap: every entry is serving a call right now, so + # nothing is safe to evict. Allow the overflow rather + # than block or fail the step. + logger.debug( + "MCP step pool at cap %d with every entry locked; allowing overflow", + _MCP_STEP_POOL_MAX, + ) + self._mcp_step_pending += 1 + break + evicted = self._mcp_step_managers.pop(target) + # The close runs outside the guard (the guard never spans I/O) and + # with cancellation-safe semantics — see the helper. + await self._close_evicted_mcp_step_manager(target, evicted) + + server_def = self.config.workflow.runtime.mcp_servers[server_name] + # MCPServerDef -> connect kwargs. DRIFT HAZARD: this translation is + # duplicated from cli/run.py::_build_mcp_servers (mcp steps execute in + # the engine, which must not import conductor.cli — a reverse cycle). + # Keep the two in sync when the translation changes. + server_config: dict[str, Any] = { + "type": "stdio", + "command": server_def.command, + "args": server_def.args, + "tools": server_def.tools, + } + if server_def.env: + server_config["env"] = server_def.env + if server_def.timeout: + server_config["timeout"] = server_def.timeout + resolved = await resolve_mcp_server_config(server_name, server_config) + + try: + manager = MCPManager(tool_output=self.config.workflow.runtime.tool_output) + await manager.connect_server( + name=server_name, + command=resolved["command"], + args=resolved.get("args"), + env=resolved.get("env"), + timeout=resolved.get("timeout"), + cwd=resolved_cwd, + # Deterministic mcp-step connections take the redacted logging + # path: a stdio failure's exception can embed server-supplied + # stderr (values the step's no-values policy excludes), so the + # manager logs safe metadata only; the raw exception still + # chains into the RuntimeError below, and _run_mcp_step's + # diagnostic sink is the only place the full traceback lands. + redact_errors=True, + ) + except BaseException: + # Release the reservation on failure AND cancellation — a leak + # here would shrink the effective pool capacity for the rest of + # the run. + async with self._mcp_step_pool_guard: + self._mcp_step_pending -= 1 + raise + async with self._mcp_step_pool_guard: + self._mcp_step_pending -= 1 + self._mcp_step_managers[key] = manager + return manager + + def _pick_mcp_eviction_target(self, current_server: str) -> tuple[str, str] | None: + """Choose one pool entry to evict for ``current_server``, or None. + + CALLER HOLDS ``_mcp_step_pool_guard``. Eviction order: + + 1. Oldest entry of ``current_server``. The caller holds that server's + slot lock across this call, and every use of a server's entries + happens under its slot lock — so no entry of ``current_server`` + can be in flight and all are evictable. Without this arm, one + server with many cwds (a for_each over templated working_dirs) + could never evict anything: its own held lock marks every entry + "locked" and the pool would grow past the cap. + 2. Oldest entry of any other server whose per-server slot lock is + unheld (a held lock means a call is in flight against that entry; + closing it mid-call is forbidden). + 3. None — every entry is locked; the caller allows the overflow + rather than blocking (the cap is a soft threshold). + """ + target: tuple[str, str] | None = next( + (key for key in self._mcp_step_managers if key[0] == current_server), + None, + ) + if target is None: + for pool_key in self._mcp_step_managers: + lock = self._mcp_step_locks.get(pool_key[0]) + if lock is None or not lock.locked(): + target = pool_key + break + return target + + async def _close_evicted_mcp_step_manager( + self, evicted_key: tuple[str, str], evicted: MCPManager + ) -> None: + """Close an evicted pool manager without swallowing task cancellation. + + :meth:`MCPManager.close` deliberately absorbs ``CancelledError`` until + owner-task teardown completes (task-affine MCP contexts must not be + orphaned). Awaited directly, that means a workflow cancellation (or a + fail-fast sibling) landing mid-close would be swallowed here and the + caller would carry on to connect — and then invoke a new tool call — + after the workflow was cancelled. So the close runs as its own + shielded task: repeated cancellation is tolerated while teardown + drains, then ``CancelledError`` is re-raised BEFORE the caller goes + on to connect or invoke anything. The close itself stays best-effort: + a failing close is logged and never fails the run. + """ + cleanup = asyncio.ensure_future(evicted.close()) + cancelled = False + while True: + try: + await asyncio.shield(cleanup) + break + except asyncio.CancelledError: + cancelled = True + if cleanup.done(): + break + exc = cleanup.exception() if cleanup.done() else None + if isinstance(exc, Exception): + logger.warning("Error closing evicted MCP manager for %s: %s", evicted_key, exc) + if cancelled: + raise asyncio.CancelledError + + async def _close_mcp_step_managers(self) -> None: + """Close every pooled MCP manager (best-effort) and clear the pool.""" + # Unconditional: the lock dict must be cleared even when the pool is + # empty (reachable after a failed connect, which creates a slot lock + # without pooling a manager), and clearing happens before closing so + # the pool is consistent even if a close raises. + managers = list(self._mcp_step_managers.items()) + self._mcp_step_managers.clear() + self._mcp_step_locks.clear() + for key, manager in managers: + try: + await manager.close() + except Exception as e: # noqa: BLE001 - cleanup must not mask the run outcome + logger.warning("Error closing MCP manager for %s: %s", key, e) + def _resolve_agent_directory( self, agent: AgentDef, @@ -603,6 +950,7 @@ def _resolve_agent_directory( ) -> str: """Render and absolutize one authored directory value. + Shared by ``working_dir`` and ``settings_dir`` so the two cannot drift apart: the raw value is Jinja-rendered against the per-agent context (so templates such as ``{{ item }}`` in for-each work at either @@ -1485,6 +1833,372 @@ async def _run_set_step(self, agent: AgentDef, agent_context: dict[str, Any]) -> ) return set_output + async def _run_mcp_step( + self, + agent: AgentDef, + agent_context: dict[str, Any], + *, + event_fields: Mapping[str, Any] | None = None, + allow_interrupt: bool = False, + ) -> dict[str, Any]: + """Execute an mcp step end-to-end with events and output validation. + + Shared between the main dispatch loop (``event_fields=None``) and + parallel / for-each groups (``event_fields`` carries ``group_name`` / + ``item_key`` so per-item events can be told apart). + + Lifecycle is strict: the timer starts, ``mcp_started`` is emitted, + then ONE ``try`` block covers the runtime checks, the slot-locked + connect + tool existence check + invoke, and the ``output:`` schema + validation. Failures split into three arms: + + - Authored, value-free errors (unknown server, non-stdio transport, + disallowed/missing tool, the cwd check, a per-call timeout) emit + ``mcp_failed`` carrying their authored message and propagate + verbatim. + - ``_McpStepInterrupted`` (only reachable when ``allow_interrupt``) + is control flow, not a failure: no ``mcp_failed``, and the + main-loop caller routes into the dashboard/CLI pause flow. + - Every other exception is REDACTED: raw exception text can carry + argument or result values, so events and the raised + ``ExecutionError`` carry only a generic message pointing at the + private per-run diagnostic file (:meth:`_write_mcp_diagnostic`), + the one place the full traceback lands. This arm is deliberately + ``BaseException``: a value-bearing ``SystemExit`` from SDK / + mcp_auth / connect / renderer code would otherwise bypass the + handler and publish the value via ``str(e)`` in + ``workflow_failed``. + + The runtime checks mirror the static validator because + ``conductor run`` never calls it: the server must be declared in + ``runtime.mcp_servers``, be stdio, and allow the tool — plus the + tool must actually exist on the connected server, which only a live + connection can prove. The whole call runs under the per-server slot + lock, serializing concurrent executions against one server process. + + Args: + agent: The mcp step definition. + agent_context: Render context for ``arguments``. + event_fields: Extra fields merged into every ``mcp_*`` payload + (group membership / item identity). + allow_interrupt: Watch ``self._interrupt_event`` during the + slot/connect/call waits and raise ``_McpStepInterrupted`` + when it fires. Only the main loop passes True — group + members mirror LLM group members, which never receive the + interrupt signal mid-call either. + + Callers are responsible for storing the returned envelope in context, + recording iteration, and evaluating routes. + """ + # Guaranteed by AgentDef.validate_agent_type (config/schema.py) for + # type == "mcp": both fields are required and non-empty. + assert agent.server is not None + assert agent.tool is not None + server = agent.server + tool = agent.tool + extra = dict(event_fields or {}) + + iteration = self.limits.get_agent_execution_count(agent.name) + 1 + start = _time.time() + self._emit( + "mcp_started", + { + "agent_name": agent.name, + "iteration": iteration, + "server": server, + "tool": tool, + "argument_keys": sorted((agent.arguments or {}).keys()), + **extra, + }, + ) + + try: + # Runtime half of the static validator checks (conductor run + # never calls the validator). Unknown server short-circuits so + # the allowlist/transport checks don't cascade. + mcp_servers = self.config.workflow.runtime.mcp_servers + if server not in mcp_servers: + available = ", ".join(sorted(mcp_servers)) or "(none)" + raise _McpStepRuntimeCheckError( + f"MCP step '{agent.name}' references unknown server " + f"'{server}'. Available servers: {available}", + agent_name=agent.name, + ) + server_def = mcp_servers[server] + if server_def.type != "stdio": + raise _McpStepRuntimeCheckError( + f"MCP step '{agent.name}': server '{server}' has type " + f"'{server_def.type}'; type: mcp supports stdio servers only " + f"(http/sse support is not implemented yet)", + agent_name=agent.name, + ) + # Wildcard rule mirrors the static validator exactly + # (config/validator.py::_validate_mcp_steps): a ``"*"`` MEMBER + # means unrestricted, so a mixed list like ["*", "health"] is + # accepted here precisely when validate accepts it. + if "*" not in server_def.tools and tool not in server_def.tools: + raise _McpStepRuntimeCheckError( + f"MCP step '{agent.name}': tool '{tool}' is not enabled on " + f"server '{server}' (enabled tools: {server_def.tools})", + agent_name=agent.name, + ) + + # Resolve the server process cwd under THIS execution's context, + # by the same rules as _resolve_agent_working_dir (render Jinja + # -> expanduser -> normpath against the workflow dir -> existence + # check). Per-step working_dir is forbidden by the schema, so + # only the runtime-level value renders. + raw_cwd = self.config.workflow.runtime.working_dir + if raw_cwd is None: + resolved_cwd = os.path.normpath( + str(self._workflow_dir) if self._workflow_dir is not None else os.getcwd() + ) + else: + rendered_cwd = self.renderer.render(raw_cwd, agent_context) + cwd_path = Path(rendered_cwd).expanduser() + if not cwd_path.is_absolute(): + base = self._workflow_dir if self._workflow_dir is not None else Path.cwd() + cwd_path = base / cwd_path + resolved_cwd = os.path.normpath(cwd_path) + if not Path(resolved_cwd).is_dir(): + # Redacted on purpose: resolved_cwd and raw_cwd are + # Jinja-rendered from the execution context and can carry + # values (e.g. "{{ item.secret_path }}"). They land only + # in the private diagnostic file; the propagated message + # names the failure, nothing else. + diag = self._write_mcp_diagnostic( + agent_name=agent.name, + server=server, + tool=tool, + detail=( + f"runtime working_dir does not exist or is not a directory: " + f"resolved={resolved_cwd!r} rendered_from={raw_cwd!r}" + ), + ) + raise _McpStepRedactedCheckError( + f"MCP step '{agent.name}': runtime working_dir does not exist " + f"or is not a directory{self._diagnostic_suffix(diag)}", + agent_name=agent.name, + ) + + async def _invoke_under_slot() -> dict[str, Any]: + async with await self._mcp_step_slot(server): + manager = await self._get_mcp_step_manager(server, resolved_cwd) + # The static validator cannot check this: the tool must + # actually exist on the connected server. + server_tools = { + t.get("original_name") or t.get("name", "") + for t in manager.get_server_tools(server) + } + if tool not in server_tools: + raise _McpStepRuntimeCheckError( + f"MCP step '{agent.name}': tool '{tool}' does not exist " + f"on server '{server}'", + agent_name=agent.name, + ) + return await self.mcp_step_executor.execute(agent, agent_context, manager) + + if allow_interrupt and self._interrupt_event is not None: + envelope = await self._invoke_mcp_interruptible(agent, _invoke_under_slot()) + else: + envelope = await _invoke_under_slot() + + # `output:` schema validation runs here so the contract holds in + # the main loop, parallel groups, and for-each alike (mirrors the + # set-step path). + if agent.output is not None: + validate_output(envelope, agent.output) + except ( + _McpStepRuntimeCheckError, + _McpStepRedactedCheckError, + McpStepTimeoutError, + ) as exc: + # Authored, value-free errors: the message is safe to surface as + # the event payload AND to propagate verbatim (the timeout keeps + # its duration, the name checks keep their literal config names). + elapsed = _time.time() - start + self._emit( + "mcp_failed", + { + "agent_name": agent.name, + "elapsed": elapsed, + "server": server, + "tool": tool, + "error_type": type(exc).__name__, + "message": str(exc), + **extra, + }, + ) + raise + except _McpStepInterrupted: + # Control flow, not a failure: no mcp_failed. The main-loop + # caller routes into the pause flow. + raise + except (asyncio.CancelledError, GeneratorExit): + # Cancellation is not a step failure: re-raise untouched with no + # mcp_failed, preserving the engine's cancellation semantics. + raise + except BaseException as exc: + elapsed = _time.time() - start + diag = self._write_mcp_diagnostic( + agent_name=agent.name, server=server, tool=tool, exc=exc + ) + self._emit( + "mcp_failed", + { + "agent_name": agent.name, + "elapsed": elapsed, + "server": server, + "tool": tool, + "error_type": type(exc).__name__, + "message": (f"MCP step '{agent.name}' failed{self._diagnostic_suffix(diag)}"), + **extra, + }, + ) + # Re-raise a generic redacted error so workflow_failed and group + # failure events stay value-free. The full exception (including + # the connect-time cause chain) is in the diagnostic file. + raise ExecutionError( + f"MCP step '{agent.name}' failed{self._diagnostic_suffix(diag)}", + agent_name=agent.name, + ) from None + elapsed = _time.time() - start + + content = envelope.get("content") + # Truncation markers are trusted here because call_tool_structured + # strips server-supplied fields of these names at ingestion — this + # envelope came straight from the live call. The synthetic replay + # path never republishes stored markers (see _synth_mcp_pair). + truncated, spill_path = mcp_truncation_metadata(content) + self._emit( + "mcp_completed", + { + "agent_name": agent.name, + "elapsed": elapsed, + "server": server, + "tool": tool, + "is_error": envelope.get("is_error", False), + "result_bytes": mcp_result_bytes(content, envelope.get("structured")), + "truncated": truncated, + "spill_path": spill_path, + **extra, + }, + ) + return envelope + + def _mcp_diagnostic_path(self) -> Path: + """Return the per-run private diagnostic file for mcp step failures. + + Sits next to the run's JSONL event log (``.mcp-diagnostics.log``) + when the CLI wired one — both ``run`` and ``resume`` always do — and + otherwise falls back to the shared ``$TMPDIR/conductor`` directory + keyed by run id. This file is the one place raw mcp step exception + text lands: events, checkpoints, and raised errors carry redacted + messages, and ``--log-file`` never sees them (it mirrors the console, + it is not a Python logging sink). + """ + log_file = self._run_context.log_file + if log_file: + path = Path(log_file) + name = path.name + events_suffix = ".events.jsonl" + if name.endswith(events_suffix): + name = name[: -len(events_suffix)] + return path.with_name(f"{name}.mcp-diagnostics.log") + run_id = self._run_id or f"pid-{os.getpid()}" + return Path(tempfile.gettempdir()) / "conductor" / f"{run_id}.mcp-diagnostics.log" + + @staticmethod + def _diagnostic_suffix(path: Path | None) -> str: + """Render the redacted-message pointer to the diagnostic file.""" + if path is None: + return "; diagnostic file could not be written (see stderr warning)" + return f"; full diagnostic: {path}" + + def _write_mcp_diagnostic( + self, + *, + agent_name: str, + server: str, + tool: str, + exc: BaseException | None = None, + detail: str | None = None, + ) -> Path | None: + """Append the full diagnostic for an mcp step failure to the private sink. + + Args: + agent_name: The failed step. + server: MCP server name (literal config). + tool: MCP tool name (literal config). + exc: The exception to dump with its full traceback (including the + ``__cause__`` chain), mutually exclusive with ``detail``. + detail: A precomposed detail string for failures that discarded + rendered values before raising (e.g. the cwd existence check), + mutually exclusive with ``exc``. + + Returns: + The sink path so the redacted public message can point at it, or + None when the write itself failed (best-effort — a diagnostics + failure must never mask the step failure). + """ + path = self._mcp_diagnostic_path() + try: + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "a", encoding="utf-8") as fh: + fh.write( + f"=== {_time.strftime('%Y-%m-%d %H:%M:%S')} step={agent_name!r} " + f"server={server!r} tool={tool!r} ===\n" + ) + if exc is not None: + fh.write("".join(traceback.format_exception(type(exc), exc, exc.__traceback__))) + elif detail is not None: + fh.write(detail) + fh.write("\n") + except OSError as write_exc: + logger.warning( + "Failed to write MCP step diagnostic for '%s': %s", agent_name, write_exc + ) + return None + return path + + async def _invoke_mcp_interruptible( + self, agent: AgentDef, invocation: Coroutine[Any, Any, dict[str, Any]] + ) -> dict[str, Any]: + """Race an mcp slot/connect/call invocation against a user Stop. + + When the interrupt wins, the in-flight call is cancelled and drained + (re-cancellation-proof, via the shared group-drain helper) and + :class:`_McpStepInterrupted` is raised — the call is NEVER auto- + replayed, because its external side effects are unknown (the + documented at-least-once semantics cover the explicit Resume + re-execution, not a transparent retry). The interrupt event itself + stays SET for the caller's pause flow to consume. A call that already + completed when the interrupt fires returns its result — the between- + step interrupt check handles the pending Stop as usual. + """ + assert self._interrupt_event is not None # guarded by the caller + call_task = asyncio.ensure_future(invocation) + stop_task = asyncio.ensure_future(self._interrupt_event.wait()) + try: + done, _pending = await asyncio.wait( + {call_task, stop_task}, return_when=asyncio.FIRST_COMPLETED + ) + except BaseException: + # The engine task itself was cancelled (Kill / teardown): cancel + # both arms so neither leaks past this await. + stop_task.cancel() + await _cancel_and_drain_group_tasks([call_task]) + with contextlib.suppress(asyncio.CancelledError): + await stop_task + raise + if call_task in done: + stop_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await stop_task + return call_task.result() + await _cancel_and_drain_group_tasks([call_task]) + raise _McpStepInterrupted(agent.name) + def _validate_script_output_schema( self, agent: AgentDef, @@ -2532,6 +3246,9 @@ async def run(self, inputs: dict[str, Any]) -> dict[str, Any]: try: result = await self._execute_loop(current_agent_name) finally: + # Best-effort shutdown of MCP step connections; each close runs + # in its own guard so a failing manager cannot mask the run outcome. + await self._close_mcp_step_managers() # The pricing verdict belongs to the run ending, not to anyone # asking for a summary. Drawing it here covers the run that dies # part way -- the case where "these numbers came from the static @@ -2574,6 +3291,7 @@ async def resume(self, current_agent_name: str) -> dict[str, Any]: try: result = await self._execute_loop(current_agent_name) finally: + await self._close_mcp_step_managers() # Same reasoning as :meth:`run` -- a resumed run that dies part way # is still a run that priced nothing. self._warn_if_pricing_hook_silent() @@ -3686,43 +4404,54 @@ async def _handle_interrupt_result( return current_agent_name async def _handle_web_pause( - self, agent_name: str, partial_output: AgentOutput + self, agent_name: str, partial_output: AgentOutput | None ) -> WebPauseOutcome: """Handle a mid-agent interrupt when the web dashboard is connected. Emits an ``agent_paused`` event and waits for the user to click Resume or Kill in the dashboard, or to submit guidance (issue #400). - If all browser clients disconnect while waiting, auto-resumes to - avoid hanging the workflow. + If all browser clients disconnect while waiting, the wait resolves + with ``reason="disconnect"`` (no ``agent_resumed`` is emitted): + whether that means auto-resume (the LLM path) or park as a + resumable stop (an interrupted ``type: mcp`` call) is the caller's + decision. Args: agent_name: The name of the interrupted agent. partial_output: The partial output from the interrupted agent. + ``None`` for a provider-free step (an interrupted ``type: + mcp`` call produces no partial content) — the pause preview + is then a fixed placeholder, never step data. Returns: A :class:`WebPauseOutcome`. ``handled=True`` means the pause was - resolved here (Resume clicked, guidance submitted, or all clients - disconnected) — ``guidance`` carries any submitted text(s), empty - for a plain Resume/disconnect. ``handled=False`` covers two - distinct cases the caller branches on separately: a dashboard is - attached but has no connected clients (auto-resume — there is no - one to wait on), or no dashboard is attached at all (fall + resolved here, with ``reason`` saying how: ``resume`` / ``guidance`` + are explicit user decisions, ``disconnect`` means every browser + client went away mid-pause (NOT a resume decision — the + ``agent_resumed`` event is deliberately not emitted on that arm; + the caller emits it only if it actually resumes). ``handled=False`` + (``reason="unavailable"``) covers two distinct cases the caller + branches on separately: a dashboard is attached but has no + connected clients, or no dashboard is attached at all (fall through to the CLI interactive handler, ``_handle_partial_output``). Raises: InterruptError: If the user chose Kill (``POST /api/kill``). """ if self._web_dashboard is None or not self._web_dashboard.has_connections(): - return WebPauseOutcome(False, []) + return WebPauseOutcome(False, [], reason="unavailable") - try: - # ``ensure_ascii=False`` so the preview shows real non-ASCII - # text instead of \uXXXX escapes (issue #356). - preview = json.dumps(partial_output.content, indent=2, default=str, ensure_ascii=False)[ - :500 - ] - except (TypeError, ValueError): - preview = str(partial_output.content)[:500] + if partial_output is None: + preview = "(no partial output available for this step)" + else: + try: + # ``ensure_ascii=False`` so the preview shows real non-ASCII + # text instead of \uXXXX escapes (issue #356). + preview = json.dumps( + partial_output.content, indent=2, default=str, ensure_ascii=False + )[:500] + except (TypeError, ValueError): + preview = str(partial_output.content)[:500] self._emit( "agent_paused", @@ -3836,13 +4565,24 @@ async def _handle_web_pause( resume_event.clear() self._emit("agent_resumed", {"agent_name": agent_name, "with_guidance": True}) logger.info("Agent '%s' resumed with guidance — re-executing", agent_name) - return WebPauseOutcome(True, texts) - - if disconnect_task in done: + return WebPauseOutcome(True, texts, reason="guidance") + + if disconnect_task in done and resume_task not in done: + # Deliberately NO agent_resumed on this arm: whether the + # interrupted work is actually re-executed is the caller's + # decision — the LLM path auto-resumes (and emits the event + # there), while an interrupted mcp call is parked as a resumable + # stop, where a resumed event would be a lie. Disconnecting is + # not a resume decision. An explicit Resume click completed in + # the same wait batch WINS over the disconnect and takes the + # shared resume path below: the user made the decision, the lost + # client is incidental. logger.info( - "All dashboard clients disconnected while '%s' was paused — auto-resuming", + "All dashboard clients disconnected while '%s' was paused", agent_name, ) + resume_event.clear() + return WebPauseOutcome(True, [], reason="disconnect") # Clear resume_event after consumption so a stale signal from a # double-click or prior API call doesn't skip the next legitimate pause. @@ -3850,7 +4590,7 @@ async def _handle_web_pause( self._emit("agent_resumed", {"agent_name": agent_name, "with_guidance": False}) logger.info("Agent '%s' resumed — re-executing", agent_name) - return WebPauseOutcome(True, []) + return WebPauseOutcome(True, [], reason="resume") async def _send_guidance_followup( self, @@ -5122,6 +5862,89 @@ async def _execute_loop(self, current_agent_name: str) -> dict[str, Any]: ) continue + # Handle mcp steps. Direct tool calls against a server + # from runtime.mcp_servers — no LLM involved. The + # result envelope (with merged structured keys) lands + # in context like set/script outputs, so routing on + # e.g. ``output.is_error`` works unchanged. + if agent.type == "mcp": + try: + mcp_envelope = await self._run_mcp_step( + agent, agent_context, allow_interrupt=True + ) + except _McpStepInterrupted: + # Stop landed mid-call: the call was cancelled + # and is NOT replayed here — its external side + # effects are unknown. The call is re-entered + # from the loop top ONLY on an explicit resume + # decision: a dashboard Resume/guidance, or the + # CLI interrupt menu. When no one can decide + # (every browser disconnected mid-pause, or the + # dashboard has no clients at all) the run + # parks as a resumable stop instead of silently + # repeating a side-effecting call — ``conductor + # resume`` is then the explicit at-least-once + # boundary. Kill unwinds via InterruptError. + pause_outcome = await self._handle_web_pause(agent.name, None) + if pause_outcome.handled: + if pause_outcome.reason == "disconnect": + raise _McpStepOutcomeUncertain(agent.name) from None + # Explicit Resume / guidance (the guidance + # was applied to context inside + # _handle_web_pause). + if self._interrupt_event is not None: + self._interrupt_event.clear() + continue + if self._web_dashboard is not None: + # Dashboard attached but zero clients: + # park rather than auto-resume (see + # above) — unlike the LLM branch, whose + # re-run only costs tokens. + raise _McpStepOutcomeUncertain(agent.name) from None + # No dashboard: the interrupt flag is still + # set, so the shared check presents the CLI + # interrupt menu and consumes it — every menu + # outcome is an explicit decision. + interrupt_result = await self._check_interrupt(agent.name) + if interrupt_result is not None: + current_agent_name = await self._handle_interrupt_result( + interrupt_result, agent.name + ) + continue + self.context.store(agent.name, mcp_envelope) + self.limits.record_execution(agent.name) + self.limits.check_timeout() + + route_result = self._evaluate_routes(agent, mcp_envelope) + + self._emit( + "route_taken", + { + "from_agent": agent.name, + "to_agent": route_result.target, + }, + ) + + if route_result.target == "$end": + result = self._build_final_output(route_result.output_transform) + self._emit( + "workflow_completed", + { + "elapsed": _time.time() - _workflow_start, + "output": result, + }, + ) + return result + + current_agent_name = route_result.target + + interrupt_result = await self._check_interrupt(current_agent_name) + if interrupt_result is not None: + current_agent_name = await self._handle_interrupt_result( + interrupt_result, current_agent_name + ) + continue + # Handle sub-workflow steps if agent.type == "workflow": _sub_start = _time.time() @@ -5233,6 +6056,16 @@ async def _execute_loop(self, current_agent_name: str) -> dict[str, Any]: if output.partial: pause_outcome = await self._handle_web_pause(agent.name, output) if pause_outcome.handled: + if pause_outcome.reason == "disconnect": + # _handle_web_pause deliberately emits no + # agent_resumed on the disconnect arm (an + # interrupted mcp step is parked, not + # resumed); the LLM path auto-resumes, so + # it emits the event here. + self._emit( + "agent_resumed", + {"agent_name": agent.name, "with_guidance": False}, + ) # Web mode: agent paused then resumed. Clear # interrupt_event to prevent a re-executed agent # from seeing the stale signal and returning @@ -6264,6 +7097,34 @@ async def execute_single_agent(agent: AgentDef) -> tuple[str, Any]: ) return (agent.name, set_output.value) + # `mcp` steps are provider-free tool calls; per-server + # serialization lives inside _run_mcp_step (slot lock). Like + # the set branch above: no `parallel_agent_started` (that + # event is LLM-only), and `parallel_agent_completed` carries + # no `output` field — the no-values policy for step events. + if agent.type == "mcp": + mcp_envelope = await self._run_mcp_step( + agent, + agent_context, + event_fields={"group_name": parallel_group.name}, + ) + _agent_elapsed = _time.time() - _agent_start + self._emit( + "parallel_agent_completed", + { + "group_name": parallel_group.name, + "agent_name": agent.name, + "elapsed": _agent_elapsed, + "model": "", + "tokens": 0, + "cost_usd": 0.0, + "context_window_used": 0, + "context_window_max": None, + "agent_type": "mcp", + }, + ) + return (agent.name, mcp_envelope) + # Resolve working_dir / settings_dir for provider-backed LLM agents against # this agent's own (pre-group snapshot) context. `set` steps # returned above; other types in a parallel group are LLM agents. @@ -6360,17 +7221,45 @@ async def execute_single_agent(agent: AgentDef) -> tuple[str, Any]: parallel_output = ParallelGroupOutput() if parallel_group.failure_mode == "fail_fast": - # Fail immediately on first error + # Fail immediately on first error. Tasks are created explicitly so + # that on failure the siblings can be cancelled and drained before + # propagating: gather() alone leaves them running, and an in-flight + # step (e.g. an mcp call) must not outlive the group — it would + # race manager cleanup in run()'s finally and emit late events + # after the failure. + tasks = [asyncio.ensure_future(execute_single_agent(agent)) for agent in agents] try: - results = await asyncio.gather( - *[execute_single_agent(agent) for agent in agents], - return_exceptions=False, - ) + # Shield the gather: the gathering future re-cascades every + # cancel() of this task to the children, and it stays pending + # while a cancelled child is still in cleanup — so a second + # cancel arriving mid-cleanup would re-cancel the child and + # kill its cleanup (_must_cancel). The except arm cancels each + # child exactly once instead; shield detaches the cascade. + results = await asyncio.shield(asyncio.gather(*tasks, return_exceptions=False)) # All succeeded for agent_name, output_content in results: parallel_output.outputs[agent_name] = output_content - except Exception as e: + except BaseException as e: + # BaseException, not Exception: a child completing with + # CancelledError (a BaseException) propagates out of gather + # WITHOUT entering an except-Exception arm, and external + # cancellation of this group lands here as CancelledError too + # — either way the siblings must be cancelled and drained + # before anything propagates, or an in-flight step (e.g. an + # mcp call) outlives the group and races manager cleanup in + # run()'s finally. The drain is re-cancellation-proof: a + # second cancel() arriving mid-drain must not abandon it. + await _cancel_and_drain_group_tasks(tasks) + + # Cancellation semantics are preserved by re-raising + # non-Exception base exceptions (CancelledError from a child + # or from external cancellation, GeneratorExit) unchanged — + # converting them to a group failure would defeat the + # engine's cancellation handling upstream. + if not isinstance(e, Exception): + raise + # Extract agent name and exception type from wrapped exception agent_name = getattr(e, "_parallel_agent_name", "unknown") exception_type = type(e).__name__ @@ -6742,6 +7631,31 @@ async def execute_single_item(item: Any, index: int, key: str) -> tuple[str, Any ) return (key, set_output.value) + # `mcp` steps per item: the item_key is only known here inside + # execute_single_item, so it rides event_fields into all three + # mcp_* payloads (merged inside _run_mcp_step). No `output` + # field on for_each_item_completed — deliberate divergence + # from the set branch above: mcp events follow the no-values + # policy, the envelope is data for routing, never for events. + if for_each_group.agent.type == "mcp": + mcp_envelope = await self._run_mcp_step( + for_each_group.agent, + agent_context, + event_fields={"group_name": for_each_group.name, "item_key": key}, + ) + _item_elapsed = _time.time() - _item_start + self._emit( + "for_each_item_completed", + { + "group_name": for_each_group.name, + "item_key": key, + "elapsed": _item_elapsed, + "tokens": 0, + "cost_usd": 0.0, + }, + ) + return (key, mcp_envelope) + # Qualify the per-iteration agent name so that any verbose # provider-side logging (e.g. CopilotProvider tool/reasoning # lines) can attribute interleaved output to a specific @@ -6873,15 +7787,22 @@ def _item_callback(event_type: str, data: dict[str, Any]) -> None: # Execute based on failure mode if for_each_group.failure_mode == "fail_fast": - # Fail immediately on first error - try: - results = await asyncio.gather( - *[ - execute_single_item(item, batch_start_idx + i, batch_keys[i]) - for i, item in enumerate(batch_items) - ], - return_exceptions=False, + # Fail immediately on first error. Explicit tasks + drain for + # the same reason as the parallel fail_fast branch: a sibling + # item still in flight (e.g. an mcp call) must be cancelled + # and awaited before the exception propagates. + tasks = [ + asyncio.ensure_future( + execute_single_item(item, batch_start_idx + i, batch_keys[i]) ) + for i, item in enumerate(batch_items) + ] + try: + # Shield for the same reason as the parallel fail_fast + # branch: a second cancel() of this task mid-cleanup must + # not re-cancel the items through the pending gathering + # future; the except arm cancels each item exactly once. + results = await asyncio.shield(asyncio.gather(*tasks, return_exceptions=False)) # All succeeded - store outputs for item_key, output_content in results: if for_each_group.key_by: @@ -6889,7 +7810,20 @@ def _item_callback(event_type: str, data: dict[str, Any]) -> None: else: for_each_output.outputs.append(output_content) # type: ignore[union-attr] - except Exception as e: + except BaseException as e: + # Same reasoning as the parallel fail_fast branch: a child + # completing with CancelledError, or external cancellation + # of this group, must still cancel+drain the in-flight + # sibling items before anything propagates. The drain is + # re-cancellation-proof: a second cancel() arriving + # mid-drain must not abandon it. + await _cancel_and_drain_group_tasks(tasks) + + # Preserve cancellation semantics (see the parallel + # fail_fast branch). + if not isinstance(e, Exception): + raise + # Extract item key from wrapped exception item_key = getattr(e, "_for_each_item_key", "unknown") exception_type = type(e).__name__ diff --git a/src/conductor/executor/__init__.py b/src/conductor/executor/__init__.py index 03c30204..e08894fd 100644 --- a/src/conductor/executor/__init__.py +++ b/src/conductor/executor/__init__.py @@ -5,6 +5,7 @@ """ from conductor.executor.agent import AgentExecutor, resolve_agent_tools +from conductor.executor.mcp_step import McpStepExecutor from conductor.executor.output import parse_json_output, validate_output from conductor.executor.script import ScriptExecutor, ScriptOutput from conductor.executor.template import TemplateRenderer @@ -12,6 +13,7 @@ __all__ = [ "AgentExecutor", + "McpStepExecutor", "ScriptExecutor", "ScriptOutput", "TemplateRenderer", diff --git a/src/conductor/executor/mcp_step.py b/src/conductor/executor/mcp_step.py new file mode 100644 index 00000000..76366334 --- /dev/null +++ b/src/conductor/executor/mcp_step.py @@ -0,0 +1,292 @@ +"""Execution for ``type: mcp`` workflow steps. + +An ``mcp`` step calls a tool on an MCP server configured in +``workflow.runtime.mcp_servers`` and stores the JSON-safe result envelope in +the workflow context. There is no LLM call — the step is a typed bridge +between the workflow engine and an MCP server. + +Argument rendering: + +- ``arguments`` values are Jinja2-rendered recursively: dicts and lists are + walked, string leaves are rendered against the workflow context, and each + FULLY RENDERED string is then YAML-parsed (the set-step ``auto`` rule). + Whatever the rendered text parses as is the value: ``"105"`` -> ``int``, + ``"true"`` -> ``bool``, ``"[1, 2]"`` -> ``list`` — including renders built + from embedded templates, so ``"1{{ x }}"`` with ``x=2`` renders ``"12"`` + and becomes the integer ``12``, and ``"label: {{ x }}"`` becomes a mapping. + A render that does not parse as YAML stays the raw string, and YAML-native + scalars (int / float / bool / None) pass through untouched. +- ``FileString`` values (from the ``!file`` tag) are ``str`` subclasses and + render like normal templates. + +The result envelope (produced by +:meth:`conductor.mcp.manager.MCPManager.call_tool_structured`) has the shape +``{"content": [...], "structured": {...}|null, "is_error": bool}``. When +``structured`` is a dict, its keys are merged on top of the envelope so routes +and templates can address individual result fields directly — except the +reserved keys (see :data:`_RESERVED_ENVELOPE_KEYS`), which are never +overridden (collisions are dropped with a debug-level log, mirroring the +script-step JSON shadow precedent in ``engine/workflow.py``). +""" + +from __future__ import annotations + +import asyncio +import json +import logging +from typing import TYPE_CHECKING, Any + +from ruamel.yaml.error import YAMLError + +from conductor.exceptions import ExecutionError +from conductor.executor.set_step import _to_json_safe, _yaml_load +from conductor.executor.template import TemplateRenderer + +if TYPE_CHECKING: + from conductor.config.schema import AgentDef + from conductor.mcp.manager import MCPManager + +logger = logging.getLogger(__name__) + +# Envelope keys owned by the MCP result envelope itself. A structured result +# carrying same-named keys must never override them — the merge drops these +# collisions rather than corrupting the envelope contract. +# +# ``outputs`` / ``errors`` are envelope-external but equally reserved: +# ``WorkflowContext`` duck-types parallel/for-each group outputs by exactly +# those two top-level keys, so a structured result flattening them onto the +# envelope would make an ordinary step output misclassify as a group output +# (losing its normal ``.output`` wrapper in all three context modes) and would +# confuse for-each source resolution. They stay reachable under +# ``output.structured.outputs`` / ``output.structured.errors``. +_RESERVED_ENVELOPE_KEYS = frozenset({"content", "structured", "is_error", "outputs", "errors"}) + +# Explicit null markers recognised by the auto-coercion rule; a render that +# parses to None through any other string keeps its raw form (mirrors the +# set-step auto rule). +_NULL_MARKERS = frozenset({"null", "~", "Null", "NULL"}) + + +def mcp_result_bytes(content: Any, structured: Any) -> int: + """Compute the UTF-8 byte size of an MCP result envelope. + + This is the single result-size contract shared by the live engine events + and the web server's synthetic replay path — both must measure the same + payload the same way. ``ensure_ascii=False`` keeps multibyte text as-is so + the byte count reflects the actual UTF-8 encoding, and the compact + separators make the measurement independent of formatting. + + Args: + content: The envelope's ``content`` block list. + structured: The envelope's ``structured`` mapping (or ``None``). + + Returns: + The byte length of the JSON-encoded ``{"content", "structured"}`` + payload. + """ + return len( + json.dumps( + {"content": content, "structured": structured}, + ensure_ascii=False, + separators=(",", ":"), + ).encode("utf-8") + ) + + +def mcp_truncation_metadata(content: Any) -> tuple[bool, str | None]: + """Extract the trusted truncation markers from a LIVE result envelope. + + ``truncated`` and ``spill_path`` on a content block are Conductor-local + metadata: :meth:`conductor.mcp.manager.MCPManager.call_tool_structured` + strips any server-supplied fields of those names at ingestion and only + its own truncation pass sets them. This helper is therefore called ONLY + on a freshly returned envelope — the engine's live ``mcp_completed`` + event — never on a checkpoint-restored one: a checkpoint may have been + written before the ingestion stripping existed, so a stored + ``spill_path`` can be a server-supplied string. The web server's + synthetic replay path does not republish stored markers at all (see + ``WebDashboard._synth_mcp_pair``). The defensive type checks remain + because the live contract is only ever a list of dict blocks. + + Args: + content: The envelope's ``content`` value (expected list of dicts). + + Returns: + ``(truncated, spill_path)`` — ``truncated`` is True when any block was + locally truncated; ``spill_path`` is the first local spill path (a + non-empty string) or ``None``. + """ + blocks = content if isinstance(content, list) else [] + truncated = any(isinstance(b, dict) and b.get("truncated") is True for b in blocks) + spill_path = next( + ( + b["spill_path"] + for b in blocks + if isinstance(b, dict) and isinstance(b.get("spill_path"), str) and b["spill_path"] + ), + None, + ) + return truncated, spill_path + + +class McpStepTimeoutError(ExecutionError): + """A ``type: mcp`` step's per-call ``timeout`` elapsed. + + A distinct, value-free category: the message (``timed out after Ns``) is + authored at the raise site and safe to surface verbatim, so the engine + propagates it unchanged (unlike transport/render/validation failures, + whose raw text can embed argument or result values and is redacted). + """ + + +class McpStepExecutor: + """Executes ``type: mcp`` workflow steps. + + Renders the step's ``arguments`` recursively against the workflow context, + invokes the tool through the supplied :class:`MCPManager`, and returns the + JSON-safe result envelope with ``structured`` keys merged on top. + + The renderer instance is reused across invocations to avoid Jinja2 + environment churn. + """ + + def __init__(self) -> None: + """Initialize the executor with a shared template renderer.""" + self.renderer = TemplateRenderer() + + async def execute( + self, + agent: AgentDef, + agent_context: dict[str, Any], + manager: MCPManager, + ) -> dict[str, Any]: + """Render arguments, call the MCP tool, and merge the result envelope. + + Args: + agent: Agent definition with ``type == "mcp"``. + agent_context: Workflow context for template rendering. + manager: Connected MCP manager owning the target server's session. + + Returns: + The JSON-safe envelope ``{"content": [...], "structured": dict | + None, "is_error": bool}`` with ``structured`` keys merged on top + (reserved keys are never overridden — see + :data:`_RESERVED_ENVELOPE_KEYS`). + + Raises: + McpStepTimeoutError: If the call exceeds ``agent.timeout`` seconds. + ValueError: Unknown server / tool — propagated from the manager. + RuntimeError: Call failure or malformed structured content — + propagated from the manager. + """ + # Guaranteed by AgentDef.validate_agent_type (config/schema.py) for + # type == "mcp": both fields are required and non-empty. + assert agent.server is not None + assert agent.tool is not None + label = f"mcp step '{agent.name}'" + rendered = _render_arguments(self.renderer, agent.arguments or {}, agent_context, label) + result = _to_json_safe(rendered, label) + + coro = manager.call_tool_structured(agent.server, agent.tool, result) + timeout = agent.timeout + try: + if timeout is not None: + envelope = await asyncio.wait_for(coro, timeout=timeout) + else: + envelope = await coro + except TimeoutError: + raise McpStepTimeoutError( + f"MCP step '{agent.name}' timed out after {timeout}s", + agent_name=agent.name, + ) from None + + structured = envelope.get("structured") + if isinstance(structured, dict): + shadowed = set(structured) & _RESERVED_ENVELOPE_KEYS + if shadowed: + logger.debug( + "MCP step '%s' structured content shadows envelope fields: %s", + agent.name, + ", ".join(sorted(shadowed)), + ) + envelope.update( + {key: value for key, value in structured.items() if key not in shadowed} + ) + return envelope + + +def _render_arguments( + renderer: TemplateRenderer, + value: Any, + context: dict[str, Any], + label: str, +) -> Any: + """Recursively render string leaves of an ``arguments`` mapping. + + Dicts and lists are walked recursively; string leaves are Jinja2-rendered + against the workflow context and coerced with the set-step ``auto`` rule. + ``FileString`` values (from the ``!file`` tag) are ``str`` subclasses and + render like normal templates, yielding plain strings. All other YAML-native + scalars (int / float / bool / None) pass through unchanged. + + Args: + renderer: Template renderer instance. + value: The value to render (dict / list / scalar). + context: Workflow context for template rendering. + label: Human-readable label for error messages (grows with nesting). + + Returns: + The rendered value with the same container shape. + """ + if isinstance(value, dict): + return { + key: _render_arguments(renderer, sub, context, f"{label}.{key}") + for key, sub in value.items() + } + if isinstance(value, (list, tuple)): + return [_render_arguments(renderer, item, context, label) for item in value] + if isinstance(value, str): + rendered = renderer.render(value, context) + return _coerce_auto(rendered, label) + return value + + +def _coerce_auto(rendered: str, label: str) -> Any: + """Coerce a rendered template string using the set-step ``auto`` rule. + + The WHOLE rendered string is YAML-parsed and whatever it parses as is the + value: a scalar (``"105"`` -> ``int``, ``"true"`` -> ``bool``, ``"null"`` + -> ``None``) or a collection (``"[1, 2]"`` -> ``list``, ``"a: 1"`` -> + ``dict``). This applies to embedded templates too — ``"1{{ x }}"`` with + ``x=2`` renders ``"12"`` and becomes the integer ``12``; only renders + whose text parses as a plain string (e.g. ``"pre-{{ x }}"`` -> + ``"pre-2"``, multi-word prose) stay strings. Empty and whitespace-only + renders bind ``""`` rather than ``None``. A render that parses to ``None`` + through any string other than an explicit null marker keeps its raw form, + so users don't get a surprise null argument. + + Args: + rendered: The template's rendered string output. + label: Human-readable label for debug messages. + + Returns: + The coerced, JSON-safe-by-construction value. + """ + stripped = rendered.strip() + if not stripped: + return "" + try: + parsed = _yaml_load(rendered) + except YAMLError: + # Best-effort fallback: a malformed render passes the raw string so + # the MCP tool (or its schema validation) surfaces the issue. Logged + # at debug level, mirroring the set-step auto rule. + logger.debug( + "%s: yaml.safe_load failed for auto-detect; using raw string", + label, + exc_info=True, + ) + return rendered + if parsed is None and stripped not in _NULL_MARKERS: + return rendered + return parsed diff --git a/src/conductor/fleet/summary.py b/src/conductor/fleet/summary.py index 6695c566..ffec4658 100644 --- a/src/conductor/fleet/summary.py +++ b/src/conductor/fleet/summary.py @@ -433,6 +433,7 @@ def stream_event_log( "script_completed", "wait_completed", "set_completed", + "mcp_completed", "gate_resolved", "subworkflow_completed", "parallel_agent_completed", @@ -459,6 +460,7 @@ def stream_event_log( "script_failed", "wait_failed", "set_failed", + "mcp_failed", "subworkflow_failed", } ) diff --git a/src/conductor/mcp/manager.py b/src/conductor/mcp/manager.py index a4a4283b..349254b3 100644 --- a/src/conductor/mcp/manager.py +++ b/src/conductor/mcp/manager.py @@ -146,6 +146,7 @@ async def connect_server( env: dict[str, str] | None = None, timeout: int | None = None, cwd: str | None = None, + redact_errors: bool = False, ) -> list[dict[str, Any]]: """Connect to an MCP server and return its tools. @@ -161,6 +162,14 @@ async def connect_server( cwd: Working directory for the spawned server process. When None, the server inherits the conductor process's current working directory (pre-pool legacy behavior). + redact_errors: When True, a connection failure is logged with + safe metadata only (server name; no exception text or + traceback — the exception a stdio failure carries can embed + server-supplied stderr, which may contain values the caller's + redaction policy excludes). The raised ``RuntimeError`` still + chains the original exception for the caller's own diagnostic + sink. Deterministic ``type: mcp`` steps use this; the default + preserves the existing provider-facing logging behavior. Returns: List of tool definitions from this server. Each tool dict contains: @@ -274,7 +283,14 @@ async def own_connection_lifecycle() -> None: self._connection_tasks.pop(name, None) self._connection_stops.pop(name, None) self._discard_server_state(name) - logger.error(f"Failed to connect to MCP server '{name}': {exc}", exc_info=exc) + if redact_errors: + logger.error( + "Failed to connect to MCP server '%s' " + "(details redacted; see the MCP step diagnostic file)", + name, + ) + else: + logger.error(f"Failed to connect to MCP server '{name}': {exc}", exc_info=exc) raise RuntimeError(f"Failed to connect to MCP server '{name}': {exc}") from exc logger.info( @@ -368,6 +384,121 @@ async def call_tool( logger.error(f"MCP tool call failed: {prefixed_name}: {e}") raise RuntimeError(f"MCP tool call failed: {prefixed_name}: {e}") from e + async def call_tool_structured( + self, + server_name: str, + tool_name: str, + arguments: dict[str, Any], + ) -> dict[str, Any]: + """Call a tool on a named server and return a JSON-safe structured envelope. + + Unlike :meth:`call_tool`, this keeps the result as structured data + instead of flattening it to a string, for ``type: mcp`` workflow steps. + + The returned envelope has the shape:: + + {"content": [...], "structured": dict | None, "is_error": bool} + + where each entry of ``content`` is a JSON-safe dict produced by + ``block.model_dump(mode="json")`` (with a ``{"type", "text"}`` fallback + for blocks that are not pydantic models). ``structured`` is read from + the ``structuredContent``/``structured_content`` field and is strictly + ``dict | None`` — any other shape is a malformed MCP response. + ``is_error`` mirrors the result's error flag. + + The per-result text budget (``runtime.tool_output``) applies to TEXT + blocks only: when the combined text length exceeds ``max_chars``, + blocks are walked in order and each keeps ``min(len(text), remaining)`` + characters, where ``remaining`` starts at ``max_chars``. Every + truncated block gets ``"truncated": true`` and, when spilling is + enabled, a ``"spill_path"`` written by :meth:`_spill_full_output` + holding that block's FULL original text. ``structured`` is structural + data and is NEVER truncated. + + Logging contract: this method emits no log records at all, so argument + values, result values, and exception text can never leak into logs. + + Args: + server_name: Name of the connected MCP server. + tool_name: Tool name as exposed by the server (no server prefix). + arguments: Tool input arguments matching the tool's input schema. + + Returns: + The envelope described above. + + Raises: + ValueError: If the server is unknown. + RuntimeError: If the server has no live session, the call fails, + or the response carries malformed structured content. + """ + if server_name not in self.sessions: + raise ValueError(f"Unknown server: {server_name}") + session = self.sessions[server_name] + if not session: + raise RuntimeError(f"No session for server: {server_name}") + + try: + result = await session.call_tool(tool_name, arguments=arguments) + except Exception as e: + raise RuntimeError(f"MCP tool call failed: {tool_name}: {e}") from e + + content: list[dict[str, Any]] = [] + for block in result.content or []: + try: + dumped = block.model_dump(mode="json") + except Exception: + dumped = {"type": getattr(block, "type", "unknown"), "text": str(block)} + # ``truncated`` / ``spill_path`` are Conductor-local metadata + # generated by the truncation pass below — a server must not set + # them. A forged ``spill_path`` would otherwise be forwarded into + # ``mcp_completed`` as trusted metadata (leaking result data the + # no-values policy excludes, and breaking the frontend's ``str`` + # type for that field); strip any server-supplied values here so + # live events and checkpoint/replay reads stay trusted. + dumped.pop("truncated", None) + dumped.pop("spill_path", None) + content.append(dumped) + + structured = _mcp_field(result, "structured_content", "structuredContent") + if structured is not None and not isinstance(structured, dict): + raise RuntimeError( + f"MCP tool '{tool_name}' on server '{server_name}' returned malformed " + "structured content (expected a dict or null)" + ) + + if self._tool_output.enabled: + max_chars = self._tool_output.max_chars + text_total = sum( + len(block["text"]) + for block in content + if block.get("type") == "text" and isinstance(block.get("text"), str) + ) + if text_total > max_chars: + remaining = max_chars + for block in content: + if block.get("type") != "text" or not isinstance(block.get("text"), str): + continue + text = block["text"] + kept = min(len(text), max(remaining, 0)) + if kept < len(text): + block["text"] = text[:kept] + block["truncated"] = True + if self._tool_output.spill_to_file: + spill_path = self._spill_full_output( + full_text=text, + server_name=server_name, + original_name=tool_name, + ) + if spill_path: + block["spill_path"] = spill_path + remaining -= kept + + return { + "content": content, + "structured": structured, + "is_error": bool(_mcp_field(result, "is_error", "isError")), + } + def _maybe_truncate_response( self, response_text: str, diff --git a/src/conductor/web/frontend/src/components/detail/DetailPanel.tsx b/src/conductor/web/frontend/src/components/detail/DetailPanel.tsx index 848d23ea..f19c1291 100644 --- a/src/conductor/web/frontend/src/components/detail/DetailPanel.tsx +++ b/src/conductor/web/frontend/src/components/detail/DetailPanel.tsx @@ -6,6 +6,7 @@ import { parseNodeKey } from '@/lib/node-id'; import { AgentDetail } from './AgentDetail'; import { ScriptDetail } from './ScriptDetail'; import { SetDetail } from './SetDetail'; +import { McpDetail } from './McpDetail'; import { GateDetail } from './GateDetail'; import { QuestionsDetail } from './QuestionsDetail'; import { GroupDetail } from './GroupDetail'; @@ -55,6 +56,8 @@ export function DetailPanel() { return WaitDetail; case 'set': return SetDetail; + case 'mcp': + return McpDetail; case 'human_gate': return GateDetail; case 'questions': diff --git a/src/conductor/web/frontend/src/components/detail/GroupDetail.tsx b/src/conductor/web/frontend/src/components/detail/GroupDetail.tsx index b97c900b..2b114add 100644 --- a/src/conductor/web/frontend/src/components/detail/GroupDetail.tsx +++ b/src/conductor/web/frontend/src/components/detail/GroupDetail.tsx @@ -128,13 +128,17 @@ function ForEachItemRow({ groupName, item }: { groupName: string; item: ForEachI item.prompt || item.output != null || (item.activity && item.activity.length > 0) || - item.error_type + item.error_type || item.mcp_server != null ); const metadataItems: Array<{ label: string; value: string | number | null | undefined }> = []; if (item.elapsed != null) metadataItems.push({ label: 'Elapsed', value: formatElapsed(item.elapsed) }); if (item.tokens != null) metadataItems.push({ label: 'Tokens', value: formatTokens(item.tokens) }); if (item.cost_usd != null) metadataItems.push({ label: 'Cost', value: formatCost(item.cost_usd) }); + if (item.mcp_server) metadataItems.push({ label: 'Server', value: item.mcp_server }); + if (item.mcp_tool) metadataItems.push({ label: 'Tool', value: item.mcp_tool }); + if (item.mcp_result_bytes != null) metadataItems.push({ label: 'Result Bytes', value: `${item.mcp_result_bytes}${item.mcp_truncated ? ' (truncated)' : ''}` }); + if (item.mcp_spill_path) metadataItems.push({ label: 'Spill Path', value: item.mcp_spill_path }); return (
@@ -215,6 +219,13 @@ function ForEachItemRow({ groupName, item }: { groupName: string; item: ForEachI )} + {/* MCP Is Error warning */} + {item.mcp_is_error === true && ( +
+ Tool reported an error (is_error) +
+ )} + {/* Prompt / Input */} {item.prompt && ( diff --git a/src/conductor/web/frontend/src/components/detail/McpDetail.tsx b/src/conductor/web/frontend/src/components/detail/McpDetail.tsx new file mode 100644 index 00000000..8b4f2a99 --- /dev/null +++ b/src/conductor/web/frontend/src/components/detail/McpDetail.tsx @@ -0,0 +1,45 @@ +import { MetadataGrid } from './MetadataGrid'; +import type { NodeData } from '@/stores/workflow-store'; +import { NODE_STATUS_HEX } from '@/lib/constants'; +import { formatElapsed } from '@/lib/utils'; +import type { NodeStatus } from '@/lib/constants'; + +interface McpDetailProps { + node: NodeData; +} + +export function McpDetail({ node }: McpDetailProps) { + const status = node.status as NodeStatus; + const statusColor = NODE_STATUS_HEX[status] || NODE_STATUS_HEX.pending; + + const items: Array<{ label: string; value: string | number | null | undefined }> = []; + if (node.elapsed != null) items.push({ label: 'Elapsed', value: formatElapsed(node.elapsed) }); + if (node.mcp_server) items.push({ label: 'Server', value: node.mcp_server }); + if (node.mcp_tool) items.push({ label: 'Tool', value: node.mcp_tool }); + if (node.mcp_is_error !== undefined) items.push({ label: 'Is Error', value: String(node.mcp_is_error) }); + if (node.mcp_result_bytes != null) items.push({ label: 'Result Bytes', value: `${node.mcp_result_bytes}${node.mcp_truncated ? ' (truncated)' : ''}` }); + if (node.mcp_spill_path) items.push({ label: 'Spill Path', value: node.mcp_spill_path }); + + if (node.error_type) items.push({ label: 'Error', value: node.error_type }); + if (node.error_message) items.push({ label: 'Message', value: node.error_message }); + + return ( +
+ {/* Status badge */} +
+ + {status} + + MCP +
+ + +
+ ); +} diff --git a/src/conductor/web/frontend/src/components/graph/McpNode.tsx b/src/conductor/web/frontend/src/components/graph/McpNode.tsx new file mode 100644 index 00000000..9c3a1e60 --- /dev/null +++ b/src/conductor/web/frontend/src/components/graph/McpNode.tsx @@ -0,0 +1,150 @@ +import { memo, useEffect, useRef, useState } from 'react'; +import { Handle, Position, type NodeProps } from '@xyflow/react'; +import { Blocks } from 'lucide-react'; +import { cn, formatElapsed } from '@/lib/utils'; +import { NODE_STATUS_HEX } from '@/lib/constants'; +import { useWorkflowStore } from '@/stores/workflow-store'; +import { useNodeLiveData } from '@/hooks/use-viewed-context'; +import { NodeTooltip } from './NodeTooltip'; +import type { GraphNodeData } from './graph-layout'; +import type { NodeStatus } from '@/lib/constants'; + +export const McpNode = memo(function McpNode({ data, selected }: NodeProps) { + const nodeData = data as unknown as GraphNodeData; + const nd = useNodeLiveData(nodeData); + const storeStatus = nd?.status; + const status = (storeStatus || nodeData.status || 'pending') as NodeStatus; + const borderColor = NODE_STATUS_HEX[status] || NODE_STATUS_HEX.pending; + + const elapsed = nd?.elapsed; + const errorType = nd?.error_type; + const errorMessage = nd?.error_message; + + const mcpServer = nd?.mcp_server; + const mcpTool = nd?.mcp_tool; + const mcpResultBytes = nd?.mcp_result_bytes; + const mcpTruncated = nd?.mcp_truncated; + + const liveElapsed = useLiveElapsed(nd?.startedAt, status); + const transitionClass = useStatusTransition(status); + + const statsLine = (() => { + if (status === 'failed' && errorMessage) { + const msg = errorMessage.length > 40 ? errorMessage.slice(0, 37) + '...' : errorMessage; + return { text: msg, className: 'text-red-400' }; + } + if (status === 'running') { + return { text: liveElapsed, className: 'text-[var(--text-muted)]' }; + } + if (status === 'completed') { + const parts: string[] = []; + if (elapsed != null) parts.push(formatElapsed(elapsed)); + if (mcpServer && mcpTool) { + parts.push(`${mcpServer}/${mcpTool}`); + } + if (mcpResultBytes != null) { + parts.push(`${mcpResultBytes}B${mcpTruncated ? ' (!)' : ''}`); + } + return { text: parts.join(' · ') || null, className: 'text-[var(--text-muted)]' }; + } + return { text: null, className: '' }; + })(); + + return ( + <> + + +
+
+ +
+
+ {nodeData.label} + {statsLine.text && ( + + {statsLine.text} + + )} +
+
+
+ + + ); +}); + +function useLiveElapsed(startedAt: number | undefined, status: NodeStatus): string { + const replayMode = useWorkflowStore((s) => s.replayMode); + const lastEventTime = useWorkflowStore((s) => s.lastEventTime); + const [display, setDisplay] = useState('0.0s'); + const rafRef = useRef | null>(null); + + useEffect(() => { + if (status === 'running') { + if (replayMode) { + if (rafRef.current) clearInterval(rafRef.current); + const origin = startedAt ?? (lastEventTime ?? 0); + const now = lastEventTime ?? origin; + setDisplay(formatElapsed(now - origin)); + return; + } + const origin = startedAt != null ? startedAt * 1000 : Date.now(); + const tick = () => { + const sec = (Date.now() - origin) / 1000; + setDisplay(formatElapsed(sec)); + }; + tick(); + rafRef.current = setInterval(tick, 1000); + return () => { + if (rafRef.current) clearInterval(rafRef.current); + }; + } else { + if (rafRef.current) clearInterval(rafRef.current); + } + }, [status, startedAt, replayMode, lastEventTime]); + + return display; +} + +function useStatusTransition(status: NodeStatus): string { + const prevStatusRef = useRef(status); + const [transitionClass, setTransitionClass] = useState(''); + + useEffect(() => { + const prev = prevStatusRef.current; + prevStatusRef.current = status; + if (prev === status) return; + + if (status === 'running') { + setTransitionClass('node-activate'); + } else if (prev === 'running' && (status === 'completed' || status === 'failed')) { + setTransitionClass(status === 'completed' ? 'node-complete' : 'node-fail'); + } + + const timer = setTimeout(() => setTransitionClass(''), 400); + return () => clearTimeout(timer); + }, [status]); + + return transitionClass; +} diff --git a/src/conductor/web/frontend/src/components/graph/WorkflowGraph.tsx b/src/conductor/web/frontend/src/components/graph/WorkflowGraph.tsx index a7ec26c2..a58e12e5 100644 --- a/src/conductor/web/frontend/src/components/graph/WorkflowGraph.tsx +++ b/src/conductor/web/frontend/src/components/graph/WorkflowGraph.tsx @@ -26,6 +26,7 @@ import { claimCameraForAnimation, isCameraAnimating } from '@/lib/camera-authori import { AgentNode } from './AgentNode'; import { ScriptNode } from './ScriptNode'; import { SetNode } from './SetNode'; +import { McpNode } from './McpNode'; import { GateNode } from './GateNode'; import { GroupNode } from './GroupNode'; import { WorkflowNode } from './WorkflowNode'; @@ -47,6 +48,7 @@ const nodeTypes: NodeTypes = { agentNode: AgentNode, scriptNode: ScriptNode, setNode: SetNode, + mcpNode: McpNode, gateNode: GateNode, groupNode: GroupNode, workflowNode: WorkflowNode, diff --git a/src/conductor/web/frontend/src/components/graph/graph-layout.test.ts b/src/conductor/web/frontend/src/components/graph/graph-layout.test.ts index ab730fc1..42c840c5 100644 --- a/src/conductor/web/frontend/src/components/graph/graph-layout.test.ts +++ b/src/conductor/web/frontend/src/components/graph/graph-layout.test.ts @@ -946,3 +946,33 @@ describe('buildGraphElements — for_each-of-workflow inline expansion', () => { ]); }); }); + +describe('graph-layout parallel group node types', () => { + // Requirement: Parallel group members must inherit their declared step type, not just 'agent' (Finding B). + it('assigns correct React Flow node types to parallel group members based on declared type', () => { + const { processEvent } = useWorkflowStore.getState(); + processEvent(event('workflow_started', { + name: 'root', + agents: [ + { name: 'mcp_member', type: 'mcp' }, + { name: 'script_member', type: 'script' } + ], + routes: [], + parallel_groups: [{ name: 'pg1', agents: ['mcp_member', 'script_member'] }], + for_each_groups: [], + entry_point: 'pg1', + })); + + const { nodes } = buildGraphElements(rootBase(), [], new Set()); + const mcpNode = nodes.find(n => n.id === nodeKey([], 'mcp_member'))!; + const scriptNode = nodes.find(n => n.id === nodeKey([], 'script_member'))!; + + expect(mcpNode).toBeDefined(); + expect(mcpNode.type).toBe('mcpNode'); + expect(mcpNode.data.type).toBe('mcp'); + + expect(scriptNode).toBeDefined(); + expect(scriptNode.type).toBe('scriptNode'); + expect(scriptNode.data.type).toBe('script'); + }); +}); diff --git a/src/conductor/web/frontend/src/components/graph/graph-layout.ts b/src/conductor/web/frontend/src/components/graph/graph-layout.ts index c3660e18..9992ca61 100644 --- a/src/conductor/web/frontend/src/components/graph/graph-layout.ts +++ b/src/conductor/web/frontend/src/components/graph/graph-layout.ts @@ -333,6 +333,17 @@ interface ContextLayout { height: number; } +function flowNodeTypeFor(nodeType: string): string { + if (nodeType === 'script') return 'scriptNode'; + if (nodeType === 'set') return 'setNode'; + if (nodeType === 'mcp') return 'mcpNode'; + if (nodeType === 'human_gate' || nodeType === 'questions') return 'gateNode'; + if (nodeType === 'workflow') return 'workflowNode'; + if (nodeType === 'wait') return 'waitNode'; + if (nodeType === 'terminate') return 'terminateNode'; + return 'agentNode'; +} + /** * Recursively lay out a single context and its inline-expanded descendants. * @@ -366,6 +377,7 @@ function layoutContext( const deferredNodes: Node[] = []; const deferredEdges: Edge[] = []; + const agentTypes = new Map(ctx.agents.map((a) => [a.name, (a.type || 'agent') as NodeType])); const agentToGroup = new Map(); for (const pg of ctx.parallelGroups) { for (const a of pg.agents) { @@ -404,9 +416,10 @@ function layoutContext( for (let i = 0; i < pg.agents.length; i++) { const agentName = pg.agents[i]!; const agentNd = ctx.nodes[agentName]; + const declaredType = (agentTypes.get(agentName) || 'agent') as NodeType; flowNodes.push({ id: nid(agentName), - type: 'agentNode', + type: flowNodeTypeFor(declaredType), position: { x: GROUP_PADDING_X, y: GROUP_PADDING_TOP + i * (NODE_HEIGHT + GROUP_CHILD_GAP), @@ -417,7 +430,7 @@ function layoutContext( label: agentName, name: agentName, contextPath: absPath, - type: 'agent', + type: declaredType, status: agentNd?.status || 'pending', }, }); @@ -486,13 +499,7 @@ function layoutContext( if (agentNames.has(a.name) || groupAgents.has(a.name)) continue; const nodeType = (a.type || 'agent') as NodeType; const nd = ctx.nodes[a.name]; - let flowNodeType = 'agentNode'; - if (nodeType === 'script') flowNodeType = 'scriptNode'; - else if (nodeType === 'set') flowNodeType = 'setNode'; - else if (nodeType === 'human_gate' || nodeType === 'questions') flowNodeType = 'gateNode'; - else if (nodeType === 'workflow') flowNodeType = 'workflowNode'; - else if (nodeType === 'wait') flowNodeType = 'waitNode'; - else if (nodeType === 'terminate') flowNodeType = 'terminateNode'; + const flowNodeType = flowNodeTypeFor(nodeType); if (nodeType === 'workflow') { // Sequential subworkflow: slotKey === agent name. Locate its child diff --git a/src/conductor/web/frontend/src/lib/constants.ts b/src/conductor/web/frontend/src/lib/constants.ts index a46e8d5a..37e0a6d5 100644 --- a/src/conductor/web/frontend/src/lib/constants.ts +++ b/src/conductor/web/frontend/src/lib/constants.ts @@ -1,5 +1,5 @@ export type NodeStatus = 'pending' | 'running' | 'completed' | 'failed' | 'paused' | 'idle' | 'waiting'; -export type NodeType = 'agent' | 'script' | 'set' | 'human_gate' | 'questions' | 'parallel_group' | 'for_each_group' | 'workflow' | 'wait' | 'terminate' | 'start' | 'end' | 'ingress' | 'egress'; +export type NodeType = 'agent' | 'script' | 'set' | 'mcp' | 'human_gate' | 'questions' | 'parallel_group' | 'for_each_group' | 'workflow' | 'wait' | 'terminate' | 'start' | 'end' | 'ingress' | 'egress'; export const NODE_STATUS_HEX: Record = { pending: '#6b7280', diff --git a/src/conductor/web/frontend/src/stores/workflow-store.test.ts b/src/conductor/web/frontend/src/stores/workflow-store.test.ts index bdcb230b..176dac1e 100644 --- a/src/conductor/web/frontend/src/stores/workflow-store.test.ts +++ b/src/conductor/web/frontend/src/stores/workflow-store.test.ts @@ -735,6 +735,106 @@ describe('workflow-store — eager static sub-workflow preview (dashboard expand expect(child.children[0]!.slotKey).toBe('b'); expect(child.children[0]!.workflowName).toBe('grandchild-workflow'); }); + + it('types parallel-group members by their declared type in static previews', () => { + const { processEvent } = useWorkflowStore.getState(); + + processEvent(event('workflow_started', { + name: 'root', + agents: [ + { + name: 'sub_wf', + type: 'workflow', + subworkflow: { + name: 'child-workflow', + entry_point: 'pg', + agents: [ + { name: 'mcp_member', type: 'mcp' }, + { name: 'plain_member' }, + ], + routes: [], + parallel_groups: [{ name: 'pg', agents: ['mcp_member', 'plain_member'] }], + for_each_groups: [], + }, + }, + ], + routes: [], + parallel_groups: [], + for_each_groups: [], + entry_point: 'sub_wf', + })); + + // Requirement: static child contexts preserve declared member types — + // a parallel member declared `type: mcp` must not be seeded as the + // generic 'agent', or DetailPanel routes it to AgentDetail instead of + // McpDetail. + const child = useWorkflowStore.getState().subworkflowContexts[0]!; + expect(child.nodes.mcp_member?.type).toBe('mcp'); + expect(child.nodes.plain_member?.type).toBe('agent'); + }); + + it('re-syncs node types from the runtime topology when the child workflow_started reuses a placeholder', () => { + const { processEvent } = useWorkflowStore.getState(); + + processEvent(event('workflow_started', { + name: 'root', + agents: [ + { + name: 'sub_wf', + type: 'workflow', + subworkflow: { + name: 'child-workflow', + entry_point: 'pg', + agents: [ + { name: 'mcp_member', type: 'mcp' }, + { name: 'plain_member' }, + ], + routes: [], + parallel_groups: [{ name: 'pg', agents: ['mcp_member', 'plain_member'] }], + for_each_groups: [], + }, + }, + ], + routes: [], + parallel_groups: [], + for_each_groups: [], + entry_point: 'sub_wf', + })); + + // Simulate a placeholder seeded before declared types were honoured: + // the member node carries the generic type. + const staleChild = useWorkflowStore.getState().subworkflowContexts[0]!; + useWorkflowStore.setState({ + subworkflowContexts: [{ + ...staleChild, + nodes: { + ...staleChild.nodes, + mcp_member: { ...staleChild.nodes.mcp_member!, type: 'agent' }, + }, + }], + }); + + processEvent(event('subworkflow_started', { agent_name: 'sub_wf', workflow: 'child.yaml', iteration: 1, parent_path: [] })); + processEvent(event('workflow_started', { + name: 'child-workflow', + agents: [ + { name: 'mcp_member', type: 'mcp' }, + { name: 'plain_member' }, + ], + routes: [], + parallel_groups: [{ name: 'pg', agents: ['mcp_member', 'plain_member'] }], + for_each_groups: [], + entry_point: 'pg', + })); + + // Requirement: the runtime topology is authoritative over a reused + // placeholder — ensureNode never updates an existing node's type, so + // the child's workflow_started must re-sync declared types onto the + // placeholder nodes (group nodes stay untouched). + const child = useWorkflowStore.getState().subworkflowContexts[0]!; + expect(child.nodes.mcp_member?.type).toBe('mcp'); + expect(child.nodes.pg?.type).toBe('parallel_group'); + }); }); describe('workflow-store — navigating to a specific historical subworkflow iteration (#365)', () => { @@ -1372,3 +1472,183 @@ describe('workflow-store processEvent — agent_prompt_rendered continuation', ( expect(prompt).toBe('first prompt\n\n## Validation feedback\n- fix'); }); }); + +describe('workflow-store — mcp item-scoped branching', () => { + // Requirement: Normal MCP steps without a group_name/item_key update their own top-level node. + it('updates normal mcp nodes correctly', () => { + const { processEvent } = useWorkflowStore.getState(); + processEvent(event('workflow_started', { + name: 'root', + agents: [{ name: 'my_mcp', type: 'mcp' }], + routes: [], + parallel_groups: [], + for_each_groups: [], + entry_point: 'my_mcp', + })); + + processEvent(event('mcp_started', { + agent_name: 'my_mcp', + server: 'git', + tool: 'status', + argument_keys: [], + })); + + const stateRunning = useWorkflowStore.getState(); + expect(stateRunning.nodes.my_mcp?.status).toBe('running'); + + processEvent(event('mcp_completed', { + agent_name: 'my_mcp', + elapsed: 1.5, + server: 'git', + tool: 'status', + is_error: false, + result_bytes: 123, + truncated: false, + })); + + const stateCompleted = useWorkflowStore.getState(); + expect(stateCompleted.nodes.my_mcp?.status).toBe('completed'); + expect(stateCompleted.nodes.my_mcp?.mcp_server).toBe('git'); + expect(stateCompleted.nodes.my_mcp?.mcp_tool).toBe('status'); + expect(stateCompleted.nodes.my_mcp?.mcp_result_bytes).toBe(123); + }); + + // Requirement: A parallel group MCP member must not increment agentsCompleted itself (Finding A). + it('does not double-count completion for parallel MCP members', () => { + useWorkflowStore.setState({ wfDepth: 0, agentsTotal: 0, agentsCompleted: 0 }); // reset + const { processEvent } = useWorkflowStore.getState(); + processEvent(event('workflow_started', { + name: 'root', + agents: [{ name: 'member1', type: 'mcp' }], + routes: [], + parallel_groups: [{ name: 'pg1', agents: ['member1'] }], + for_each_groups: [], + entry_point: 'pg1', + })); + + processEvent(event('mcp_completed', { + agent_name: 'member1', + group_name: 'pg1', + elapsed: 1, + server: 'git', + tool: 'status', + is_error: false, + })); + + const state = useWorkflowStore.getState(); + expect(state.agentsCompleted).toBe(0); + expect(state.nodes.member1?.status).toBe('completed'); + }); + + // Requirement: Parallel group members must inherit their declared step type, not just 'agent' (Finding B). + it('assigns the declared node type to parallel group members in workflow_started', () => { + const { processEvent } = useWorkflowStore.getState(); + processEvent(event('workflow_started', { + name: 'root', + agents: [ + { name: 'mcp_member', type: 'mcp' }, + { name: 'script_member', type: 'script' } + ], + routes: [], + parallel_groups: [{ name: 'pg1', agents: ['mcp_member', 'script_member'] }], + for_each_groups: [], + entry_point: 'pg1', + })); + + const state = useWorkflowStore.getState(); + expect(state.nodes.mcp_member?.type).toBe('mcp'); + expect(state.nodes.script_member?.type).toBe('script'); + }); + + // Requirement: Two concurrently active item_keys with interleaved completions must not cross-contaminate. + it('updates for_each_items independently without touching the group node or each other (interleaved)', () => { + const { processEvent } = useWorkflowStore.getState(); + processEvent(event('workflow_started', { + name: 'root', + agents: [], + routes: [], + parallel_groups: [], + for_each_groups: [{ name: 'mcp_group' }], + entry_point: 'mcp_group', + })); + + processEvent(event('for_each_started', { group_name: 'mcp_group', item_count: 2 })); + + // Items started + processEvent(event('for_each_item_started', { group_name: 'mcp_group', item_key: 'item1', index: 0 })); + processEvent(event('for_each_item_started', { group_name: 'mcp_group', item_key: 'item2', index: 1 })); + + // Interleaved MCP starts + processEvent(event('mcp_started', { + agent_name: 'mcp_inline', + group_name: 'mcp_group', + item_key: 'item1', + server: 's1', + tool: 't1', + argument_keys: [], + })); + + processEvent(event('mcp_started', { + agent_name: 'mcp_inline', + group_name: 'mcp_group', + item_key: 'item2', + server: 's2', + tool: 't2', + argument_keys: [], + })); + + // Verify they are both running + const stateRunning = useWorkflowStore.getState(); + const groupRunning = stateRunning.nodes.mcp_group; + expect(groupRunning?.for_each_items).toHaveLength(2); + expect(groupRunning?.for_each_items?.[0]?.status).toBe('running'); + expect(groupRunning?.for_each_items?.[1]?.status).toBe('running'); + + // Interleaved MCP completions + processEvent(event('mcp_completed', { + agent_name: 'mcp_inline', + group_name: 'mcp_group', + item_key: 'item2', + elapsed: 2.0, + server: 's2', + tool: 't2', + is_error: false, + result_bytes: 42, + truncated: false, + })); + + processEvent(event('mcp_failed', { + agent_name: 'mcp_inline', + group_name: 'mcp_group', + item_key: 'item1', + elapsed: 1.0, + server: 's1', + tool: 't1', + error_type: 'TimeoutError', + message: 'timeout', + })); + + const stateFinal = useWorkflowStore.getState(); + const groupFinal = stateFinal.nodes.mcp_group; + expect(groupFinal?.for_each_items).toHaveLength(2); + + const item1 = groupFinal?.for_each_items?.find(i => i.key === 'item1'); + const item2 = groupFinal?.for_each_items?.find(i => i.key === 'item2'); + + expect(item1?.status).toBe('failed'); + expect(item1?.mcp_server).toBe('s1'); + expect(item1?.mcp_tool).toBe('t1'); + expect(item1?.error_type).toBe('TimeoutError'); + + expect(item2?.status).toBe('completed'); + expect(item2?.mcp_server).toBe('s2'); + expect(item2?.mcp_tool).toBe('t2'); + expect(item2?.mcp_result_bytes).toBe(42); + + // Group node status itself is not mutated by item events + expect(groupFinal?.status).toBe('running'); // since for_each_completed hasn't fired + + // The shared inline agent should not be created as a top-level node + expect(stateFinal.nodes.mcp_inline).toBeUndefined(); + }); +}); diff --git a/src/conductor/web/frontend/src/stores/workflow-store.ts b/src/conductor/web/frontend/src/stores/workflow-store.ts index 1011cc0f..52d886bf 100644 --- a/src/conductor/web/frontend/src/stores/workflow-store.ts +++ b/src/conductor/web/frontend/src/stores/workflow-store.ts @@ -21,6 +21,9 @@ import type { WaitFailedData, SetCompletedData, SetFailedData, + McpStartedData, + McpCompletedData, + McpFailedData, GatePresentedData, GateResolvedData, GateOptionDetail, @@ -95,6 +98,12 @@ export interface ForEachItemData { prompt?: string; output?: unknown; activity: ActivityEntry[]; + mcp_server?: string; + mcp_tool?: string; + mcp_is_error?: boolean; + mcp_result_bytes?: number; + mcp_truncated?: boolean; + mcp_spill_path?: string; } export interface NodeData { @@ -120,6 +129,15 @@ export interface NodeData { iteration?: number; error_type?: string; error_message?: string; + + // MCP-specific + mcp_server?: string; + mcp_tool?: string; + mcp_is_error?: boolean; + mcp_result_bytes?: number; + mcp_truncated?: boolean; + mcp_spill_path?: string; + // Script-specific stdout?: string; stderr?: string; @@ -605,12 +623,13 @@ function buildStaticChildContext( const groupAgents = new Set(); const agentNames = new Set(); + const agentTypes = new Map(ctx.agents.map((a) => [a.name, (a.type || 'agent') as NodeType])); for (const pg of ctx.parallelGroups) { for (const a of pg.agents) groupAgents.add(a); agentNames.add(pg.name); ensureNode(ctx.nodes, pg.name, 'parallel_group'); ctx.groupProgress[pg.name] = { total: pg.agents.length, completed: 0, failed: 0 }; - for (const agentName of pg.agents) ensureNode(ctx.nodes, agentName, 'agent'); + for (const agentName of pg.agents) ensureNode(ctx.nodes, agentName, agentTypes.get(agentName) || 'agent'); } for (const fg of ctx.forEachGroups) { agentNames.add(fg.name); @@ -1465,13 +1484,14 @@ const eventHandlers: Record(); const agentNames = new Set(); + const agentTypes = new Map(state.agents.map((a) => [a.name, (a.type || 'agent') as NodeType])); for (const pg of state.parallelGroups) { for (const a of pg.agents) groupAgents.add(a); agentNames.add(pg.name); ensureNode(state.nodes, pg.name, 'parallel_group'); state.groupProgress[pg.name] = { total: pg.agents.length, completed: 0, failed: 0 }; - for (const agentName of pg.agents) ensureNode(state.nodes, agentName, 'agent'); + for (const agentName of pg.agents) ensureNode(state.nodes, agentName, agentTypes.get(agentName) || 'agent'); } for (const fg of state.forEachGroups) { agentNames.add(fg.name); @@ -1528,13 +1548,14 @@ const eventHandlers: Record(); const agentNames = new Set(); + const agentTypes = new Map(ctx.agents.map((a) => [a.name, (a.type || 'agent') as NodeType])); for (const pg of ctx.parallelGroups) { for (const a of pg.agents) groupAgents.add(a); agentNames.add(pg.name); ensureNode(ctx.nodes, pg.name, 'parallel_group'); ctx.groupProgress[pg.name] = { total: pg.agents.length, completed: 0, failed: 0 }; - for (const agentName of pg.agents) ensureNode(ctx.nodes, agentName, 'agent'); + for (const agentName of pg.agents) ensureNode(ctx.nodes, agentName, agentTypes.get(agentName) || 'agent'); } for (const fg of ctx.forEachGroups) { agentNames.add(fg.name); @@ -1559,6 +1580,18 @@ const eventHandlers: Record { + const data = _data as unknown as McpStartedData; + const t = activeTarget(state, _data); + + if (data.group_name != null && data.item_key != null) { + const nd = ensureNode(t.nodes, data.group_name, 'for_each_group'); + if (nd.for_each_items) { + nd.for_each_items = nd.for_each_items.map((i) => + i.key === data.item_key ? { ...i, status: 'running' } : i + ); + } + replaceNode(t.nodes, data.group_name); + } else { + const nd = ensureNode(t.nodes, data.agent_name, 'mcp'); + nd.status = 'running'; + nd.startedAt = timestamp ?? Date.now() / 1000; + replaceNode(t.nodes, data.agent_name); + } + }, + + mcp_completed: (state, _data) => { + const data = _data as unknown as McpCompletedData; + const t = activeTarget(state, _data); + + if (data.group_name != null && data.item_key != null) { + const nd = ensureNode(t.nodes, data.group_name, 'for_each_group'); + if (nd.for_each_items) { + nd.for_each_items = nd.for_each_items.map((i) => + i.key === data.item_key + ? { + ...i, + status: 'completed', + elapsed: data.elapsed, + mcp_server: data.server, + mcp_tool: data.tool, + mcp_is_error: data.is_error, + mcp_result_bytes: data.result_bytes, + mcp_truncated: data.truncated, + mcp_spill_path: data.spill_path, + } + : i + ); + } + replaceNode(t.nodes, data.group_name); + } else { + const nd = ensureNode(t.nodes, data.agent_name, 'mcp'); + nd.status = 'completed'; + if (data.group_name == null) { + t.incrCompleted(); + } + nd.elapsed = data.elapsed; + nd.mcp_server = data.server; + nd.mcp_tool = data.tool; + nd.mcp_is_error = data.is_error; + nd.mcp_result_bytes = data.result_bytes; + nd.mcp_truncated = data.truncated; + nd.mcp_spill_path = data.spill_path; + replaceNode(t.nodes, data.agent_name); + } + }, + + mcp_failed: (state, _data) => { + const data = _data as unknown as McpFailedData; + const t = activeTarget(state, _data); + + if (data.group_name != null && data.item_key != null) { + const nd = ensureNode(t.nodes, data.group_name, 'for_each_group'); + if (nd.for_each_items) { + nd.for_each_items = nd.for_each_items.map((i) => + i.key === data.item_key + ? { + ...i, + status: 'failed', + elapsed: data.elapsed, + mcp_server: data.server, + mcp_tool: data.tool, + error_type: data.error_type, + error_message: data.message, + } + : i + ); + } + replaceNode(t.nodes, data.group_name); + } else { + const nd = ensureNode(t.nodes, data.agent_name, 'mcp'); + nd.status = 'failed'; + nd.elapsed = data.elapsed; + nd.mcp_server = data.server; + nd.mcp_tool = data.tool; + nd.error_type = data.error_type; + nd.error_message = data.message; + replaceNode(t.nodes, data.agent_name); + } + }, + gate_presented: (state, _data) => { const data = _data as unknown as GatePresentedData; const t = activeTarget(state, _data); @@ -2698,6 +2826,15 @@ function buildLogEntry(event: WorkflowEvent): LogEntry | null { case 'script_failed': return { timestamp: ts, level: 'error', source: String(d.agent_name), message: `Script failed: ${d.message || d.error_type || 'unknown error'}` }; + case 'mcp_started': + return { timestamp: ts, level: 'info', source: String(d.agent_name), message: `MCP tool started: ${(d.server as string)}/${(d.tool as string)}` }; + + case 'mcp_completed': + return { timestamp: ts, level: d.is_error ? 'warning' : 'success', source: String(d.agent_name), message: `MCP tool completed: ${(d.server as string)}/${(d.tool as string)}${d.elapsed != null ? ` in ${formatSec(d.elapsed as number)}` : ''}` }; + + case 'mcp_failed': + return { timestamp: ts, level: 'error', source: String(d.agent_name), message: `MCP tool failed: ${(d.server as string)}/${(d.tool as string)} — ${d.message || d.error_type || 'unknown error'}` }; + case 'wait_started': { const dur = d.duration_seconds as number | null | undefined; const reason = d.reason as string | null | undefined; @@ -3010,6 +3147,19 @@ function buildActivityLogEntry(event: WorkflowEvent): ActivityLogEntry | null { case 'script_failed': return { timestamp: ts, source: String(d.agent_name), type: 'turn', message: `Script failed: ${d.message || d.error_type || 'unknown'}` }; + case 'mcp_started': + return { timestamp: ts, source: String(d.agent_name), type: 'turn', message: `MCP tool started: ${(d.server as string)}/${(d.tool as string)}` }; + + case 'mcp_completed': + return { + timestamp: ts, source: String(d.agent_name), type: 'tool-complete', + message: `MCP tool completed: ${(d.server as string)}/${(d.tool as string)}${d.is_error ? ' (error)' : ''}`, + detail: d.result_bytes ? `${d.result_bytes} bytes${d.truncated ? ' (truncated)' : ''}` : null, + }; + + case 'mcp_failed': + return { timestamp: ts, source: String(d.agent_name), type: 'turn', message: `MCP tool failed: ${(d.server as string)}/${(d.tool as string)} — ${d.message || d.error_type || 'unknown'}` }; + case 'wait_started': { const dur = d.duration_seconds as number | null | undefined; const reason = d.reason as string | null | undefined; diff --git a/src/conductor/web/frontend/src/types/events.ts b/src/conductor/web/frontend/src/types/events.ts index 845cd42b..9f87865f 100644 --- a/src/conductor/web/frontend/src/types/events.ts +++ b/src/conductor/web/frontend/src/types/events.ts @@ -28,6 +28,9 @@ export type EventType = | 'set_started' | 'set_completed' | 'set_failed' + | 'mcp_started' + | 'mcp_completed' + | 'mcp_failed' | 'gate_presented' | 'gate_resolved' | 'questions_presented' @@ -337,6 +340,42 @@ export interface SetFailedData { message?: string; } +// --- MCP lifecycle --- + +export interface McpStartedData { + agent_name: string; + iteration?: number; + server: string; + tool: string; + argument_keys: string[]; + group_name?: string; + item_key?: string; +} + +export interface McpCompletedData { + agent_name: string; + elapsed?: number; + server: string; + tool: string; + is_error: boolean; + result_bytes: number; + truncated: boolean; + spill_path?: string; + group_name?: string; + item_key?: string; +} + +export interface McpFailedData { + agent_name: string; + elapsed?: number; + server: string; + tool: string; + error_type?: string; + message?: string; + group_name?: string; + item_key?: string; +} + // --- Gate events --- export interface GateOptionDetail { diff --git a/src/conductor/web/frontend/tsconfig.tsbuildinfo b/src/conductor/web/frontend/tsconfig.tsbuildinfo index 56bf6fde..5d452ec8 100644 --- a/src/conductor/web/frontend/tsconfig.tsbuildinfo +++ b/src/conductor/web/frontend/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/App.tsx","./src/main.tsx","./src/components/detail/ActivityStream.tsx","./src/components/detail/AgentDetail.tsx","./src/components/detail/DetailPanel.tsx","./src/components/detail/DialogDetail.tsx","./src/components/detail/DialogEngagementPrompt.tsx","./src/components/detail/DialogOverlay.tsx","./src/components/detail/FileViewer.tsx","./src/components/detail/GateDetail.tsx","./src/components/detail/GroupDetail.tsx","./src/components/detail/MetadataGrid.tsx","./src/components/detail/OutputViewer.tsx","./src/components/detail/QuestionsDetail.tsx","./src/components/detail/ScriptDetail.tsx","./src/components/detail/SetDetail.tsx","./src/components/detail/SubworkflowDetail.tsx","./src/components/detail/ValidatorDetail.tsx","./src/components/detail/WaitDetail.tsx","./src/components/dialogs/GuidanceModal.tsx","./src/components/dialogs/IterationLimitModal.tsx","./src/components/graph/AgentNode.tsx","./src/components/graph/AnimatedEdge.tsx","./src/components/graph/EgressNode.tsx","./src/components/graph/EndNode.tsx","./src/components/graph/GateNode.tsx","./src/components/graph/GroupNode.tsx","./src/components/graph/IngressNode.tsx","./src/components/graph/NodeTooltip.tsx","./src/components/graph/ScriptNode.tsx","./src/components/graph/SetNode.tsx","./src/components/graph/StartNode.tsx","./src/components/graph/TerminateNode.tsx","./src/components/graph/WaitNode.tsx","./src/components/graph/WorkflowGraph.tsx","./src/components/graph/WorkflowNode.tsx","./src/components/graph/graph-layout.test.ts","./src/components/graph/graph-layout.ts","./src/components/layout/BreadcrumbBar.tsx","./src/components/layout/ErrorBanner.tsx","./src/components/layout/Header.tsx","./src/components/layout/OutputPane.tsx","./src/components/layout/ReconnectWarningBanner.tsx","./src/components/layout/ReplayBar.tsx","./src/components/layout/ResizableLayout.tsx","./src/components/layout/SendFailedBanner.tsx","./src/components/layout/StatusBar.tsx","./src/components/layout/YamlViewer.tsx","./src/hooks/use-deep-link.ts","./src/hooks/use-elapsed-timer.ts","./src/hooks/use-reconnect-warning.ts","./src/hooks/use-replay.ts","./src/hooks/use-viewed-context.ts","./src/hooks/use-websocket.ts","./src/lib/auth.test.ts","./src/lib/auth.ts","./src/lib/camera-authority.test.ts","./src/lib/camera-authority.ts","./src/lib/constants.ts","./src/lib/graph-anchor.test.ts","./src/lib/graph-anchor.ts","./src/lib/guidance.test.ts","./src/lib/guidance.ts","./src/lib/node-id.ts","./src/lib/reconnect.test.ts","./src/lib/reconnect.ts","./src/lib/utils.ts","./src/stores/questions-store.test.ts","./src/stores/workflow-store.test.ts","./src/stores/workflow-store.ts","./src/types/events.ts"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/App.tsx","./src/main.tsx","./src/components/detail/ActivityStream.tsx","./src/components/detail/AgentDetail.tsx","./src/components/detail/DetailPanel.tsx","./src/components/detail/DialogDetail.tsx","./src/components/detail/DialogEngagementPrompt.tsx","./src/components/detail/DialogOverlay.tsx","./src/components/detail/FileViewer.tsx","./src/components/detail/GateDetail.tsx","./src/components/detail/GroupDetail.tsx","./src/components/detail/McpDetail.tsx","./src/components/detail/MetadataGrid.tsx","./src/components/detail/OutputViewer.tsx","./src/components/detail/QuestionsDetail.tsx","./src/components/detail/ScriptDetail.tsx","./src/components/detail/SetDetail.tsx","./src/components/detail/SubworkflowDetail.tsx","./src/components/detail/ValidatorDetail.tsx","./src/components/detail/WaitDetail.tsx","./src/components/dialogs/GuidanceModal.tsx","./src/components/dialogs/IterationLimitModal.tsx","./src/components/graph/AgentNode.tsx","./src/components/graph/AnimatedEdge.tsx","./src/components/graph/EgressNode.tsx","./src/components/graph/EndNode.tsx","./src/components/graph/GateNode.tsx","./src/components/graph/GroupNode.tsx","./src/components/graph/IngressNode.tsx","./src/components/graph/McpNode.tsx","./src/components/graph/NodeTooltip.tsx","./src/components/graph/ScriptNode.tsx","./src/components/graph/SetNode.tsx","./src/components/graph/StartNode.tsx","./src/components/graph/TerminateNode.tsx","./src/components/graph/WaitNode.tsx","./src/components/graph/WorkflowGraph.tsx","./src/components/graph/WorkflowNode.tsx","./src/components/graph/graph-layout.test.ts","./src/components/graph/graph-layout.ts","./src/components/layout/BreadcrumbBar.tsx","./src/components/layout/ErrorBanner.tsx","./src/components/layout/Header.tsx","./src/components/layout/OutputPane.tsx","./src/components/layout/ReconnectWarningBanner.tsx","./src/components/layout/ReplayBar.tsx","./src/components/layout/ResizableLayout.tsx","./src/components/layout/SendFailedBanner.tsx","./src/components/layout/StatusBar.tsx","./src/components/layout/YamlViewer.tsx","./src/hooks/use-deep-link.ts","./src/hooks/use-elapsed-timer.ts","./src/hooks/use-reconnect-warning.ts","./src/hooks/use-replay.ts","./src/hooks/use-viewed-context.ts","./src/hooks/use-websocket.ts","./src/lib/auth.test.ts","./src/lib/auth.ts","./src/lib/camera-authority.test.ts","./src/lib/camera-authority.ts","./src/lib/constants.ts","./src/lib/graph-anchor.test.ts","./src/lib/graph-anchor.ts","./src/lib/guidance.test.ts","./src/lib/guidance.ts","./src/lib/node-id.ts","./src/lib/reconnect.test.ts","./src/lib/reconnect.ts","./src/lib/utils.ts","./src/stores/questions-store.test.ts","./src/stores/workflow-store.test.ts","./src/stores/workflow-store.ts","./src/types/events.ts"],"version":"5.9.3"} \ No newline at end of file diff --git a/src/conductor/web/server.py b/src/conductor/web/server.py index 8f93f520..7064c377 100644 --- a/src/conductor/web/server.py +++ b/src/conductor/web/server.py @@ -854,25 +854,20 @@ def replay_synthetic_from_context( for name in execution_history: output = agent_outputs.get(name, {}) if name in parallel_groups: - started_type, started_data, completed_type, completed_data = self._synth_parallel( - name, parallel_groups[name], output - ) + events = self._synth_parallel(name, parallel_groups[name], output, agent_defs) elif name in for_each_groups: - started_type, started_data, completed_type, completed_data = self._synth_for_each( - name, output - ) + events = self._synth_for_each(name, for_each_groups[name], output) else: started_type, started_data, completed_type, completed_data = ( self._synth_agent_or_script(name, agent_defs.get(name), output) ) + events = [(started_type, started_data), (completed_type, completed_data)] - self._event_history.append( - {"type": started_type, "timestamp": ts, "data": started_data} - ) - self._event_history.append( - {"type": completed_type, "timestamp": ts, "data": completed_data} - ) - count += 2 + for event_type, event_data in events: + self._event_history.append( + {"type": event_type, "timestamp": ts, "data": event_data} + ) + count += len(events) logger.info( "Synthesized %d replay events from %d history entries", @@ -883,36 +878,93 @@ def replay_synthetic_from_context( @staticmethod def _synth_parallel( - name: str, pg: Any, output: Any - ) -> tuple[str, dict[str, Any], str, dict[str, Any]]: - """Build synthetic (started, completed) event payloads for a parallel group. + name: str, pg: Any, output: Any, agent_defs: dict[str, Any] + ) -> list[tuple[str, dict[str, Any]]]: + """Build synthetic replay events for a parallel group. The frontend renders ``parallel_completed`` as failed unless - ``failure_count === 0`` (workflow-store.ts:1266), so always emit + ``failure_count === 0`` (workflow-store.ts), so always emit zeros — we can't know the original counts from the restored context, but assuming success is the closest match to "the engine kept going past this group". + + ``type: mcp`` members need the member step types (``agent_defs``): + their saved outputs are full result envelopes, and live execution + deliberately never publishes argument/result values — so a replay + that dropped them into the aggregate ``parallel_completed.outputs`` + would expose exactly what the live path excludes. MCP members are + instead stripped from the aggregate and replayed as metadata-only + ``mcp_started``/``mcp_completed`` pairs (via the shared + :meth:`_synth_agent_or_script` shape, tagged with ``group_name``) + plus the LLM-less ``parallel_agent_completed`` the live engine + emits for them. """ agents = list(getattr(pg, "agents", []) or []) output_dict = output if isinstance(output, dict) else {} - started_data: dict[str, Any] = { - "group_name": name, - "agents": agents, - "synthetic": True, - } - completed_data: dict[str, Any] = { - "group_name": name, - "outputs": output_dict, - "success_count": len(agents), - "failure_count": 0, - "elapsed": 0.0, - "synthetic": True, - } - return "parallel_started", started_data, "parallel_completed", completed_data + member_outputs = output_dict.get("outputs") + if not isinstance(member_outputs, dict): + member_outputs = {} + events: list[tuple[str, dict[str, Any]]] = [ + ( + "parallel_started", + { + "group_name": name, + "agents": agents, + "synthetic": True, + }, + ), + ] + stripped_outputs: dict[str, Any] = {} + for member_name, member_output in member_outputs.items(): + member_def = agent_defs.get(member_name) + if getattr(member_def, "type", None) == "mcp": + started_data, completed_data = WebDashboard._synth_mcp_pair( + member_name, member_def, member_output + ) + started_data["group_name"] = name + completed_data["group_name"] = name + events.append(("mcp_started", started_data)) + events.append(("mcp_completed", completed_data)) + # Mirror the live engine's LLM-less member completion (no + # `output` field — the no-values policy for step events). + events.append( + ( + "parallel_agent_completed", + { + "group_name": name, + "agent_name": member_name, + "elapsed": 0.0, + "model": "", + "tokens": 0, + "cost_usd": 0.0, + "context_window_used": 0, + "context_window_max": None, + "agent_type": "mcp", + "synthetic": True, + }, + ) + ) + else: + stripped_outputs[member_name] = member_output + aggregate = {**output_dict, "outputs": stripped_outputs} + events.append( + ( + "parallel_completed", + { + "group_name": name, + "outputs": aggregate, + "success_count": len(agents), + "failure_count": 0, + "elapsed": 0.0, + "synthetic": True, + }, + ) + ) + return events @staticmethod - def _synth_for_each(name: str, output: Any) -> tuple[str, dict[str, Any], str, dict[str, Any]]: - """Build synthetic (started, completed) event payloads for a for-each group. + def _synth_for_each(name: str, fg: Any, output: Any) -> list[tuple[str, dict[str, Any]]]: + """Build synthetic replay events for a for-each group. The engine stores for-each output as ``{"outputs": , "errors": {...}, "count": N}`` (see @@ -921,6 +973,14 @@ def _synth_for_each(name: str, output: Any) -> tuple[str, dict[str, Any], str, d when that field is missing. Naïve ``output.get("outputs") or ...`` would treat an empty list as missing and use the wrapper dict's key count (3) as the item count. + + A group whose inline agent is a ``type: mcp`` step stores one full + result envelope per item; live execution never publishes those + values, so the envelopes are stripped from the aggregate and each + item is replayed as the metadata-only event sequence the live + engine emits (``for_each_item_started`` -> ``mcp_started`` -> + ``mcp_completed`` -> ``for_each_item_completed`` without + ``output``). """ output_dict = output if isinstance(output, dict) else {} item_count = 0 @@ -928,17 +988,131 @@ def _synth_for_each(name: str, output: Any) -> tuple[str, dict[str, Any], str, d item_count = output_dict["count"] elif isinstance(output_dict.get("outputs"), (list, dict)): item_count = len(output_dict["outputs"]) - started_data: dict[str, Any] = {"group_name": name, "synthetic": True} + events: list[tuple[str, dict[str, Any]]] = [ + ("for_each_started", {"group_name": name, "synthetic": True}), + ] + + aggregate = output_dict + agent_def = getattr(fg, "agent", None) + if getattr(agent_def, "type", None) == "mcp": + raw_outputs = output_dict.get("outputs") + items: list[tuple[str, int, Any]] = [] + if isinstance(raw_outputs, dict): + items = [ + (str(key), index, env) for index, (key, env) in enumerate(raw_outputs.items()) + ] + elif isinstance(raw_outputs, list): + items = [(str(index), index, env) for index, env in enumerate(raw_outputs)] + for item_key, index, envelope in items: + events.append( + ( + "for_each_item_started", + { + "group_name": name, + "item_key": item_key, + "index": index, + "synthetic": True, + }, + ) + ) + started_data, completed_data = WebDashboard._synth_mcp_pair( + getattr(agent_def, "name", name), agent_def, envelope + ) + started_data["group_name"] = name + started_data["item_key"] = item_key + completed_data["group_name"] = name + completed_data["item_key"] = item_key + events.append(("mcp_started", started_data)) + events.append(("mcp_completed", completed_data)) + # Deliberate divergence from the set-step branch, matching + # live: no `output` field on the item completion. + events.append( + ( + "for_each_item_completed", + { + "group_name": name, + "item_key": item_key, + "elapsed": 0.0, + "tokens": 0, + "cost_usd": 0.0, + "synthetic": True, + }, + ) + ) + # Strip the per-item envelopes from the aggregate: they are + # result values the live event stream deliberately excludes. + aggregate = { + **output_dict, + "outputs": {} if isinstance(raw_outputs, dict) else [], + } + + events.append( + ( + "for_each_completed", + { + "group_name": name, + "outputs": aggregate, + "item_count": item_count, + "success_count": item_count, + "failure_count": 0, + "elapsed": 0.0, + "synthetic": True, + }, + ) + ) + return events + + @staticmethod + def _synth_mcp_pair( + name: str, agent_def: Any, output: Any + ) -> tuple[dict[str, Any], dict[str, Any]]: + """Build the metadata-only (mcp_started, mcp_completed) data payloads. + + Shared by the standalone branch of :meth:`_synth_agent_or_script` + and the group syntheses (which add ``group_name`` / ``item_key`` + themselves). Mirrors the live runtime's mcp payload shape so + synthetic replays render identically to live runs. The result size + is measured by the same helper the engine emitter uses. + + Truncation markers are NEVER republished from a stored envelope. + ``truncated`` / ``spill_path`` on a content block are trustworthy + only on the live path, where + :meth:`conductor.mcp.manager.MCPManager.call_tool_structured` strips + server-supplied fields of those names at ingestion before its own + truncation pass sets them. A checkpoint may have been written before + that stripping existed, so a stored ``spill_path`` can be a + server-supplied string — republishing it would present + server-controlled data as Conductor-generated metadata. Synthetic + events therefore report no truncation; the stored envelope itself + stays intact in the workflow context for routing and templates. + """ + from conductor.executor.mcp_step import mcp_result_bytes + + server = getattr(agent_def, "server", None) + tool = getattr(agent_def, "tool", None) + arguments = getattr(agent_def, "arguments", None) + output_dict = output if isinstance(output, dict) else {} + content = output_dict.get("content") + started_data: dict[str, Any] = { + "agent_name": name, + "iteration": 1, + "server": server, + "tool": tool, + "argument_keys": sorted(arguments.keys()) if isinstance(arguments, dict) else [], + "synthetic": True, + } completed_data: dict[str, Any] = { - "group_name": name, - "outputs": output_dict, - "item_count": item_count, - "success_count": item_count, - "failure_count": 0, + "agent_name": name, "elapsed": 0.0, + "server": server, + "tool": tool, + "is_error": output_dict.get("is_error", False), + "result_bytes": mcp_result_bytes(content, output_dict.get("structured")), + "truncated": False, + "spill_path": None, "synthetic": True, } - return "for_each_started", started_data, "for_each_completed", completed_data + return started_data, completed_data @staticmethod def _synth_agent_or_script( @@ -1007,6 +1181,14 @@ def _synth_agent_or_script( } return "set_started", started_data, "set_completed", completed_data + if agent_type == "mcp": + # Shared metadata-only shape with the group syntheses — the + # result-size measurement and the trusted truncation markers + # must not drift between live, standalone replay, and group + # replay (see _synth_mcp_pair). + started_data, completed_data = WebDashboard._synth_mcp_pair(name, agent_def, output) + return "mcp_started", started_data, "mcp_completed", completed_data + started_data = { "agent_name": name, "iteration": 1, diff --git a/src/conductor/web/static/assets/index-Ca9QQYfJ.js b/src/conductor/web/static/assets/index-Ca9QQYfJ.js new file mode 100644 index 00000000..1f5c6bc8 --- /dev/null +++ b/src/conductor/web/static/assets/index-Ca9QQYfJ.js @@ -0,0 +1,91 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var u=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=u()})),f=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),p=o(((e,t)=>{t.exports=f()})),m=o((e=>{var t=d();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=m()})),g=o((e=>{var t=p(),n=d(),r=h();function i(e){var t=`https://react.dev/errors/`+e;if(1ie||(e.current=re[ie],re[ie]=null,ie--)}function L(e,t){ie++,re[ie]=e.current,e.current=t}var oe=ae(null),se=ae(null),ce=ae(null),le=ae(null);function ue(e,t){switch(L(ce,t),L(se,e),L(oe,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Gd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Gd(t),e=Kd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}I(oe),L(oe,e)}function de(){I(oe),I(se),I(ce)}function fe(e){e.memoizedState!==null&&L(le,e);var t=oe.current,n=Kd(t,e.type);t!==n&&(L(se,e),L(oe,n))}function pe(e){se.current===e&&(I(oe),I(se)),le.current===e&&(I(le),np._currentValue=ne)}var me,he;function ge(e){if(me===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);me=t&&t[1]||``,he=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{_e=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?ge(n):``}function ye(e,t){switch(e.tag){case 26:case 27:case 5:return ge(e.type);case 16:return ge(`Lazy`);case 13:return e.child!==t&&t!==null?ge(`Suspense Fallback`):ge(`Suspense`);case 19:return ge(`SuspenseList`);case 0:case 15:return ve(e.type,!1);case 11:return ve(e.type.render,!1);case 1:return ve(e.type,!0);case 31:return ge(`Activity`);default:return``}}function be(e){try{var t=``,n=null;do t+=ye(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var xe=Object.prototype.hasOwnProperty,Se=t.unstable_scheduleCallback,Ce=t.unstable_cancelCallback,we=t.unstable_shouldYield,Te=t.unstable_requestPaint,Ee=t.unstable_now,De=t.unstable_getCurrentPriorityLevel,Oe=t.unstable_ImmediatePriority,ke=t.unstable_UserBlockingPriority,Ae=t.unstable_NormalPriority,je=t.unstable_LowPriority,Me=t.unstable_IdlePriority,Ne=t.log,Pe=t.unstable_setDisableYieldValue,Fe=null,Ie=null;function Le(e){if(typeof Ne==`function`&&Pe(e),Ie&&typeof Ie.setStrictMode==`function`)try{Ie.setStrictMode(Fe,e)}catch{}}var Re=Math.clz32?Math.clz32:Ve,ze=Math.log,Be=Math.LN2;function Ve(e){return e>>>=0,e===0?32:31-(ze(e)/Be|0)|0}var He=256,Ue=262144,R=4194304;function We(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function z(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=We(n))):i=We(o):i=We(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=We(n))):i=We(o)):i=We(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Ge(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ke(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function qe(){var e=R;return R<<=1,!(R&62914560)&&(R=4194304),e}function Je(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ye(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Xe(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),rn=!1;if(nn)try{var an={};Object.defineProperty(an,"passive",{get:function(){rn=!0}}),window.addEventListener(`test`,an,an),window.removeEventListener(`test`,an,an)}catch{rn=!1}var on=null,sn=null,cn=null;function ln(){if(cn)return cn;var e,t=sn,n=t.length,r,i=`value`in on?on.value:on.textContent,a=i.length;for(e=0;e=Bn),Un=` `,Wn=!1;function Gn(e,t){switch(e){case`keyup`:return Rn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Kn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var qn=!1;function Jn(e,t){switch(e){case`compositionend`:return Kn(t);case`keypress`:return t.which===32?(Wn=!0,Un):null;case`textInput`:return e=t.data,e===Un&&Wn?null:e;default:return null}}function Yn(e,t){if(qn)return e===`compositionend`||!zn&&Gn(e,t)?(e=ln(),cn=sn=on=null,qn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=_r(n)}}function yr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?yr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function br(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=At(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=At(e.document)}return t}function xr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Sr=nn&&`documentMode`in document&&11>=document.documentMode,Cr=null,wr=null,Tr=null,Er=!1;function Dr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Er||Cr==null||Cr!==At(r)||(r=Cr,`selectionStart`in r&&xr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Tr&&gr(Tr,r)||(Tr=r,r=kd(wr,`onSelect`),0>=o,i-=o,yi=1<<32-Re(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Oi&&xi(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Oi&&xi(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Oi&&xi(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Oi&&xi(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&Sa(l)===r.type){n(e,r.sibling),c=a(r,o.props),ka(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===y?(c=oi(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=ai(o.type,o.key,o.props,null,e.mode,c),ka(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=li(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=Sa(o),b(e,r,o,c)}if(te(o))return h(e,r,o,c);if(M(o)){if(l=M(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Oa(o),c);if(o.$$typeof===C)return b(e,r,Xi(e,o),c);Aa(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=si(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Da=0;var i=b(e,t,n,r);return Ea=null,i}catch(t){if(t===ga||t===va)throw t;var a=ti(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ma=ja(!0),Na=ja(!1),Pa=!1;function Fa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ia(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function La(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ra(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ll&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Qr(e),Zr(e,null,n),t}return Jr(e,r,t,n),Qr(e)}function za(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}function Ba(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Va=!1;function Ha(){if(Va){var e=sa;if(e!==null)throw e}}function Ua(e,t,n,r){Va=!1;var i=e.updateQueue;Pa=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(zl&f)===f:(r&f)===f){f!==0&&f===oa&&(Va=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=m({},d,f);break a;case 2:Pa=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),ql|=o,e.lanes=o,e.memoizedState=d}}function Wa(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Ga(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=P.T,s={};P.T=s,js(e,!1,t,n);try{var c=i(),l=P.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?As(e,t,ua(c,r),hu(e)):As(e,t,r,hu(e))}catch(n){As(e,t,{then:function(){},status:`rejected`,reason:n},hu())}finally{F.p=a,o!==null&&s.types!==null&&(o.types=s.types),P.T=o}}function bs(){}function xs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ss(e).queue;ys(e,a,t,ne,n===null?bs:function(){return Cs(e),n(r)})}function Ss(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ne,baseState:ne,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mo,lastRenderedState:ne},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Cs(e){var t=Ss(e);t.next===null&&(t=e.alternate.memoizedState),As(e,t.next.queue,{},hu())}function ws(){return Yi(np)}function Ts(){return Do().memoizedState}function Es(){return Do().memoizedState}function Ds(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=hu();e=La(n);var r=Ra(t,e,n);r!==null&&(_u(r,t,n),za(r,t,n)),t={cache:na()},e.payload=t;return}t=t.return}}function Os(e,t,n){var r=hu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ms(e)?Ns(t,n):(n=Yr(e,t,n,r),n!==null&&(_u(n,e,r),Ps(n,t,r)))}function ks(e,t,n){As(e,t,n,hu())}function As(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ms(e))Ns(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,hr(s,o))return Jr(e,t,i,0),Rl===null&&qr(),!1}catch{}if(n=Yr(e,t,i,r),n!==null)return _u(n,e,r),Ps(n,t,r),!0}return!1}function js(e,t,n,r){if(r={lane:2,revertLane:md(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ms(e)){if(t)throw Error(i(479))}else t=Yr(e,n,r,2),t!==null&&_u(t,e,2)}function Ms(e){var t=e.alternate;return e===K||t!==null&&t===K}function Ns(e,t){uo=lo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ps(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}var Fs={readContext:Yi,use:Ao,useCallback:_o,useContext:_o,useEffect:_o,useImperativeHandle:_o,useLayoutEffect:_o,useInsertionEffect:_o,useMemo:_o,useReducer:_o,useRef:_o,useState:_o,useDebugValue:_o,useDeferredValue:_o,useTransition:_o,useSyncExternalStore:_o,useId:_o,useHostTransitionStatus:_o,useFormState:_o,useActionState:_o,useOptimistic:_o,useMemoCache:_o,useCacheRefresh:_o};Fs.useEffectEvent=_o;var Is={readContext:Yi,use:Ao,useCallback:function(e,t){return Eo().memoizedState=[e,t===void 0?null:t],e},useContext:Yi,useEffect:os,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),is(4194308,4,fs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return is(4194308,4,e,t)},useInsertionEffect:function(e,t){is(4,2,e,t)},useMemo:function(e,t){var n=Eo();t=t===void 0?null:t;var r=e();if(fo){Le(!0);try{e()}finally{Le(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Eo();if(n!==void 0){var i=n(t);if(fo){Le(!0);try{n(t)}finally{Le(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Os.bind(null,K,e),[r.memoizedState,e]},useRef:function(e){var t=Eo();return e={current:e},t.memoizedState=e},useState:function(e){e=Ho(e);var t=e.queue,n=ks.bind(null,K,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ms,useDeferredValue:function(e,t){return _s(Eo(),e,t)},useTransition:function(){var e=Ho(!1);return e=ys.bind(null,K,e.queue,!0,!1),Eo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=K,a=Eo();if(Oi){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Rl===null)throw Error(i(349));zl&127||Lo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,os(zo.bind(null,r,o,e),[e]),r.flags|=2048,ns(9,{destroy:void 0},Ro.bind(null,r,o,n,t),null),n},useId:function(){var e=Eo(),t=Rl.identifierPrefix;if(Oi){var n=bi,r=yi;n=(r&~(1<<32-Re(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=po++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[rt]=t,o[it]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Rd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Ac(t)}}return Fc(t),jc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Ac(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ce.current,Fi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Ei,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[rt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Fd(e.nodeValue,n)),e||Mi(t,!0)}else e=Wd(e).createTextNode(r),e[rt]=t,t.stateNode=e}return Fc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Fi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[rt]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),e=!1}else n=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ro(t),t):(ro(t),null);if(t.flags&128)throw Error(i(558))}return Fc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Fi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[rt]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),a=!1}else a=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(ro(t),t):(ro(t),null)}return ro(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Nc(t,t.updateQueue),Fc(t),null);case 4:return de(),e===null&&Td(t.stateNode.containerInfo),Fc(t),null;case 10:return Ui(t.type),Fc(t),null;case 19:if(I(io),r=t.memoizedState,r===null)return Fc(t),null;if(a=(t.flags&128)!=0,o=r.rendering,o===null)if(a)Pc(r,!1);else{if(Kl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=ao(e),o!==null){for(t.flags|=128,Pc(r,!1),e=o.updateQueue,t.updateQueue=e,Nc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)ii(n,e),n=n.sibling;return L(io,io.current&1|2),Oi&&xi(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ee()>ru&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304)}else{if(!a)if(e=ao(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Nc(t,e),Pc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Oi)return Fc(t),null}else 2*Ee()-r.renderingStartTime>ru&&n!==536870912&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Fc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ee(),e.sibling=null,n=io.current,L(io,a?n&1|2:n&1),Oi&&xi(t,r.treeForkCount),e);case 22:case 23:return ro(t),Xa(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Fc(t),t.subtreeFlags&6&&(t.flags|=8192)):Fc(t),n=t.updateQueue,n!==null&&Nc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&I(fa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ui(ta),Fc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Lc(e,t){switch(wi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ui(ta),de(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return pe(t),null;case 31:if(t.memoizedState!==null){if(ro(t),t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ro(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return I(io),null;case 4:return de(),null;case 10:return Ui(t.type),null;case 22:case 23:return ro(t),Xa(),e!==null&&I(fa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ui(ta),null;case 25:return null;default:return null}}function Rc(e,t){switch(wi(t),t.tag){case 3:Ui(ta),de();break;case 26:case 27:case 5:pe(t);break;case 4:de();break;case 31:t.memoizedState!==null&&ro(t);break;case 13:ro(t);break;case 19:I(io);break;case 10:Ui(t.type);break;case 22:case 23:ro(t),Xa(),e!==null&&I(fa);break;case 24:Ui(ta)}}function zc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){qu(t,t.return,e)}}function Bc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){qu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){qu(t,t.return,e)}}function Vc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ga(t,n)}catch(t){qu(e,e.return,t)}}}function Hc(e,t,n){n.props=Us(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){qu(e,t,n)}}function Uc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){qu(e,t,n)}}function Wc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){qu(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){qu(e,t,n)}else n.current=null}function Gc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){qu(e,e.return,t)}}function Kc(e,t,n){try{var r=e.stateNode;zd(r,e.type,n,t),r[it]=t}catch(t){qu(e,e.return,t)}}function qc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&tf(e.type)||e.tag===4}function Jc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||qc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&tf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Yc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=qt));else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Yc(e,t,n),e=e.sibling;e!==null;)Yc(e,t,n),e=e.sibling}function Xc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Xc(e,t,n),e=e.sibling;e!==null;)Xc(e,t,n),e=e.sibling}function Zc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Rd(t,r,n),t[rt]=e,t[it]=n}catch(t){qu(e,e.return,t)}}var Qc=!1,$c=!1,el=!1,tl=typeof WeakSet==`function`?WeakSet:Set,nl=null;function rl(e,t){if(e=e.containerInfo,Hd=dp,e=br(e),xr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Ud={focusedElem:e,selectionRange:n},dp=!1,nl=t;nl!==null;)if(t=nl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,nl=e;else for(;nl!==null;){switch(t=nl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Rd(o,r,n),o[rt]=e,ht(o),r=o;break a;case`link`:var s=Gf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=vr(s,h),v=vr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,P.T=null,n=du,du=null;var o=su,s=lu;if(ou=0,cu=su=null,lu=0,Ll&6)throw Error(i(331));var c=Ll;if(Ll|=4,Ml(o.current),wl(o,o.current,s,n),Ll=c,sd(0,!1),Ie&&typeof Ie.onPostCommitFiberRoot==`function`)try{Ie.onPostCommitFiberRoot(Fe,o)}catch{}return!0}finally{F.p=a,P.T=r,Uu(e,t)}}function Ku(e,t,n){t=di(n,t),t=Ys(e.stateNode,t,2),e=Ra(e,t,2),e!==null&&(Ye(e,2),od(e))}function qu(e,t,n){if(e.tag===3)Ku(e,e,n);else for(;t!==null;){if(t.tag===3){Ku(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(au===null||!au.has(r))){e=di(n,e),n=Xs(2),r=Ra(t,n,2),r!==null&&(Zs(n,r,t,e),Ye(r,2),od(r));break}}t=t.return}}function Ju(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Il;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Wl=!0,i.add(n),e=Yu.bind(null,e,t,n),t.then(e,e))}function Yu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Rl===e&&(zl&n)===n&&(Kl===4||Kl===3&&(zl&62914560)===zl&&300>Ee()-tu?!(Ll&2)&&wu(e,0):Yl|=n,Zl===zl&&(Zl=0)),od(e)}function Xu(e,t){t===0&&(t=qe()),e=Xr(e,t),e!==null&&(Ye(e,t),od(e))}function Zu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Xu(e,n)}function Qu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Xu(e,n)}function $u(e,t){return Se(e,t)}var ed=null,td=null,nd=!1,rd=!1,id=!1,ad=0;function od(e){e!==td&&e.next===null&&(td===null?ed=td=e:td=td.next=e),rd=!0,nd||(nd=!0,pd())}function sd(e,t){if(!id&&rd){id=!0;do for(var n=!1,r=ed;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Re(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,fd(r,a))}else a=zl,a=z(r,r===Rl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ge(r,a)||(n=!0,fd(r,a));r=r.next}while(n);id=!1}}function cd(){ld()}function ld(){rd=nd=!1;var e=0;ad!==0&&Yd()&&(e=ad);for(var t=Ee(),n=null,r=ed;r!==null;){var i=r.next,a=ud(r,t);a===0?(r.next=null,n===null?ed=i:n.next=i,i===null&&(td=n)):(n=r,(e!==0||a&3)&&(rd=!0)),r=i}ou!==0&&ou!==5||sd(e,!1),ad!==0&&(ad=0)}function ud(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Bd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Tf(e,t,n){var r=wf;if(r&&typeof t==`string`&&t){var i=Mt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),yf.has(i)||(yf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Rd(t,`link`,e),ht(t),r.head.appendChild(t)))}}function Ef(e){xf.D(e),Tf(`dns-prefetch`,e,null)}function Df(e,t){xf.C(e,t),Tf(`preconnect`,e,t)}function Of(e,t,n){xf.L(e,t,n);var r=wf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Mt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Mt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Mt(n.imageSizes)+`"]`)):i+=`[href="`+Mt(e)+`"]`;var a=i;switch(t){case`style`:a=Pf(e);break;case`script`:a=Rf(e)}vf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Ff(a))||t===`script`&&r.querySelector(zf(a))||(t=r.createElement(`link`),Rd(t,`link`,e),ht(t),r.head.appendChild(t)))}}function kf(e,t){xf.m(e,t);var n=wf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Mt(r)+`"][href="`+Mt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rf(e)}if(!vf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),vf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zf(a)))return}r=n.createElement(`link`),Rd(r,`link`,e),ht(r),n.head.appendChild(r)}}}function Af(e,t,n){xf.S(e,t,n);var r=wf;if(r&&e){var i=mt(r).hoistableStyles,a=Pf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Ff(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vf.get(a))&&Hf(e,n);var c=o=r.createElement(`link`);ht(c),Rd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jf(e,t){xf.X(e,t);var n=wf;if(n&&e){var r=mt(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=m({src:e,async:!0},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),ht(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t){xf.M(e,t);var n=wf;if(n&&e){var r=mt(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),ht(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nf(e,t,n,r){var a=(a=ce.current)?bf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Pf(n.href),n=mt(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pf(n.href);var o=mt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Ff(e)))&&!o._p&&(s.instance=o,s.state.loading=5),vf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vf.set(e,n),o||Lf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Rf(n),n=mt(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Pf(e){return`href="`+Mt(e)+`"`}function Ff(e){return`link[rel="stylesheet"][`+e+`]`}function If(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Lf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Rd(t,`link`,n),ht(t),e.head.appendChild(t))}function Rf(e){return`[src="`+Mt(e)+`"]`}function zf(e){return`script[async]`+e}function Bf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Mt(n.href)+`"]`);if(r)return t.instance=r,ht(r),r;var a=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),ht(r),Rd(r,`style`,a),Vf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Pf(n.href);var o=e.querySelector(Ff(a));if(o)return t.state.loading|=4,t.instance=o,ht(o),o;r=If(n),(a=vf.get(a))&&Hf(r,a),o=(e.ownerDocument||e).createElement(`link`),ht(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Rd(o,`link`,r),t.state.loading|=4,Vf(o,n.precedence,e),t.instance=o;case`script`:return o=Rf(n.src),(a=e.querySelector(zf(o)))?(t.instance=a,ht(a),a):(r=n,(a=vf.get(o))&&(r=m({},n),Uf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),ht(a),Rd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vf(r,n.precedence,e));return t.instance}function Vf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Yf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pf(r.href),a=t.querySelector(Ff(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Qf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,ht(a);return}a=t.ownerDocument||t,r=If(r),(i=vf.get(i))&&Hf(r,i),a=a.createElement(`link`),ht(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Rd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Qf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Xf=0;function Zf(e,t){return e.stylesheets&&e.count===0&&ep(e,e.stylesheets),0Xf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Qf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ep(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var $f=null;function ep(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,$f=new Map,t.forEach(tp,e),$f=null,Qf.call(e))}function tp(e,t){if(!(t.state.loading&4)){var n=$f.get(e);if(n)var r=n.get(null);else{n=new Map,$f.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=g()})),v=l(d()),y=_(),b=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),x=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),S={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},C=(0,v.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,v.createElement)(`svg`,{ref:c,...S,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:x(`lucide`,i),...s},[...o.map(([e,t])=>(0,v.createElement)(e,t)),...Array.isArray(a)?a:[a]])),w=(e,t)=>{let n=(0,v.forwardRef)(({className:n,...r},i)=>(0,v.createElement)(C,{ref:i,iconNode:t,className:x(`lucide-${b(e)}`,n),...r}));return n.displayName=`${e}`,n},T=w(`Activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),E=w(`ArrowDownToLine`,[[`path`,{d:`M12 17V3`,key:`1cwfxf`}],[`path`,{d:`m6 11 6 6 6-6`,key:`12ii2o`}],[`path`,{d:`M19 21H5`,key:`150jfl`}]]),D=w(`ArrowUpFromLine`,[[`path`,{d:`m18 9-6-6-6 6`,key:`kcunyi`}],[`path`,{d:`M12 3v14`,key:`7cf3v8`}],[`path`,{d:`M5 21h14`,key:`11awu3`}]]),O=w(`Ban`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m4.9 4.9 14.2 14.2`,key:`1m5liu`}]]),k=w(`Blocks`,[[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`path`,{d:`M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3`,key:`1fpvtg`}]]),A=w(`Bot`,[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]),j=w(`Check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),M=w(`ChevronDown`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),N=w(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),ee=w(`ChevronUp`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),te=w(`ChevronsDownUp`,[[`path`,{d:`m7 20 5-5 5 5`,key:`13a0gw`}],[`path`,{d:`m7 4 5 5 5-5`,key:`1kwcof`}]]),P=w(`ChevronsUpDown`,[[`path`,{d:`m7 15 5 5 5-5`,key:`1hf1tw`}],[`path`,{d:`m7 9 5-5 5 5`,key:`sgt6xg`}]]),F=w(`CircleCheck`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),ne=w(`CircleStop`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`rect`,{x:`9`,y:`9`,width:`6`,height:`6`,rx:`1`,key:`1ssd4o`}]]),re=w(`Clock`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`polyline`,{points:`12 6 12 12 16 14`,key:`68esgv`}]]),ie=w(`Coins`,[[`circle`,{cx:`8`,cy:`8`,r:`6`,key:`3yglwk`}],[`path`,{d:`M18.09 10.37A6 6 0 1 1 10.34 18`,key:`t5s6rm`}],[`path`,{d:`M7 6h1v4`,key:`1obek4`}],[`path`,{d:`m16.71 13.88.7.71-2.82 2.82`,key:`1rbuyh`}]]),ae=w(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),I=w(`Download`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`7 10 12 15 17 10`,key:`2ggqvy`}],[`line`,{x1:`12`,x2:`12`,y1:`15`,y2:`3`,key:`1vk2je`}]]),L=w(`Eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),oe=w(`FileCode`,[[`path`,{d:`M10 12.5 8 15l2 2.5`,key:`1tg20x`}],[`path`,{d:`m14 12.5 2 2.5-2 2.5`,key:`yinavb`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z`,key:`1mlx9k`}]]),se=w(`FileOutput`,[[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2`,key:`1vk7w2`}],[`path`,{d:`M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6`,key:`1jink5`}],[`path`,{d:`m5 11-3 3`,key:`1dgrs4`}],[`path`,{d:`m5 17-3-3h10`,key:`1mvvaf`}]]),ce=w(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),le=w(`GitBranch`,[[`line`,{x1:`6`,x2:`6`,y1:`3`,y2:`15`,key:`17qcm7`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M18 9a9 9 0 0 1-9 9`,key:`n2h4wq`}]]),ue=w(`Hash`,[[`line`,{x1:`4`,x2:`20`,y1:`9`,y2:`9`,key:`4lhtct`}],[`line`,{x1:`4`,x2:`20`,y1:`15`,y2:`15`,key:`vyu0kd`}],[`line`,{x1:`10`,x2:`8`,y1:`3`,y2:`21`,key:`1ggp8o`}],[`line`,{x1:`16`,x2:`14`,y1:`3`,y2:`21`,key:`weycgp`}]]),de=w(`Layers`,[[`path`,{d:`M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z`,key:`zw3jo`}],[`path`,{d:`M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12`,key:`1wduqc`}],[`path`,{d:`M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17`,key:`kqbvx6`}]]),fe=w(`ListChecks`,[[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`m3 7 2 2 4-4`,key:`1obspn`}],[`path`,{d:`M13 6h8`,key:`15sg57`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 18h8`,key:`oe0vm4`}]]),pe=w(`LoaderCircle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),me=w(`Maximize`,[[`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`,key:`1dcmit`}],[`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`,key:`1e4gt3`}],[`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`,key:`wsl5sc`}],[`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`,key:`18trek`}]]),he=w(`MessageCircle`,[[`path`,{d:`M7.9 20A9 9 0 1 0 4 16.1L2 22Z`,key:`vv11sd`}]]),ge=w(`MessageSquarePlus`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M12 7v6`,key:`lw1j43`}],[`path`,{d:`M9 10h6`,key:`9gxzsh`}]]),_e=w(`Octagon`,[[`path`,{d:`M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z`,key:`2d38gg`}]]),ve=w(`Pause`,[[`rect`,{x:`14`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`zuxfzm`}],[`rect`,{x:`6`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`1okwgv`}]]),ye=w(`Play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),be=w(`Repeat`,[[`path`,{d:`m17 2 4 4-4 4`,key:`nntrym`}],[`path`,{d:`M3 11v-1a4 4 0 0 1 4-4h14`,key:`84bu3i`}],[`path`,{d:`m7 22-4-4 4-4`,key:`1wqhfi`}],[`path`,{d:`M21 13v1a4 4 0 0 1-4 4H3`,key:`1rx37r`}]]),xe=w(`Search`,[[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`path`,{d:`m21 21-4.3-4.3`,key:`1qie3q`}]]),Se=w(`Send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),Ce=w(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),we=w(`SkipForward`,[[`polygon`,{points:`5 4 15 12 5 20 5 4`,key:`16p6eg`}],[`line`,{x1:`19`,x2:`19`,y1:`5`,y2:`19`,key:`futhcm`}]]),Te=w(`SquareTerminal`,[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]]),Ee=w(`Square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),De=w(`Terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),Oe=w(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),ke=w(`Variable`,[[`path`,{d:`M8 21s-4-3-4-9 4-9 4-9`,key:`uto9ud`}],[`path`,{d:`M16 3s4 3 4 9-4 9-4 9`,key:`4w2vsq`}],[`line`,{x1:`15`,x2:`9`,y1:`9`,y2:`15`,key:`f7djnv`}],[`line`,{x1:`9`,x2:`15`,y1:`9`,y2:`15`,key:`1shsy8`}]]),Ae=w(`WifiOff`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}],[`path`,{d:`M5 12.859a10 10 0 0 1 5.17-2.69`,key:`1dl1wf`}],[`path`,{d:`M19 12.859a10 10 0 0 0-2.007-1.523`,key:`4k23kn`}],[`path`,{d:`M2 8.82a15 15 0 0 1 4.177-2.643`,key:`1grhjp`}],[`path`,{d:`M22 8.82a15 15 0 0 0-11.288-3.764`,key:`z3jwby`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),je=w(`Wifi`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M2 8.82a15 15 0 0 1 20 0`,key:`dnpr2z`}],[`path`,{d:`M5 12.859a10 10 0 0 1 14 0`,key:`1x1e6c`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}]]),Me=w(`X`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),Ne=w(`Zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]),Pe=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},Fe=(e=>e?Pe(e):Pe),Ie=e=>e;function Le(e,t=Ie){let n=v.useSyncExternalStore(e.subscribe,v.useCallback(()=>t(e.getState()),[e,t]),v.useCallback(()=>t(e.getInitialState()),[e,t]));return v.useDebugValue(n),n}var Re=e=>{let t=Fe(e),n=e=>Le(t,e);return Object.assign(n,t),n},ze=(e=>e?Re(e):Re);function Be(e,t){if(t.type===`guidance_received`)return[...e,{text:t.data.text,applied:!1}];let n=e.findIndex(e=>!e.applied&&e.text===t.data.text);if(n===-1)return[...e,{text:t.data.text,applied:!0,source:t.data.source,agentName:t.data.agent_name}];let r=[...e];return r[n]={...r[n],applied:!0,source:t.data.source,agentName:t.data.agent_name},r}function Ve(){return window.__CONDUCTOR_TOKEN__}function He(){let e=Ve();return e?{Authorization:`Bearer ${e}`}:{}}function Ue(e){let t=Ve();return t?`${e}${e.includes(`?`)?`&`:`?`}token=${encodeURIComponent(t)}`:e}function R(e,t,n=`agent`){return e[t]||(e[t]={name:t,status:`pending`,type:n,activity:[]}),e[t].activity||(e[t].activity=[]),e[t]}function We(e,t,n){R(e,t).activity.push(n)}function z(e,t){e[t]&&(e[t]={...e[t]})}function Ge(e,t,n,r){let i=e[t];if(!i?.for_each_items)return;let a=i.for_each_items.find(e=>e.key===n);a&&a.activity.push(r)}function Ke(e,t,n,r){return{parentAgent:e,iteration:t,slotKey:r??e,workflowFile:n,workflowName:``,status:`pending`,agents:[],routes:[],parallelGroups:[],forEachGroups:[],nodes:{},groupProgress:{},highlightedEdges:[],entryPoint:null,children:[],agentsCompleted:0,agentsTotal:0,totalCost:0,totalTokens:0,unpricedCount:0,eventLog:[],activityLog:[],workflowOutput:null,workflowFailure:null}}function qe(e,t,n){let r=Ke(e,1,n,e);r.workflowName=t.name||``,r.entryPoint=t.entry_point||null,r.agents=t.agents,r.routes=t.routes||[],r.parallelGroups=t.parallel_groups||[],r.forEachGroups=t.for_each_groups||[];let i=new Set,a=new Set,o=new Map(r.agents.map(e=>[e.name,e.type||`agent`]));for(let e of r.parallelGroups){for(let t of e.agents)i.add(t);a.add(e.name),R(r.nodes,e.name,`parallel_group`),r.groupProgress[e.name]={total:e.agents.length,completed:0,failed:0};for(let t of e.agents)R(r.nodes,t,o.get(t)||`agent`)}for(let e of r.forEachGroups)a.add(e.name),R(r.nodes,e.name,`for_each_group`),r.groupProgress[e.name]={total:0,completed:0,failed:0};for(let e of r.agents){if(a.has(e.name)||i.has(e.name))continue;let t=e.type||`agent`;R(r.nodes,e.name,t),a.add(e.name)}return Je(r.agents,r.children),r}function Je(e,t){for(let n of e)n.type!==`workflow`||!n.subworkflow||t.some(e=>e.slotKey===n.name)||t.push(qe(n.name,n.subworkflow,``))}function Ye(e){return{...e,agents:[...e.agents],routes:[...e.routes],parallelGroups:[...e.parallelGroups],forEachGroups:[...e.forEachGroups],nodes:{...e.nodes},groupProgress:{...e.groupProgress},highlightedEdges:[...e.highlightedEdges],eventLog:[...e.eventLog],activityLog:[...e.activityLog],children:[...e.children]}}function Xe(e,t){function n(e,t){let r=[...e];if(t.length===0)return{contexts:r,ctx:null};let i=t[0],a=r[i];if(!a)return{contexts:r,ctx:null};let o=Ye(a);if(t.length>1){let e=n(a.children,t.slice(1));return o.children=e.contexts,r[i]=o,{contexts:r,ctx:e.ctx}}return r[i]=o,{contexts:r,ctx:o}}let r=n(e.subworkflowContexts,t);return e.subworkflowContexts=r.contexts,r.ctx}function Ze(e,t){let n=$e(e.subworkflowContexts,t);if(!n)return null;let r=Xe(e,n.indexPath);return{indexPath:n.indexPath,ctx:r}}function Qe(e,t){if(t.length===0)return null;let n=e[t[0]];for(let e=1;e=0;n--)if(r[n].slotKey===e){t=n;break}if(t===-1)return null;n.push(t),i=r[t],r=i.children}return{indexPath:n,ctx:i}}function et(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.slotKey===t)return{ctx:r,index:n}}return null}var B=ze((e,t)=>({workflowName:``,workflowStatus:`pending`,workflowStartTime:null,workflowFailure:null,workflowFailedAgent:null,workflowTermination:null,workflowYaml:null,conductorVersion:null,entryPoint:null,agents:[],routes:[],parallelGroups:[],forEachGroups:[],nodes:{},groupProgress:{},highlightedEdges:[],agentsCompleted:0,agentsTotal:0,totalCost:0,totalTokens:0,unpricedCount:0,selectedNode:null,wsStatus:`connecting`,wsDisconnectedSince:null,wsAuthFailed:!1,wsSendFailed:!1,systemLogFile:null,bgStderrLog:null,bgStdoutLog:null,eventLog:[],activityLog:[],workflowOutput:null,lastEventTime:null,isPaused:!1,iterationLimitGate:null,userGuidance:[],wfDepth:0,subworkflowContexts:[],activeContextPath:[],viewContextPath:[],expandedContexts:new Set,replayMode:!1,replayEvents:[],replayPosition:0,replayTotalEvents:0,replayPlaying:!1,replaySpeed:1,_wsSend:null,setWsSend:t=>{e({_wsSend:t})},sendGateResponse:(t,n,r,i)=>{let a=B.getState()._wsSend;a?(a({type:`gate_response`,agent_name:t,selected_value:n,additional_input:r||{},prompt_id:i??null}),e({wsSendFailed:!1})):(console.error(`sendGateResponse: WebSocket not connected, response was not sent`),e({wsSendFailed:!0}))},activeDialog:null,dialogEngaged:!1,engageDialog:()=>{e({dialogEngaged:!0})},sendDialogMessage:(t,n,r)=>{let i=B.getState()._wsSend;i?(i({type:`dialog_message`,agent_name:t,dialog_id:n,content:r}),e({wsSendFailed:!1})):(console.error(`sendDialogMessage: WebSocket not connected, message was not sent`),e({wsSendFailed:!0}))},sendDialogDecline:(t,n)=>{let r=B.getState()._wsSend;r?(r({type:`dialog_decline`,agent_name:t,dialog_id:n}),e({wsSendFailed:!1})):(console.error(`sendDialogDecline: WebSocket not connected, decline was not sent`),e({wsSendFailed:!0}))},sendIterationLimitResponse:(t,n,r)=>{let i=B.getState()._wsSend;if(!i){console.error(`sendIterationLimitResponse: WebSocket not connected, response was not sent`),e({wsSendFailed:!0});return}let a=Math.max(0,Math.floor(Number(r)||0));i({type:`iteration_limit_response`,gate_id:n,...`agent_name`in t?{agent_name:t.agent_name}:{group_name:t.group_name},additional_iterations:a}),e({wsSendFailed:!1})},sendGuidance:async e=>{try{let t=await fetch(`/api/guidance`,{method:`POST`,headers:{"Content-Type":`application/json`,...He()},body:JSON.stringify({text:e})}),n=await t.json().catch(()=>({}));return t.ok?{ok:!0,pending:n.pending??0,paused:n.paused??!1}:{ok:!1,status:t.status,error:n.error||`HTTP ${t.status}`}}catch{return{ok:!1,status:null,error:`The dashboard is unreachable.`}}},processEvent:t=>{let n=nt[t.type];e(e=>{let r={...e,nodes:{...e.nodes},groupProgress:{...e.groupProgress},eventLog:[...e.eventLog],activityLog:[...e.activityLog],lastEventTime:t.timestamp};n&&n(r,t.data,t.timestamp);let i=it(t);i&&r.eventLog.push(i);let a=ot(t);return a&&r.activityLog.push(a),r})},replayState:t=>{e(e=>{let n={...e,agentsCompleted:0,totalCost:0,totalTokens:0,unpricedCount:0,nodes:{},groupProgress:{},highlightedEdges:[],eventLog:[],activityLog:[],workflowOutput:null,workflowFailedAgent:null,workflowTermination:null,activeDialog:null,dialogEngaged:!1,wfDepth:0,subworkflowContexts:[],activeContextPath:[]};for(let e of t){let t=nt[e.type];t&&t(n,e.data,e.timestamp);let r=it(e);r&&n.eventLog.push(r);let i=ot(e);i&&n.activityLog.push(i),n.lastEventTime=e.timestamp}return n})},selectNode:t=>{e({selectedNode:t})},toggleContextExpanded:t=>{e(e=>{let n=new Set(e.expandedContexts);return n.has(t)?n.delete(t):n.add(t),{expandedContexts:n}})},expandContexts:t=>{t.length!==0&&e(e=>{let n=new Set(e.expandedContexts),r=!1;for(let e of t)n.has(e)||(n.add(e),r=!0);return r?{expandedContexts:n}:{}})},collapseContexts:t=>{t.length!==0&&e(e=>{let n=new Set(e.expandedContexts),r=!1;for(let e of t)n.delete(e)&&(r=!0);return r?{expandedContexts:n}:{}})},markReplayMode:()=>{e({replayMode:!0})},setReplayMode:t=>{e(e=>{let n={...e,replayMode:!0,replayEvents:t,replayTotalEvents:t.length,replayPosition:t.length,replayPlaying:!1,replaySpeed:1,agentsCompleted:0,totalCost:0,totalTokens:0,unpricedCount:0,nodes:{},groupProgress:{},highlightedEdges:[],eventLog:[],activityLog:[],workflowOutput:null,workflowFailedAgent:null,workflowTermination:null,activeDialog:null,dialogEngaged:!1,wfDepth:0,subworkflowContexts:[],activeContextPath:[],viewContextPath:[]};for(let e of t){let t=nt[e.type];t&&t(n,e.data,e.timestamp);let r=it(e);r&&n.eventLog.push(r);let i=ot(e);i&&n.activityLog.push(i),n.lastEventTime=e.timestamp}return n})},setReplayPosition:t=>{e(e=>{let n=e.replayEvents.slice(0,t),r={...e,replayPosition:t,agentsCompleted:0,totalCost:0,totalTokens:0,unpricedCount:0,nodes:{},groupProgress:{},highlightedEdges:[],eventLog:[],activityLog:[],workflowOutput:null,workflowFailedAgent:null,workflowTermination:null,workflowStatus:`pending`,workflowStartTime:null,workflowName:``,workflowFailure:null,entryPoint:null,agents:[],routes:[],parallelGroups:[],forEachGroups:[],isPaused:!1,iterationLimitGate:null,userGuidance:[],lastEventTime:null,activeDialog:null,dialogEngaged:!1,wfDepth:0,subworkflowContexts:[],activeContextPath:[],viewContextPath:[]};for(let e of n){let t=nt[e.type];t&&t(r,e.data,e.timestamp);let n=it(e);n&&r.eventLog.push(n);let i=ot(e);i&&r.activityLog.push(i),r.lastEventTime=e.timestamp}return r})},setReplayPlaying:t=>{e({replayPlaying:t})},setReplaySpeed:t=>{e({replaySpeed:t})},setWsStatus:t=>{e(e=>{let n=e.wsDisconnectedSince;return t===`connected`?n=null:(e.wsStatus===`connected`||n===null)&&(n=Date.now()),{wsStatus:t,wsDisconnectedSince:n}})},setWsAuthFailed:t=>{e({wsAuthFailed:t})},setWsSendFailed:t=>{e({wsSendFailed:t})},setEdgeHighlight:(t,n,r)=>{e(e=>({highlightedEdges:[...e.highlightedEdges.filter(e=>!(e.from===t&&e.to===n)),{from:t,to:n,state:r}]}))},clearEdgeHighlight:(t,n)=>{e(e=>({highlightedEdges:e.highlightedEdges.filter(e=>!(e.from===t&&e.to===n))}))},navigateToContext:t=>{e({viewContextPath:t,selectedNode:null})},navigateUp:()=>{e(e=>({viewContextPath:e.viewContextPath.slice(0,-1),selectedNode:null}))},navigateIntoSubworkflow:n=>{let r=t(),i=r.viewContextPath,a;if(i.length===0)a=r.subworkflowContexts;else{let e=Qe(r.subworkflowContexts,i);if(!e)return;a=e.children}let o=et(a,n);o&&e({viewContextPath:[...i,o.index],selectedNode:null})},getViewedContext:()=>{let e=t();if(e.viewContextPath.length===0)return{workflowName:e.workflowName,agents:e.agents,routes:e.routes,parallelGroups:e.parallelGroups,forEachGroups:e.forEachGroups,nodes:e.nodes,groupProgress:e.groupProgress,highlightedEdges:e.highlightedEdges,entryPoint:e.entryPoint,subworkflowContexts:e.subworkflowContexts};let n=Qe(e.subworkflowContexts,e.viewContextPath);return n?{workflowName:n.workflowName,agents:n.agents,routes:n.routes,parallelGroups:n.parallelGroups,forEachGroups:n.forEachGroups,nodes:n.nodes,groupProgress:n.groupProgress,highlightedEdges:n.highlightedEdges,entryPoint:n.entryPoint,subworkflowContexts:n.children}:{workflowName:e.workflowName,agents:e.agents,routes:e.routes,parallelGroups:e.parallelGroups,forEachGroups:e.forEachGroups,nodes:e.nodes,groupProgress:e.groupProgress,highlightedEdges:e.highlightedEdges,entryPoint:e.entryPoint,subworkflowContexts:e.subworkflowContexts}},getBreadcrumbs:()=>{let e=t(),n=[{label:e.workflowName||`Root`,path:[]}],r=e.subworkflowContexts;for(let t=0;te.slotKey===a.slotKey).length>1?`${o} (iteration ${a.iteration})`:o;n.push({label:s,path:e.viewContextPath.slice(0,t+1)}),r=a.children}return n}}));function V(e,t){let n=null,r=t?.subworkflow_path;if(Array.isArray(r)&&r.length>0&&(n=Ze(e,r)?.ctx??null),n){let t=n;return{nodes:t.nodes,groupProgress:t.groupProgress,routes:t.routes,highlightedEdges:t.highlightedEdges,addCost:n=>{t.totalCost+=n,e.totalCost+=n},addTokens:n=>{t.totalTokens+=n,e.totalTokens+=n},addUnpriced:()=>{t.unpricedCount++,e.unpricedCount++},incrCompleted:()=>{t.agentsCompleted++,e.agentsCompleted++}}}return{nodes:e.nodes,groupProgress:e.groupProgress,routes:e.routes,highlightedEdges:e.highlightedEdges,addCost:t=>{e.totalCost+=t},addTokens:t=>{e.totalTokens+=t},addUnpriced:()=>{e.unpricedCount++},incrCompleted:()=>{e.agentsCompleted++}}}function tt(e,t){let n=e.findIndex(e=>e.slotKey===t.slotKey&&e.status===`pending`);if(n>=0){let r=e[n];return e[n]={...r,parentAgent:t.parentAgent,iteration:t.iteration,workflowFile:t.workflowFile||r.workflowFile},n}return e.push(t),e.length-1}var nt={workflow_started:(e,t,n)=>{let r=t;if(e.wfDepth===0){e.workflowStatus=`running`,e.workflowStartTime=n??Date.now()/1e3,e.workflowName=r.name||``,e.workflowYaml=t.yaml_source??null,e.conductorVersion=t.version??null,e.entryPoint=r.entry_point||null,e.systemLogFile=r.system?.log_file||null,e.bgStderrLog=r.system?.bg_stderr_log??null,e.bgStdoutLog=r.system?.bg_stdout_log??null,e.agents=r.agents||[],e.routes=r.routes||[],e.parallelGroups=r.parallel_groups||[],e.forEachGroups=r.for_each_groups||[],e.userGuidance=[],R(e.nodes,`$start`,`start`),e.nodes.$start.status=`running`,z(e.nodes,`$start`);let i=new Set,a=new Set,o=new Map(e.agents.map(e=>[e.name,e.type||`agent`]));for(let t of e.parallelGroups){for(let e of t.agents)i.add(e);a.add(t.name),R(e.nodes,t.name,`parallel_group`),e.groupProgress[t.name]={total:t.agents.length,completed:0,failed:0};for(let n of t.agents)R(e.nodes,n,o.get(n)||`agent`)}for(let t of e.forEachGroups)a.add(t.name),R(e.nodes,t.name,`for_each_group`),e.groupProgress[t.name]={total:0,completed:0,failed:0};for(let t of e.agents)if(!a.has(t.name)&&!i.has(t.name)){let n=t.type||`agent`;if(R(e.nodes,t.name,n),t.model&&(e.nodes[t.name].model=t.model),t.reasoning_effort&&(e.nodes[t.name].reasoning_effort=t.reasoning_effort),t.provider_name){e.nodes[t.name].provider_name=t.provider_name;let n=r.providers?.[t.provider_name];n?.tier&&(e.nodes[t.name].provider_tier=n.tier)}a.add(t.name)}e.agentsTotal=a.size,Xe(e,[]),Je(e.agents,e.subworkflowContexts)}else{let n=t.subworkflow_path,i=Array.isArray(n)&&n.length>0?Ze(e,n)?.ctx??null:Xe(e,e.activeContextPath);if(i){i.workflowName=r.name||``,i.status=`running`,i.entryPoint=r.entry_point||null,i.agents=r.agents||[],i.routes=r.routes||[],i.parallelGroups=r.parallel_groups||[],i.forEachGroups=r.for_each_groups||[],R(i.nodes,`$start`,`start`),i.nodes.$start.status=`running`;let e=new Set,t=new Set,n=new Map(i.agents.map(e=>[e.name,e.type||`agent`]));for(let r of i.parallelGroups){for(let t of r.agents)e.add(t);t.add(r.name),R(i.nodes,r.name,`parallel_group`),i.groupProgress[r.name]={total:r.agents.length,completed:0,failed:0};for(let e of r.agents)R(i.nodes,e,n.get(e)||`agent`)}for(let e of i.forEachGroups)t.add(e.name),R(i.nodes,e.name,`for_each_group`),i.groupProgress[e.name]={total:0,completed:0,failed:0};for(let n of i.agents)if(!t.has(n.name)&&!e.has(n.name)){let e=n.type||`agent`;if(R(i.nodes,n.name,e),n.model&&(i.nodes[n.name].model=n.model),n.reasoning_effort&&(i.nodes[n.name].reasoning_effort=n.reasoning_effort),n.provider_name){i.nodes[n.name].provider_name=n.provider_name;let e=r.providers?.[n.provider_name];e?.tier&&(i.nodes[n.name].provider_tier=e.tier)}t.add(n.name)}i.agentsTotal=t.size;for(let e of i.agents){let t=i.nodes[e.name];t&&(t.type=e.type||`agent`)}Je(i.agents,i.children)}}e.wfDepth++},agent_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.iteration!=null&&(a.output!=null||a.error_type!=null)&&(a.iterationHistory||=[],a.iterationHistory.push({iteration:a.iteration,prompt:a.prompt,output:a.output,elapsed:a.elapsed,model:a.model,reasoning_effort:a.reasoning_effort,tokens:a.tokens,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd,activity:a.activity,error_type:a.error_type,error_message:a.error_message})),a.status=`running`,a.iteration=r.iteration,a.startedAt=n??Date.now()/1e3,a.activity=[],r.context_window_max!=null&&(a.context_window_max=r.context_window_max),a.prompt=void 0,a.output=void 0,a.error_type=void 0,a.error_message=void 0,a.context_pct=void 0,z(i.nodes,r.agent_name)},agent_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.model=n.model,i.tokens=n.tokens,i.input_tokens=n.input_tokens,i.output_tokens=n.output_tokens,i.cost_usd=n.cost_usd,i.output=n.output,i.output_keys=n.output_keys,i.context_window_used=n.context_window_used,i.context_window_max=n.context_window_max,n.context_window_used!=null&&n.context_window_max!=null&&n.context_window_max>0?i.context_pct=Math.round(n.context_window_used/n.context_window_max*100):i.context_pct=void 0,n.cost_usd&&r.addCost(n.cost_usd),n.tokens&&r.addTokens(n.tokens),n.tokens&&n.cost_usd==null&&r.addUnpriced();let a=t;a.terminated_by&&(i.termination_status=a.status??`success`,i.termination_reason=a.termination_reason,i.terminated_by=a.terminated_by),z(r.nodes,n.agent_name)},agent_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message;for(let e of r.routes)e.to===n.agent_name&&r.highlightedEdges.push({from:e.from,to:e.to,state:`failed`});let a=t;a.terminated_by&&(i.termination_status=a.status??`failed`,i.termination_reason=a.termination_reason,i.terminated_by=a.terminated_by),z(r.nodes,n.agent_name)},agent_prompt_rendered:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=R(i.nodes,n.agent_name);if(a.prompt=n.continuation?`${a.prompt??``}\n\n${n.rendered_prompt}`:n.rendered_prompt,a.context_keys=n.context_keys,r){Ge(i.nodes,n.agent_name,r,{type:`prompt`,icon:`📝`,label:`prompt`,text:`Prompt rendered`,detail:n.rendered_prompt?.slice(0,500)||null});let e=i.nodes[n.agent_name];if(e?.for_each_items){let t=e.for_each_items.find(e=>e.key===r);t&&(t.prompt=n.continuation?`${t.prompt??``}\n\n${n.rendered_prompt}`:n.rendered_prompt)}}z(i.nodes,n.agent_name)},agent_reasoning:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`reasoning`,icon:`💭`,label:`thinking`,text:n.content};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_tool_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`tool-start`,icon:`🔧`,label:`tool`,text:n.tool_name,detail:n.arguments||null};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_tool_complete:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`tool-complete`,icon:`✓`,label:`result`,text:n.tool_name||`done`,detail:n.result||null};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_compaction_config:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=n.enabled===!1?{type:`compaction-config`,icon:`⚙`,label:`compaction`,text:`disabled${n.disabled_reason?`: ${n.disabled_reason}`:``}`}:{type:`compaction-config`,icon:`⚙`,label:`compaction`,text:`armed (window ${n.context_window} from ${n.context_window_source}, output limit ${n.output_limit} from ${n.output_limit_source}, trigger ${n.trigger_tokens??`?`}, target ${n.target_tokens??`?`})`};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_compaction_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`compaction-start`,icon:`🧹`,label:`compacting`,text:`compacting context (${n.tokens_before??`?`} tokens, window ${n.context_window} from ${n.context_window_source})`};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_compaction_complete:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a;if(n.errored)a={type:`compaction-error`,icon:`⚠️`,label:`compaction failed`,text:`${n.error_type||`Error`}: ${n.message||`unknown`}`};else if(n.still_over_trigger||n.degraded_tiers&&n.degraded_tiers.length>0){let e=[...n.degraded_tiers&&n.degraded_tiers.length>0?[`degraded tiers: ${n.degraded_tiers.join(`, `)}`]:[],...n.still_over_trigger?[`still over trigger`]:[]];a={type:`compaction-error`,icon:`⚠️`,label:`compacted with warnings`,text:`${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${e.join(`; `)})`}}else a={type:`compaction-complete`,icon:`🧹`,label:`compacted`,text:`${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${n.messages_before??`?`} → ${n.messages_after??`?`} messages, ${n.elapsed==null?`?`:at(n.elapsed)}${n.tokens_saved==null?``:`, saved ${n.tokens_saved} tokens`})`};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_tool_output_truncated:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`tool-complete`,icon:`✂`,label:`truncated`,text:n.tool_name||`tool`,detail:`${n.original_chars}→${n.kept_chars} chars${n.spill_path?` · full: `+n.spill_path:``}`};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_parse_recovery:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`parse-recovery`,icon:`↻`,label:`retry`,text:`${n.reason===`schema`?`output schema mismatch`:`invalid JSON`} (${n.attempt??`?`}/${n.max_attempts??`?`})`,detail:n.error||null};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_turn_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`turn`,icon:`⏳`,label:`turn`,text:`Turn ${n.turn??`?`}`};We(i.nodes,n.agent_name,a),r&&Ge(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_message:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.latest_message=n.content,z(r.nodes,n.agent_name)},script_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.status=`running`,a.startedAt=n??Date.now()/1e3,z(i.nodes,r.agent_name)},script_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.stdout=n.stdout,i.stderr=n.stderr,i.exit_code=n.exit_code,z(r.nodes,n.agent_name)},script_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name)},wait_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.status=`running`,a.startedAt=n??Date.now()/1e3,a.duration_seconds=r.duration_seconds??null,a.reason=r.reason??null,a.iteration=r.iteration,z(i.nodes,r.agent_name)},wait_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.waited_seconds=n.waited_seconds,i.requested_seconds=n.requested_seconds,i.reason=n.reason??null,i.interrupted=n.interrupted,z(r.nodes,n.agent_name)},wait_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name)},set_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.status=`running`,a.startedAt=n??Date.now()/1e3,z(i.nodes,r.agent_name)},set_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.set_output_type=n.output_type,i.set_output_keys=n.output_keys,i.set_value_repr=n.value_repr,z(r.nodes,n.agent_name)},set_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name)},mcp_started:(e,t,n)=>{let r=t,i=V(e,t);if(r.group_name!=null&&r.item_key!=null){let e=R(i.nodes,r.group_name,`for_each_group`);e.for_each_items&&=e.for_each_items.map(e=>e.key===r.item_key?{...e,status:`running`}:e),z(i.nodes,r.group_name)}else{let e=R(i.nodes,r.agent_name,`mcp`);e.status=`running`,e.startedAt=n??Date.now()/1e3,z(i.nodes,r.agent_name)}},mcp_completed:(e,t)=>{let n=t,r=V(e,t);if(n.group_name!=null&&n.item_key!=null){let e=R(r.nodes,n.group_name,`for_each_group`);e.for_each_items&&=e.for_each_items.map(e=>e.key===n.item_key?{...e,status:`completed`,elapsed:n.elapsed,mcp_server:n.server,mcp_tool:n.tool,mcp_is_error:n.is_error,mcp_result_bytes:n.result_bytes,mcp_truncated:n.truncated,mcp_spill_path:n.spill_path}:e),z(r.nodes,n.group_name)}else{let e=R(r.nodes,n.agent_name,`mcp`);e.status=`completed`,n.group_name??r.incrCompleted(),e.elapsed=n.elapsed,e.mcp_server=n.server,e.mcp_tool=n.tool,e.mcp_is_error=n.is_error,e.mcp_result_bytes=n.result_bytes,e.mcp_truncated=n.truncated,e.mcp_spill_path=n.spill_path,z(r.nodes,n.agent_name)}},mcp_failed:(e,t)=>{let n=t,r=V(e,t);if(n.group_name!=null&&n.item_key!=null){let e=R(r.nodes,n.group_name,`for_each_group`);e.for_each_items&&=e.for_each_items.map(e=>e.key===n.item_key?{...e,status:`failed`,elapsed:n.elapsed,mcp_server:n.server,mcp_tool:n.tool,error_type:n.error_type,error_message:n.message}:e),z(r.nodes,n.group_name)}else{let e=R(r.nodes,n.agent_name,`mcp`);e.status=`failed`,e.elapsed=n.elapsed,e.mcp_server=n.server,e.mcp_tool=n.tool,e.error_type=n.error_type,e.error_message=n.message,z(r.nodes,n.agent_name)}},gate_presented:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`waiting`,i.options=n.options,i.option_details=n.option_details,i.prompt=n.prompt,i.gate_prompt_id=n.prompt_id??null,z(r.nodes,n.agent_name)},gate_resolved:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.selected_option=n.selected_option,i.route=n.route,i.additional_input=n.additional_input,z(r.nodes,n.agent_name)},questions_presented:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.status=`waiting`,i.questions_total=n.total,i.questions_answered_count=0,i.questions_skipped_count=0,i.questions_outcomes={},i.questions_outcome=void 0,z(r.nodes,n.agent_name)},questions_answered:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.questions_total=n.total;let a={...i.questions_outcomes||{}};a[n.question_id]=n.skipped?`skipped`:`answered`,i.questions_outcomes=a;let o=Object.values(a);i.questions_answered_count=o.filter(e=>e===`answered`).length,i.questions_skipped_count=o.filter(e=>e===`skipped`).length,i.questions_reject_reason=null,z(r.nodes,n.agent_name)},questions_answer_rejected:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.questions_reject_reason=n.reason,z(r.nodes,n.agent_name)},questions_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.status=`completed`,r.incrCompleted(),i.questions_outcome=n.outcome,i.questions_answered_count=n.answered_count,i.questions_skipped_count=n.skipped_count,i.questions_reject_reason=null,z(r.nodes,n.agent_name)},route_taken:(e,t)=>{let n=t;V(e,t).highlightedEdges.push({from:n.from_agent,to:n.to_agent,state:`taken`})},parallel_started:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.group_name,`parallel_group`);i.status=`running`,r.groupProgress[n.group_name]&&(r.groupProgress[n.group_name].total=n.agents.length,r.groupProgress[n.group_name].completed=0,r.groupProgress[n.group_name].failed=0),z(r.nodes,n.group_name)},parallel_agent_completed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].completed++;let i=R(r.nodes,n.agent_name);i.status=`completed`,i.elapsed=n.elapsed,i.model=n.model,i.tokens=n.tokens,i.cost_usd=n.cost_usd,i.context_window_used=n.context_window_used,i.context_window_max=n.context_window_max,n.context_window_used!=null&&n.context_window_max!=null&&n.context_window_max>0?i.context_pct=Math.round(n.context_window_used/n.context_window_max*100):i.context_pct=void 0,n.cost_usd&&r.addCost(n.cost_usd),n.tokens&&r.addTokens(n.tokens),n.tokens&&n.cost_usd==null&&r.addUnpriced(),z(r.nodes,n.agent_name),z(r.nodes,n.group_name)},parallel_agent_failed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].failed++;let i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name),z(r.nodes,n.group_name)},parallel_completed:(e,t)=>{let n=t,r=V(e,t);r.incrCompleted();let i=R(r.nodes,n.group_name,`parallel_group`);i.status=n.failure_count===0?`completed`:`failed`,z(r.nodes,n.group_name)},for_each_started:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.group_name,`for_each_group`);i.status=`running`,i.for_each_items=[],r.groupProgress[n.group_name]&&(r.groupProgress[n.group_name].total=n.item_count,r.groupProgress[n.group_name].completed=0,r.groupProgress[n.group_name].failed=0),z(r.nodes,n.group_name)},for_each_item_started:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.group_name,`for_each_group`);i.for_each_items||=[],i.for_each_items.push({key:n.item_key??String(n.index),index:n.index,status:`running`,activity:[]}),z(r.nodes,n.group_name)},for_each_item_completed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].completed++;let i=R(r.nodes,n.group_name,`for_each_group`);if(i.for_each_items){let e=n.item_key??String(n.index),t=i.for_each_items.find(t=>t.key===e);t&&(t.status=`completed`,t.elapsed=n.elapsed,t.tokens=n.tokens,t.cost_usd=n.cost_usd,t.output=n.output)}z(r.nodes,n.group_name)},for_each_item_failed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].failed++;let i=R(r.nodes,n.group_name,`for_each_group`);if(i.for_each_items){let e=n.item_key??String(n.index),t=i.for_each_items.find(t=>t.key===e);t&&(t.status=`failed`,t.elapsed=n.elapsed,t.error_type=n.error_type,t.error_message=n.message)}z(r.nodes,n.group_name)},for_each_completed:(e,t)=>{let n=t,r=V(e,t);r.incrCompleted();let i=R(r.nodes,n.group_name,`for_each_group`);i.status=(n.failure_count??0)===0?`completed`:`failed`,i.elapsed=n.elapsed,i.success_count=n.success_count,i.failure_count=n.failure_count,z(r.nodes,n.group_name)},workflow_completed:(e,t)=>{if(e.wfDepth=Math.max(0,e.wfDepth-1),e.wfDepth===0){let n=t;e.workflowStatus=`completed`,e.isPaused=!1,e.iterationLimitGate=null,e.workflowOutput=n.output??null,n.is_explicit?e.workflowTermination={is_explicit:!0,status:n.status??`success`,termination_reason:n.termination_reason,terminated_by:n.terminated_by}:e.workflowTermination=null,e.nodes.$end&&(e.nodes.$end.status=`completed`,z(e.nodes,`$end`)),e.nodes.$start&&(e.nodes.$start.status=`completed`,z(e.nodes,`$start`)),e.highlightedEdges=[]}else{let n=t,r=n.subworkflow_path?Ze(e,n.subworkflow_path)?.ctx:Xe(e,e.activeContextPath);r&&(r.status=`completed`,r.workflowOutput=n.output??null,r.nodes.$end&&(r.nodes.$end.status=`completed`),r.nodes.$start&&(r.nodes.$start.status=`completed`),r.highlightedEdges=[])}},workflow_failed:(e,t)=>{let n=t;if(e.wfDepth=n.stopped_by_user&&!n.subworkflow_path?0:Math.max(0,e.wfDepth-1),e.wfDepth===0){if(e.workflowStatus=`failed`,e.isPaused=!1,e.iterationLimitGate=null,e.workflowFailedAgent=n.agent_name||null,n.agent_name&&e.nodes[n.agent_name]){e.nodes[n.agent_name].status=`failed`,z(e.nodes,n.agent_name);for(let t of e.routes)t.to===n.agent_name&&e.highlightedEdges.push({from:t.from,to:t.to,state:`failed`})}e.workflowFailure={error_type:n.error_type,message:n.message,elapsed_seconds:n.elapsed_seconds,timeout_seconds:n.timeout_seconds,current_agent:n.current_agent,checkpoint_path:n.checkpoint_path,checkpoint_unavailable_reason:n.checkpoint_unavailable_reason,stopped_by_user:n.stopped_by_user,termination_reason:n.termination_reason,terminated_by:n.terminated_by,is_explicit:n.is_explicit,status:n.status},n.is_explicit?e.workflowTermination={is_explicit:!0,status:n.status??`failed`,termination_reason:n.termination_reason,terminated_by:n.terminated_by}:e.workflowTermination=null,e.nodes.$start&&(e.nodes.$start.status=`completed`,z(e.nodes,`$start`))}else{let t=n.subworkflow_path?Ze(e,n.subworkflow_path)?.ctx:Xe(e,e.activeContextPath);t&&(t.status=`failed`,t.workflowFailure={error_type:n.error_type,message:n.message})}},subworkflow_started:(e,t)=>{let n=t,r=n.slot_key??(n.item_key==null?n.agent_name:`${n.agent_name}[${n.item_key}]`),i=Ke(n.agent_name,n.iteration??1,n.workflow,r),a;if(n.parent_path!==void 0){let t=$e(e.subworkflowContexts,n.parent_path);if(!t)return;a=t.indexPath}else a=e.activeContextPath;let o,s=null;if(a.length===0)Xe(e,[]),o=[tt(e.subworkflowContexts,i)];else{if(s=Xe(e,a),!s)return;let t=tt(s.children,i);o=[...a,t]}if(e.activeContextPath=o,a.length===0){let t=e.nodes[n.agent_name];t&&(t.status=`running`,z(e.nodes,n.agent_name))}else if(s){let e=s.nodes[n.agent_name];e&&(e.status=`running`,z(s.nodes,n.agent_name))}},subworkflow_completed:(e,t)=>{let n=t,r;if(n.parent_path!==void 0){let t=$e(e.subworkflowContexts,n.parent_path);if(!t)return;r=t.indexPath}else r=e.activeContextPath;let i=r.length===0?null:Xe(e,r),a=r.length===0?e.nodes:i?.nodes;if(a){let t=a[n.agent_name];t&&(n.item_key??(t.status=`completed`,t.elapsed=n.elapsed,r.length===0?e.agentsCompleted++:i&&i.agentsCompleted++),z(a,n.agent_name))}e.activeContextPath=r},subworkflow_failed:(e,t)=>{let n=t,r;if(n.parent_path!==void 0){let t=$e(e.subworkflowContexts,n.parent_path);if(!t)return;r=t.indexPath}else r=e.activeContextPath;let i=r.length===0?e.nodes:Xe(e,r)?.nodes;if(i){let e=i[n.agent_name];e&&n.item_key==null&&(e.status=`failed`,e.elapsed=n.elapsed,e.error_type=n.error_type,e.error_message=n.message,z(i,n.agent_name))}e.activeContextPath=r},checkpoint_saved:(e,t)=>{let n=t;n.path&&e.workflowFailure&&(e.workflowFailure={...e.workflowFailure,checkpoint_path:n.path})},agent_paused:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.status=`waiting`,r.activity.push({type:`agent_paused`,icon:`⏸`,label:`Paused`,text:`Agent paused — click Resume to re-execute`}),z(e.nodes,n.agent_name),e.isPaused=!0},agent_resumed:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.status=`running`,r.activity.push({type:`agent_resumed`,icon:`▶`,label:`Resumed`,text:n.with_guidance?`Agent resumed with guidance — re-executing`:`Agent resumed — re-executing`}),z(e.nodes,n.agent_name),e.isPaused=!1},guidance_received:(e,t)=>{let n=t;e.userGuidance=Be(e.userGuidance,{type:`guidance_received`,data:n})},guidance_applied:(e,t)=>{let n=t;e.userGuidance=Be(e.userGuidance,{type:`guidance_applied`,data:n}),n.agent_name&&(R(e.nodes,n.agent_name).activity.push({type:`guidance_applied`,icon:`💬`,label:`Guidance`,text:`Guidance applied (${n.source}): ${n.text}`}),z(e.nodes,n.agent_name))},iteration_limit_reached:(e,t)=>{let n=t;e.iterationLimitGate=n;let r=n.agent_name??n.group_name;r?(R(e.nodes,r).activity.push({type:`iteration_limit_reached`,icon:`⚠`,label:`Iteration limit`,text:`Reached ${n.current_iteration}/${n.max_iterations} iterations — ${n.skip_gates?`auto-stopping (--skip-gates)`:`awaiting decision`}`}),z(e.nodes,r)):typeof console<`u`&&console.warn(`[workflow-store] iteration_limit_reached event missing both agent_name and group_name`,n)},iteration_limit_resolved:(e,t)=>{let n=t;e.iterationLimitGate=null;let r=n.agent_name??n.group_name;r?(R(e.nodes,r).activity.push({type:`iteration_limit_resolved`,icon:n.continue_execution?`▶`:`■`,label:`Iteration limit`,text:n.aborted?`Gate aborted unexpectedly — stopping workflow`:n.continue_execution?`Continuing with ${n.additional_iterations} more iteration(s)`:`Stopping workflow`}),z(e.nodes,r)):typeof console<`u`&&console.warn(`[workflow-store] iteration_limit_resolved event missing both agent_name and group_name`,n)},dialog_started:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.dialog_id=n.dialog_id,r.dialog_messages=[],r.dialog_active=!0,r.dialog_awaiting_response=!1,e.activeDialog={agentName:n.agent_name,dialogId:n.dialog_id},e.dialogEngaged=!1,z(e.nodes,n.agent_name)},dialog_message:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.dialog_messages||=[],r.dialog_messages.push({role:n.role,content:n.content}),n.role===`user`?r.dialog_awaiting_response=!0:n.role===`agent`&&(r.dialog_awaiting_response=!1),z(e.nodes,n.agent_name)},dialog_completed:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.dialog_active=!1,r.dialog_awaiting_response=!1,e.activeDialog=null,e.dialogEngaged=!1,z(e.nodes,n.agent_name)},agent_validator_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`validator-start`,icon:`🔎`,label:`validator`,text:`validating output`,detail:n.criteria_preview||null};if(We(i.nodes,n.agent_name,a),r!=null)Ge(i.nodes,n.agent_name,String(r),a);else{let e=R(i.nodes,n.agent_name);e.validator_state=`running`,e.validator_model=n.model??null,e.validator_attempts=(e.validator_attempts??0)+1}z(i.nodes,n.agent_name)},agent_validator_complete:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=n.errored?`error`:n.passed?`passed`:`failed`,o={type:`validator-complete`,icon:n.errored?`⚠️`:n.passed?`✅`:`❌`,label:`validator`,text:n.errored?`validation error (treated as pass)`:n.passed?`validation passed`:`validation failed`,detail:n.issues&&n.issues.length?n.issues.join(` +`):null};if(We(i.nodes,n.agent_name,o),r!=null)Ge(i.nodes,n.agent_name,String(r),o);else{let e=R(i.nodes,n.agent_name);e.validator_state=a,e.validator_issues=n.issues??[],e.validator_cost_usd=n.cost_usd??null,e.validator_model=n.model??e.validator_model??null}z(i.nodes,n.agent_name)},agent_validation_failed:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=n.rerun_errored===!0,o={type:`validation-failed`,icon:a?`⚠️`:`❌`,label:`validator`,text:a?`re-run failed — keeping original output`:n.will_retry?`re-running once with feedback`:`validation failed (no retry)`,detail:[...n.issues&&n.issues.length?[n.issues.join(` +`)]:[],...a&&n.error?[`cause: ${n.error}`]:[]].join(` +`)||null};if(We(i.nodes,n.agent_name,o),r!=null)Ge(i.nodes,n.agent_name,String(r),o);else{let e=R(i.nodes,n.agent_name);e.validator_will_retry=n.will_retry,e.validator_issues=n.issues??[],a&&(e.validator_state=`error`)}z(i.nodes,n.agent_name)}};function rt(e){return e.item_key==null?String(e.agent_name):`${e.agent_name}[${e.item_key}]`}function it(e){let t=e.timestamp,n=e.data;switch(e.type){case`workflow_started`:return{timestamp:t,level:`info`,source:`workflow`,message:`Workflow "${n.name||``}" started`};case`agent_started`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Agent started${n.iteration==null?``:` (iteration ${n.iteration})`}`};case`agent_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Agent completed${n.elapsed==null?``:` in ${at(n.elapsed)}`}${n.tokens==null?``:` · ${n.tokens.toLocaleString()} tokens`}${n.cost_usd==null?``:` · $${n.cost_usd.toFixed(4)}`}`};case`agent_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Agent failed: ${n.message||n.error_type||`unknown error`}`};case`script_started`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Script started`};case`script_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Script completed (exit ${n.exit_code??`?`})${n.elapsed==null?``:` in ${at(n.elapsed)}`}`};case`script_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Script failed: ${n.message||n.error_type||`unknown error`}`};case`mcp_started`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`MCP tool started: ${n.server}/${n.tool}`};case`mcp_completed`:return{timestamp:t,level:n.is_error?`warning`:`success`,source:String(n.agent_name),message:`MCP tool completed: ${n.server}/${n.tool}${n.elapsed==null?``:` in ${at(n.elapsed)}`}`};case`mcp_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`MCP tool failed: ${n.server}/${n.tool} — ${n.message||n.error_type||`unknown error`}`};case`wait_started`:{let e=n.duration_seconds,r=n.reason,i=typeof e==`number`?at(e):`?`;return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Waiting ${i}${r?` — ${r}`:``}`}}case`wait_completed`:{let e=n.waited_seconds,r=n.interrupted;return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Wait completed${e==null?``:` (${at(e)})`}${r?` — interrupted`:``}`}}case`wait_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Wait failed: ${n.message||n.error_type||`unknown error`}`};case`set_started`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Set started`};case`set_completed`:{let e=n.output_keys??[],r=e.length>0?` · ${e.join(`, `)}`:``;return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Set completed${r}${n.elapsed==null?``:` in ${at(n.elapsed)}`}`}}case`set_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Set failed: ${n.message||n.error_type||`unknown error`}`};case`gate_presented`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Waiting for human input…`};case`gate_resolved`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Gate resolved → ${n.selected_option||`continue`}`};case`questions_presented`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Asking ${n.total} question(s)…`};case`questions_answered`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`${n.skipped?`Skipped`:`Answered`} ${n.question_id} (${n.cursor+1}/${n.total})`};case`questions_answer_rejected`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:String(n.reason)};case`questions_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Questions ${n.outcome} — ${n.answered_count} answered, ${n.skipped_count} skipped`};case`route_taken`:return{timestamp:t,level:`debug`,source:`router`,message:`${n.from_agent} → ${n.to_agent}`};case`parallel_started`:return{timestamp:t,level:`info`,source:String(n.group_name),message:`Parallel group started (${n.agents?.length||`?`} agents)`};case`parallel_completed`:return{timestamp:t,level:n.failure_count===0?`success`:`error`,source:String(n.group_name),message:`Parallel group completed${n.failure_count>0?` with ${n.failure_count} failure(s)`:``}`};case`for_each_started`:return{timestamp:t,level:`info`,source:String(n.group_name),message:`For-each started (${n.item_count} items)`};case`for_each_completed`:return{timestamp:t,level:(n.failure_count??0)===0?`success`:`error`,source:String(n.group_name),message:`For-each completed · ${n.success_count} succeeded${n.failure_count>0?` · ${n.failure_count} failed`:``}`};case`workflow_completed`:return{timestamp:t,level:`success`,source:`workflow`,message:`Workflow completed${n.elapsed==null?``:` in ${at(n.elapsed)}`}`};case`workflow_failed`:return{timestamp:t,level:`error`,source:`workflow`,message:`Workflow failed: ${n.message||n.error_type||`unknown error`}`};case`budget_exceeded`:{let e=n.spent_usd??0,r=n.budget_usd??0,i=String(n.budget_mode??`audit`),a=n.current_agent?` at ${n.current_agent}`:``;return{timestamp:t,level:i===`enforce`?`error`:`warning`,source:`workflow`,message:`Budget exceeded — $${e.toFixed(2)} of $${r.toFixed(2)} (${i})${a}`}}case`checkpoint_saved`:return{timestamp:t,level:`info`,source:`workflow`,message:`Checkpoint saved: ${n.path?.split(`/`).pop()||`unknown`}`};case`agent_paused`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Agent paused — waiting for resume`};case`agent_resumed`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:n.with_guidance?`Agent resumed with guidance — re-executing`:`Agent resumed — re-executing`};case`guidance_received`:return{timestamp:t,level:`info`,source:`guidance`,message:`Guidance received (pending: ${n.pending}): ${n.text}`};case`guidance_applied`:return{timestamp:t,level:`info`,source:n.agent_name||`workflow`,message:`Guidance applied (${n.source}): ${n.text}`};case`iteration_limit_reached`:{let e=n.agent_name??n.group_name??`workflow`,r=n.skip_gates?` — auto-stopping (--skip-gates)`:` — awaiting decision`;return{timestamp:t,level:`warning`,source:String(e),message:`Iteration limit reached (${n.current_iteration}/${n.max_iterations})${r}`}}case`iteration_limit_resolved`:{let e=n.agent_name??n.group_name??`workflow`,r=!!n.continue_execution,i=n.additional_iterations??0;return{timestamp:t,level:r?`info`:`warning`,source:String(e),message:r?`Iteration limit resolved — continuing with ${i} more`:`Iteration limit resolved — stopping workflow`}}case`dialog_started`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Dialog started — waiting for user…`};case`dialog_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Dialog completed (${n.turn_count||0} messages)`};case`agent_validator_start`:return{timestamp:t,level:`info`,source:rt(n),message:`Validating output…`};case`agent_validator_complete`:{let e=rt(n);if(n.errored)return{timestamp:t,level:`warning`,source:e,message:`Validator error — treated as pass`};if(n.passed)return{timestamp:t,level:`success`,source:e,message:`Validation passed`};let r=Array.isArray(n.issues)?n.issues.length:0;return{timestamp:t,level:`warning`,source:e,message:`Validation failed (${r} issue${r===1?``:`s`})`}}case`agent_validation_failed`:{let e=rt(n);return n.rerun_errored?{timestamp:t,level:`error`,source:e,message:`Validation re-run failed — keeping original output`}:{timestamp:t,level:`warning`,source:e,message:`Validation failed — ${n.will_retry?`re-running once with feedback`:`no retry`}`}}default:return null}}function at(e){return e<1?`${(e*1e3).toFixed(0)}ms`:e<60?`${e.toFixed(1)}s`:`${Math.floor(e/60)}m ${(e%60).toFixed(0)}s`}function ot(e){let t=e.timestamp,n=e.data;switch(e.type){case`agent_started`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Agent started${n.iteration==null?``:` (iteration ${n.iteration})`}`};case`agent_prompt_rendered`:return{timestamp:t,source:String(n.agent_name),type:`prompt`,message:`Prompt rendered`,detail:st(String(n.rendered_prompt||``),500)};case`agent_reasoning`:return{timestamp:t,source:String(n.agent_name),type:`reasoning`,message:String(n.content||``)};case`agent_tool_start`:return{timestamp:t,source:String(n.agent_name),type:`tool-start`,message:`→ ${n.tool_name}`,detail:n.arguments?st(String(n.arguments),300):null};case`agent_tool_complete`:return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`← ${n.tool_name||`done`}`,detail:n.result?st(String(n.result),300):null};case`agent_compaction_config`:return n.enabled===!1?{timestamp:t,source:String(n.agent_name),type:`compaction-config`,message:`⚙ compaction disabled${n.disabled_reason?`: ${n.disabled_reason}`:``}`}:{timestamp:t,source:String(n.agent_name),type:`compaction-config`,message:`⚙ compaction armed (window ${n.context_window} from ${n.context_window_source}, output limit ${n.output_limit} from ${n.output_limit_source}, trigger ${n.trigger_tokens??`?`}, target ${n.target_tokens??`?`})`};case`agent_compaction_start`:return{timestamp:t,source:String(n.agent_name),type:`compaction-start`,message:`🧹 compacting context (${n.tokens_before??`?`} tokens, window ${n.context_window} from ${n.context_window_source})`};case`agent_compaction_complete`:if(n.errored)return{timestamp:t,source:String(n.agent_name),type:`compaction-error`,message:`⚠️ compaction failed — ${n.error_type||`Error`}: ${n.message||`unknown`}`};if(n.still_over_trigger||Array.isArray(n.degraded_tiers)&&n.degraded_tiers.length>0){let e=[...Array.isArray(n.degraded_tiers)&&n.degraded_tiers.length>0?[`degraded tiers: ${n.degraded_tiers.join(`, `)}`]:[],...n.still_over_trigger?[`still over trigger`]:[]];return{timestamp:t,source:String(n.agent_name),type:`compaction-error`,message:`⚠️ context compacted with warnings: ${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${e.join(`; `)})`}}return{timestamp:t,source:String(n.agent_name),type:`compaction-complete`,message:`🧹 context compacted: ${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${n.messages_before??`?`} → ${n.messages_after??`?`} messages, ${n.elapsed==null?`?`:at(n.elapsed)}${typeof n.tokens_saved==`number`?`, saved ${n.tokens_saved} tokens`:``})`};case`agent_tool_output_truncated`:return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`✂ ${n.tool_name||`tool`} truncated`,detail:`${n.original_chars}→${n.kept_chars} chars${n.spill_path?` · full: `+n.spill_path:``}`};case`agent_parse_recovery`:return{timestamp:t,source:String(n.agent_name),type:`parse-recovery`,message:`↻ retrying output — ${n.reason===`schema`?`output schema mismatch`:`invalid JSON`} (${n.attempt??`?`}/${n.max_attempts??`?`})`,detail:n.error?st(String(n.error),300):null};case`agent_turn_start`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Turn ${n.turn??`?`}`};case`agent_message`:return{timestamp:t,source:String(n.agent_name),type:`message`,message:st(String(n.content||``),500)};case`agent_completed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Completed${n.elapsed==null?``:` in ${at(n.elapsed)}`}${n.tokens==null?``:` · ${n.tokens.toLocaleString()} tokens`}`};case`agent_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Failed: ${n.message||n.error_type||`unknown`}`};case`script_started`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Script started`};case`script_completed`:return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`Script completed (exit ${n.exit_code??`?`})`,detail:n.stdout?st(String(n.stdout),300):null};case`script_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Script failed: ${n.message||n.error_type||`unknown`}`};case`mcp_started`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`MCP tool started: ${n.server}/${n.tool}`};case`mcp_completed`:return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`MCP tool completed: ${n.server}/${n.tool}${n.is_error?` (error)`:``}`,detail:n.result_bytes?`${n.result_bytes} bytes${n.truncated?` (truncated)`:``}`:null};case`mcp_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`MCP tool failed: ${n.server}/${n.tool} — ${n.message||n.error_type||`unknown`}`};case`wait_started`:{let e=n.duration_seconds,r=n.reason,i=typeof e==`number`?at(e):`?`;return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Waiting ${i}${r?` — ${r}`:``}`}}case`wait_completed`:{let e=n.waited_seconds,r=n.interrupted;return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`Wait completed${e==null?``:` (${at(e)})`}${r?` — interrupted`:``}`}}case`wait_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Wait failed: ${n.message||n.error_type||`unknown`}`};case`set_started`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Set started`};case`set_completed`:{let e=n.output_keys??[],r=e.length>0?` (${e.join(`, `)})`:``;return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`Set completed${r}`,detail:n.value_repr?st(String(n.value_repr),300):null}}case`set_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Set failed: ${n.message||n.error_type||`unknown`}`};default:return null}}function st(e,t){return e.length<=t?e:e.slice(0,t)+`…`}var ct=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),H=o(((e,t)=>{t.exports=ct()}))();function lt(e){let t=e.match(/^(\s*)/);return t?t[1].length:0}function ut(e){let t=new Map;for(let n=0;ni)a=t;else break}a>n&&t.set(n,a)}return t}function dt(e){if(/^\s*#/.test(e))return(0,H.jsx)(`span`,{className:`text-emerald-500/70`,children:e});let t=e.match(/^(\s*)(- )?([a-zA-Z_][\w.-]*)(:\s*)(.*)/);if(t){let[,e,n,r,i,a]=t;return(0,H.jsxs)(`span`,{children:[e,n??``,(0,H.jsx)(`span`,{className:`text-sky-400`,children:r}),(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:i}),ft(a??``)]})}let n=e.match(/^(\s*)(- )(.*)/);if(n){let[,e,t,r]=n;return(0,H.jsxs)(`span`,{children:[e,(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:t}),ft(r??``)]})}return(0,H.jsx)(`span`,{children:e})}function ft(e){if(!e)return``;let t=e.indexOf(` #`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t):``,i=n;return/^(true|false|null|yes|no)$/i.test(n.trim())||/^\d+(\.\d+)?$/.test(n.trim())?i=(0,H.jsx)(`span`,{className:`text-amber-400`,children:n}):/^["'].*["']$/.test(n.trim())?i=(0,H.jsx)(`span`,{className:`text-green-400`,children:n}):(n.includes(`|`)||n.includes(`>`))&&(i=(0,H.jsx)(`span`,{className:`text-[var(--text-secondary)]`,children:n})),(0,H.jsxs)(H.Fragment,{children:[i,r&&(0,H.jsx)(`span`,{className:`text-emerald-500/70`,children:r})]})}function pt({yaml:e,onClose:t}){let[n,r]=(0,v.useState)(new Set);(0,v.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let i=(0,v.useMemo)(()=>e.split(` +`),[e]),a=(0,v.useMemo)(()=>ut(i),[i]),o=(0,v.useCallback)(e=>{r(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),s=(0,v.useMemo)(()=>{let e=[],t=-1;for(let r=0;r(0,H.jsxs)(`div`,{className:`flex`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center justify-center flex-shrink-0`,style:{width:`1.25rem`},children:n?(0,H.jsx)(`button`,{onClick:()=>o(e),className:`text-[var(--text-muted)] hover:text-[var(--text)] p-0 leading-none`,style:{background:`none`,border:`none`,cursor:`pointer`},children:r?(0,H.jsx)(N,{className:`w-3 h-3`}):(0,H.jsx)(M,{className:`w-3 h-3`})}):null}),(0,H.jsxs)(`span`,{className:`flex-1`,children:[dt(t),r&&(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] text-[11px] ml-2 px-1.5 py-0.5 rounded bg-[var(--surface-hover)] cursor-pointer`,onClick:()=>o(e),children:`···`})]})]},e))})})]})]})}function mt({onClose:e}){let t=B(e=>e.isPaused),n=B(e=>e.wsStatus),r=B(e=>e.userGuidance),i=B(e=>e.sendGuidance),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(null),d=n===`connected`&&!s,f=a.trim(),p=!d||f.length===0,m=async()=>{if(p)return;c(!0),u(null);let e=await i(f);c(!1),e.ok?o(``):u(e.error)};return(0,v.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]),(0,H.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`guidance-title`,"data-testid":`guidance-modal`,className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm`,onClick:e,children:(0,H.jsxs)(`div`,{className:`relative flex flex-col w-[90vw] max-w-lg rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-2xl overflow-hidden`,onClick:e=>e.stopPropagation(),children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2.5 px-4 py-3 border-b border-[var(--border)] bg-[var(--surface-raised)]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,H.jsx)(ge,{className:`w-4 h-4 text-sky-400 flex-shrink-0`}),(0,H.jsx)(`h2`,{id:`guidance-title`,className:`text-sm font-semibold text-[var(--text)]`,children:`Guide this run`})]}),(0,H.jsx)(`button`,{type:`button`,onClick:e,className:`p-1 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,"aria-label":`Close`,children:(0,H.jsx)(Me,{className:`w-4 h-4`})})]}),(0,H.jsxs)(`div`,{className:`px-4 py-4 space-y-3`,children:[(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Applied at the next step boundary, or immediately if an agent is currently paused.`}),(0,H.jsx)(`textarea`,{"data-testid":`guidance-textarea`,value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),m())},disabled:!d,autoFocus:!0,rows:3,placeholder:`e.g. Prefer Python 3.12 examples`,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-sky-400 transition-colors disabled:opacity-50 resize-none`}),l&&(0,H.jsx)(`div`,{className:`text-[11px] text-red-300`,role:`alert`,children:l}),n!==`connected`&&(0,H.jsx)(`div`,{className:`text-[11px] text-red-300`,children:`Disconnected from server — reconnect to send guidance.`}),r.length>0&&(0,H.jsxs)(`div`,{className:`space-y-1 max-h-40 overflow-y-auto`,children:[(0,H.jsx)(`h3`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Guidance this run`}),(0,H.jsx)(`ul`,{className:`space-y-1`,children:r.map((e,t)=>(0,H.jsxs)(`li`,{className:`flex items-start gap-1.5 text-[11px] text-[var(--text-secondary)]`,children:[(0,H.jsx)(`span`,{"data-testid":`guidance-entry-marker`,className:e.applied?`text-emerald-400`:`text-amber-400`,children:e.applied?`✓`:`…`}),(0,H.jsx)(`span`,{children:e.text})]},`${t}-${e.text}`))})]})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-2 px-4 py-3 border-t border-[var(--border)] bg-[var(--surface-raised)]`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:e,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg border border-[var(--border)] text-[var(--text)] hover:bg-[var(--surface-hover)] transition-colors`,children:`Close`}),(0,H.jsxs)(`button`,{type:`button`,"data-testid":`guidance-send`,onClick:()=>void m(),disabled:p,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg bg-sky-500 text-white hover:bg-sky-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium`,children:[(0,H.jsx)(Se,{className:`w-3.5 h-3.5`}),s?`Sending…`:t?`Send & resume`:`Send`]})]})]})})}function ht(){let e=B(e=>e.workflowName),t=B(e=>e.workflowStatus),n=B(e=>e.isPaused),r=B(e=>e.workflowYaml),i=B(e=>e.conductorVersion),a=B(e=>e.replayMode),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(!1),[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(!1),[m,h]=(0,v.useState)(!1),[g,_]=(0,v.useState)(null),y=!a&&n,b=!a&&!n&&(t===`running`||t===`pending`);(0,v.useEffect)(()=>{n||(s(!1),l(!1),d(!1))},[n]);let x=async(e,t,n)=>{n(!0),_(null);try{let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`,...He()}});if(n.ok)return;console.error(`Failed to ${t}: HTTP ${n.status} from ${e}`),_(`Could not ${t} — server returned HTTP ${n.status}.`)}catch(e){console.error(`Failed to ${t}:`,e),_(`Could not ${t} — the dashboard is unreachable.`)}n(!1)};return(0,H.jsxs)(`header`,{className:`flex items-center justify-between px-4 py-2 bg-[var(--surface)] border-b border-[var(--border)] flex-shrink-0`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(T,{className:`w-4 h-4 text-[var(--running)]`}),(0,H.jsx)(`h1`,{className:`text-sm font-semibold text-[var(--text)]`,children:`Conductor`}),e&&(0,H.jsxs)(`span`,{className:`text-sm text-[var(--text-muted)] font-normal`,children:[`— `,e]})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[g&&(0,H.jsx)(`span`,{className:`text-xs text-red-400`,role:`alert`,children:g}),y&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{onClick:()=>x(`/api/resume`,`resume the agent`,l),disabled:c,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded + bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 + hover:bg-emerald-500/20 hover:border-emerald-500/30 + disabled:opacity-50 disabled:cursor-not-allowed + transition-colors`,title:`Re-execute the paused agent`,children:[(0,H.jsx)(ye,{className:`w-3 h-3`}),c?`Resuming...`:`Resume`]}),(0,H.jsxs)(`button`,{onClick:()=>x(`/api/kill`,`kill the workflow`,d),disabled:u,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded + bg-red-500/10 text-red-400 border border-red-500/20 + hover:bg-red-500/20 hover:border-red-500/30 + disabled:opacity-50 disabled:cursor-not-allowed + transition-colors`,title:`Stop the workflow and save a checkpoint for CLI resume`,children:[(0,H.jsx)(Me,{className:`w-3 h-3`}),u?`Killing...`:`Kill`]})]}),b&&(0,H.jsxs)(`button`,{onClick:()=>x(`/api/stop`,`stop the agent`,s),disabled:o,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded + bg-red-500/10 text-red-400 border border-red-500/20 + hover:bg-red-500/20 hover:border-red-500/30 + disabled:opacity-50 disabled:cursor-not-allowed + transition-colors`,title:`Pause the current agent, then choose Resume or Kill`,children:[(0,H.jsx)(Ee,{className:`w-3 h-3`}),o?`Stopping...`:`Stop`]}),r&&(0,H.jsxs)(`button`,{onClick:()=>p(!0),className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded + bg-[var(--surface-hover)] text-[var(--text-secondary)] border border-[var(--border)] + hover:text-[var(--text)] hover:bg-[var(--surface)] + transition-colors`,title:`View workflow YAML configuration`,children:[(0,H.jsx)(oe,{className:`w-3 h-3`}),`YAML`]}),!a&&(0,H.jsxs)(`button`,{onClick:()=>h(!0),className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded + bg-[var(--surface-hover)] text-[var(--text-secondary)] border border-[var(--border)] + hover:text-[var(--text)] hover:bg-[var(--surface)] + transition-colors`,title:`Send mid-run guidance to the workflow`,children:[(0,H.jsx)(ge,{className:`w-3 h-3`}),`Guide`]}),(0,H.jsxs)(`a`,{href:`/api/logs`,download:`conductor-logs.json`,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded + bg-[var(--surface-hover)] text-[var(--text-secondary)] border border-[var(--border)] + hover:text-[var(--text)] hover:bg-[var(--surface)] + transition-colors`,title:`Download full event log as JSON`,children:[(0,H.jsx)(I,{className:`w-3 h-3`}),`Logs`]}),(0,H.jsxs)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:[`v`,i??`—`]})]}),f&&r&&(0,H.jsx)(pt,{yaml:r,onClose:()=>p(!1)}),m&&(0,H.jsx)(mt,{onClose:()=>h(!1)})]})}function gt(){let e=B(e=>e.getBreadcrumbs),t=B(e=>e.navigateToContext),n=B(e=>e.viewContextPath);if(B(e=>e.subworkflowContexts).length===0&&n.length===0)return null;let r=e();return(0,H.jsxs)(`div`,{className:`flex items-center gap-1 px-4 py-1.5 bg-[var(--surface)] border-b border-[var(--border)] text-xs flex-shrink-0`,children:[(0,H.jsx)(de,{className:`w-3 h-3 text-[var(--text-muted)] mr-1`}),r.map((e,i)=>{let a=i===r.length-1,o=JSON.stringify(e.path)===JSON.stringify(n);return(0,H.jsxs)(`span`,{className:`flex items-center gap-1`,children:[i>0&&(0,H.jsx)(N,{className:`w-3 h-3 text-[var(--text-muted)]`}),a?(0,H.jsx)(`span`,{className:`font-semibold text-[var(--text)]`,children:e.label}):(0,H.jsx)(`button`,{onClick:()=>t(e.path),className:`hover:text-[var(--running)] transition-colors ${o?`text-[var(--text)] font-medium`:`text-[var(--text-muted)]`}`,children:e.label})]},i)})]})}function U(...e){return e.filter(Boolean).join(` `)}function W(e){return e==null?``:e<60?`${e.toFixed(1)}s`:`${Math.floor(e/60)}m ${(e%60).toFixed(0)}s`}function _t(e){return e==null?``:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:`${e}`}function vt(e){return e==null?``:`$${e.toFixed(4)}`}function yt(e){return e==null?``:typeof e==`string`?e:JSON.stringify(e,null,2)}function bt(e,t){if(t<=0)return`${e.toLocaleString()} tokens (limit unknown)`;let n=e=>e.toLocaleString(),r=(e/t*100).toFixed(1);return`${n(e)} / ${n(t)} (${r}%)`}function xt(){let e=B(e=>e.workflowStatus),t=B(e=>e.workflowStartTime),n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`—`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t!=null){if(n){o.current&&=(clearInterval(o.current),null),a(W((r??t)-t));return}if(e===`running`){let e=()=>{a(W(Date.now()/1e3-t))};return e(),o.current=setInterval(e,500),()=>{o.current&&clearInterval(o.current)}}else (e===`completed`||e===`failed`)&&(o.current&&=(clearInterval(o.current),null))}},[e,t,n,r]),i}function St(){let e=B(e=>e.workflowStatus),t=B(e=>e.agentsCompleted),n=B(e=>e.agentsTotal),r=B(e=>e.totalCost),i=B(e=>e.totalTokens),a=B(e=>e.unpricedCount),o=B(e=>e.wsStatus),s=B(e=>e.workflowFailure),c=B(e=>e.lastEventTime),l=B(e=>e.iterationLimitGate),u=xt(),[d,f]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(e!==`running`||c==null){f(null);return}let t=()=>{f(Math.floor(Date.now()/1e3-c))};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[e,c]);let p=e===`failed`,m=(()=>{if(l&&e===`running`){let e=l.agent_name??l.group_name??`workflow`,t=l.skip_gates?` — auto-stopping`:` — awaiting decision`;return`Iteration limit reached: ${e} ${l.current_iteration}/${l.max_iterations}${t}`}switch(e){case`pending`:return`Waiting for workflow…`;case`running`:return`Running`;case`completed`:return`Completed`;case`failed`:{if(!s)return`Failed`;let e=s.error_type||``;return e===`MaxIterationsError`?`Failed: exceeded maximum iterations`:e===`TimeoutError`?`Failed: workflow timed out`:s.message?`Failed: ${s.message.length>60?s.message.slice(0,57)+`...`:s.message}`:`Failed: ${e}`}}})(),h=l!=null&&e===`running`,g=h?`bg-[var(--waiting)] animate-pulse`:{pending:`bg-[var(--pending)]`,running:`bg-[var(--running)] animate-pulse`,completed:`bg-[var(--completed)]`,failed:`bg-[var(--failed)]`}[e],_=(()=>{switch(o){case`connected`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--completed)]`,children:[(0,H.jsx)(je,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Connected`})]});case`disconnected`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--failed)]`,children:[(0,H.jsx)(Ae,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Disconnected`})]});case`reconnecting`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--waiting)]`,children:[(0,H.jsx)(pe,{className:`w-3 h-3 animate-spin`}),(0,H.jsx)(`span`,{children:`Reconnecting\\u2026`})]});case`connecting`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--text-muted)]`,children:[(0,H.jsx)(pe,{className:`w-3 h-3 animate-spin`}),(0,H.jsx)(`span`,{children:`Connecting\\u2026`})]})}})();return(0,H.jsxs)(`footer`,{className:U(`flex items-center gap-4 px-4 py-1.5 border-t text-xs flex-shrink-0 transition-colors duration-300`,p?`bg-red-950/50 border-red-500/30`:h?`bg-amber-950/30 border-amber-500/30`:`bg-[var(--surface)] border-[var(--border)]`),children:[(0,H.jsx)(`span`,{className:U(`w-2 h-2 rounded-full flex-shrink-0`,g)}),(0,H.jsx)(`span`,{className:U(p?`text-red-300`:h?`text-amber-200`:`text-[var(--text)]`),children:m}),n>0&&(0,H.jsxs)(`span`,{className:U(p?`text-red-400/60`:`text-[var(--text-muted)]`),children:[t,`/`,n,` agents`]}),e!==`pending`&&(0,H.jsx)(`span`,{className:U(`font-mono`,p?`text-red-400/60`:`text-[var(--text-muted)]`),children:u}),i>0&&(0,H.jsxs)(`span`,{className:U(`flex items-center gap-1`,p?`text-red-400/60`:`text-[var(--text-muted)]`),title:`Total tokens used`,children:[(0,H.jsx)(ue,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{className:`font-mono`,children:i.toLocaleString()})]}),(r>0||a>0)&&(0,H.jsxs)(`span`,{className:U(`flex items-center gap-1`,p?`text-red-400/60`:`text-[var(--text-muted)]`),title:a>0?`Total cost (partial \u2014 ${a} agent${a===1?``:`s`} with no available pricing)`:`Total cost`,children:[(0,H.jsx)(ie,{className:`w-3 h-3`}),r>0&&(0,H.jsxs)(`span`,{className:`font-mono`,children:[a>0?`~`:``,`$`,r.toFixed(4)]}),a>0&&(0,H.jsx)(`span`,{className:`text-amber-400`,children:r>0?`(${a} unpriced)`:`${a} unpriced`})]}),d!=null&&d>=5&&(0,H.jsxs)(`span`,{className:U(`flex items-center gap-1 font-mono`,d>=60?`text-amber-400`:`text-[var(--text-muted)]`),title:`Time since last event from the provider`,children:[(0,H.jsx)(re,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:d>=60?`${Math.floor(d/60)}m ${d%60}s idle`:`${d}s idle`})]}),(0,H.jsx)(`span`,{className:`flex-1`}),_]})}var Ct=[1,5,10,20,50];function wt(e,t){if(t===0||e.length===0)return`+0.0s`;let n=e[0].timestamp,r=e[Math.min(t,e.length)-1].timestamp-n;return r<60?`+${r.toFixed(1)}s`:`+${Math.floor(r/60)}m${(r%60).toFixed(0)}s`}function Tt(){let e=B(e=>e.replayPosition),t=B(e=>e.replayTotalEvents),n=B(e=>e.replayPlaying),r=B(e=>e.replaySpeed),i=B(e=>e.replayEvents),a=B(e=>e.setReplayPosition),o=B(e=>e.setReplayPlaying),s=B(e=>e.setReplaySpeed),c=e=>{a(parseInt(e.target.value,10)),n&&o(!1)},l=()=>{!n&&e>=t&&a(0),o(!n)},u=t>0?e/t*100:0;return(0,H.jsxs)(`footer`,{className:`flex items-center gap-3 px-4 py-1.5 border-t bg-[var(--surface)] border-[var(--border)] text-xs flex-shrink-0`,children:[(0,H.jsx)(`button`,{onClick:l,className:`flex items-center justify-center w-6 h-6 rounded hover:bg-[var(--surface-hover)] text-[var(--text-secondary)] hover:text-[var(--text)] transition-colors`,title:n?`Pause`:`Play`,children:n?(0,H.jsx)(ve,{className:`w-3.5 h-3.5`}):(0,H.jsx)(ye,{className:`w-3.5 h-3.5`})}),(0,H.jsxs)(`div`,{className:`flex-1 relative flex items-center`,children:[(0,H.jsx)(`input`,{type:`range`,min:0,max:t,value:e,onChange:c,className:`w-full h-1 appearance-none rounded-full cursor-pointer`,style:{background:`linear-gradient(to right, var(--accent) 0%, var(--accent) ${u}%, var(--border) ${u}%, var(--border) 100%)`,WebkitAppearance:`none`}}),(0,H.jsx)(`style`,{children:` + footer input[type="range"]::-webkit-slider-thumb { + -webkit-appearance: none; + width: 12px; + height: 12px; + border-radius: 50%; + background: var(--accent); + border: 2px solid var(--surface); + cursor: pointer; + box-shadow: 0 0 4px rgba(99, 102, 241, 0.4); + } + footer input[type="range"]::-moz-range-thumb { + width: 12px; + height: 12px; + border-radius: 50%; + background: var(--accent); + border: 2px solid var(--surface); + cursor: pointer; + box-shadow: 0 0 4px rgba(99, 102, 241, 0.4); + } + `})]}),(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] font-mono whitespace-nowrap`,children:wt(i,e)}),(0,H.jsxs)(`span`,{className:`text-[var(--text-muted)] font-mono whitespace-nowrap`,children:[`Event `,e,`/`,t]}),(0,H.jsx)(`div`,{className:`flex items-center gap-0.5`,children:Ct.map(e=>(0,H.jsxs)(`button`,{onClick:()=>s(e),className:U(`px-1.5 py-0.5 rounded text-xs font-mono transition-colors`,r===e?`bg-[var(--accent)] text-white`:`text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]`),children:[e,`×`]},e))})]})}var Et=(0,v.createContext)(null);Et.displayName=`PanelGroupContext`;var Dt={group:`data-panel-group`,groupDirection:`data-panel-group-direction`,groupId:`data-panel-group-id`,panel:`data-panel`,panelCollapsible:`data-panel-collapsible`,panelId:`data-panel-id`,panelSize:`data-panel-size`,resizeHandle:`data-resize-handle`,resizeHandleActive:`data-resize-handle-active`,resizeHandleEnabled:`data-panel-resize-handle-enabled`,resizeHandleId:`data-panel-resize-handle-id`,resizeHandleState:`data-resize-handle-state`},Ot=10,kt=v.useLayoutEffect,At=v.useId,jt=typeof At==`function`?At:()=>null,Mt=0;function Nt(e=null){let t=jt(),n=(0,v.useRef)(e||t||null);return n.current===null&&(n.current=``+ Mt++),e??n.current}function Pt({children:e,className:t=``,collapsedSize:n,collapsible:r,defaultSize:i,forwardedRef:a,id:o,maxSize:s,minSize:c,onCollapse:l,onExpand:u,onResize:d,order:f,style:p,tagName:m=`div`,...h}){let g=(0,v.useContext)(Et);if(g===null)throw Error(`Panel components must be rendered within a PanelGroup container`);let{collapsePanel:_,expandPanel:y,getPanelSize:b,getPanelStyle:x,groupId:S,isPanelCollapsed:C,reevaluatePanelConstraints:w,registerPanel:T,resizePanel:E,unregisterPanel:D}=g,O=Nt(o),k=(0,v.useRef)({callbacks:{onCollapse:l,onExpand:u,onResize:d},constraints:{collapsedSize:n,collapsible:r,defaultSize:i,maxSize:s,minSize:c},id:O,idIsFromProps:o!==void 0,order:f});(0,v.useRef)({didLogMissingDefaultSizeWarning:!1}),kt(()=>{let{callbacks:e,constraints:t}=k.current,a={...t};k.current.id=O,k.current.idIsFromProps=o!==void 0,k.current.order=f,e.onCollapse=l,e.onExpand=u,e.onResize=d,t.collapsedSize=n,t.collapsible=r,t.defaultSize=i,t.maxSize=s,t.minSize=c,(a.collapsedSize!==t.collapsedSize||a.collapsible!==t.collapsible||a.maxSize!==t.maxSize||a.minSize!==t.minSize)&&w(k.current,a)}),kt(()=>{let e=k.current;return T(e),()=>{D(e)}},[f,O,T,D]),(0,v.useImperativeHandle)(a,()=>({collapse:()=>{_(k.current)},expand:e=>{y(k.current,e)},getId(){return O},getSize(){return b(k.current)},isCollapsed(){return C(k.current)},isExpanded(){return!C(k.current)},resize:e=>{E(k.current,e)}}),[_,y,b,C,O,E]);let A=x(k.current,i);return(0,v.createElement)(m,{...h,children:e,className:t,id:O,style:{...A,...p},[Dt.groupId]:S,[Dt.panel]:``,[Dt.panelCollapsible]:r||void 0,[Dt.panelId]:O,[Dt.panelSize]:parseFloat(``+A.flexGrow).toFixed(1)})}var Ft=(0,v.forwardRef)((e,t)=>(0,v.createElement)(Pt,{...e,forwardedRef:t}));Pt.displayName=`Panel`,Ft.displayName=`forwardRef(Panel)`;var It;function Lt(){return It}var Rt=null,zt=!0,Bt=-1,Vt=null;function Ht(e,t){if(t){let e=(t&on)!==0,n=(t&sn)!==0,r=(t&cn)!==0,i=(t&ln)!==0;if(e)return r?`se-resize`:i?`ne-resize`:`e-resize`;if(n)return r?`sw-resize`:i?`nw-resize`:`w-resize`;if(r)return`s-resize`;if(i)return`n-resize`}switch(e){case`horizontal`:return`ew-resize`;case`intersection`:return`move`;case`vertical`:return`ns-resize`}}function Ut(){Vt!==null&&(document.head.removeChild(Vt),Rt=null,Vt=null,Bt=-1)}function Wt(e,t){if(!zt)return;let n=Ht(e,t);if(Rt!==n){if(Rt=n,Vt===null){Vt=document.createElement(`style`);let e=Lt();e&&Vt.setAttribute(`nonce`,e),document.head.appendChild(Vt)}if(Bt>=0){var r;(r=Vt.sheet)==null||r.removeRule(Bt)}Bt=Vt.sheet?.insertRule(`*{cursor: ${n} !important;}`)??-1}}function Gt(e){return e.type===`keydown`}function Kt(e){return e.type.startsWith(`pointer`)}function qt(e){return e.type.startsWith(`mouse`)}function Jt(e){if(Kt(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(qt(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function Yt(){if(typeof matchMedia==`function`)return matchMedia(`(pointer:coarse)`).matches?`coarse`:`fine`}function Xt(e,t,n){return n?e.xt.x&&e.yt.y:e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function Zt(e,t){if(e===t)throw Error(`Cannot compare node with itself`);let n={a:rn(e),b:rn(t)},r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;G(r,`Stacking order can only be calculated for elements with a common ancestor`);let i={a:nn(tn(n.a)),b:nn(tn(n.b))};if(i.a===i.b){let e=r.childNodes,t={a:n.a.at(-1),b:n.b.at(-1)},i=e.length;for(;i--;){let n=e[i];if(n===t.a)return 1;if(n===t.b)return-1}}return Math.sign(i.a-i.b)}var Qt=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function $t(e){let t=getComputedStyle(an(e)??e).display;return t===`flex`||t===`inline-flex`}function en(e){let t=getComputedStyle(e);return!!(t.position===`fixed`||t.zIndex!==`auto`&&(t.position!==`static`||$t(e))||+t.opacity<1||`transform`in t&&t.transform!==`none`||`webkitTransform`in t&&t.webkitTransform!==`none`||`mixBlendMode`in t&&t.mixBlendMode!==`normal`||`filter`in t&&t.filter!==`none`||`webkitFilter`in t&&t.webkitFilter!==`none`||`isolation`in t&&t.isolation===`isolate`||Qt.test(t.willChange)||t.webkitOverflowScrolling===`touch`)}function tn(e){let t=e.length;for(;t--;){let n=e[t];if(G(n,`Missing node`),en(n))return n}return null}function nn(e){return e&&Number(getComputedStyle(e).zIndex)||0}function rn(e){let t=[];for(;e;)t.push(e),e=an(e);return t}function an(e){let{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}var on=1,sn=2,cn=4,ln=8,un=Yt()===`coarse`,dn=[],fn=!1,pn=new Map,mn=new Map,hn=new Set;function gn(e,t,n,r,i){let{ownerDocument:a}=t,o={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:i},s=pn.get(a)??0;return pn.set(a,s+1),hn.add(o),Tn(),function(){mn.delete(e),hn.delete(o);let t=pn.get(a)??1;if(pn.set(a,t-1),Tn(),t===1&&pn.delete(a),dn.includes(o)){let e=dn.indexOf(o);e>=0&&dn.splice(e,1),Cn(),i(`up`,!0,null)}}}function _n(e){let{target:t}=e,{x:n,y:r}=Jt(e);fn=!0,xn({target:t,x:n,y:r}),Tn(),dn.length>0&&(En(`down`,e),e.preventDefault(),bn(t)||e.stopImmediatePropagation())}function vn(e){let{x:t,y:n}=Jt(e);if(fn&&e.buttons===0&&(fn=!1,En(`up`,e)),!fn){let{target:r}=e;xn({target:r,x:t,y:n})}En(`move`,e),Cn(),dn.length>0&&e.preventDefault()}function yn(e){let{target:t}=e,{x:n,y:r}=Jt(e);mn.clear(),fn=!1,dn.length>0&&(e.preventDefault(),bn(t)||e.stopImmediatePropagation()),En(`up`,e),xn({target:t,x:n,y:r}),Cn(),Tn()}function bn(e){let t=e;for(;t;){if(t.hasAttribute(Dt.resizeHandle))return!0;t=t.parentElement}return!1}function xn({target:e,x:t,y:n}){dn.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),hn.forEach(e=>{let{element:i,hitAreaMargins:a}=e,o=i.getBoundingClientRect(),{bottom:s,left:c,right:l,top:u}=o,d=un?a.coarse:a.fine;if(t>=c-d&&t<=l+d&&n>=u-d&&n<=s+d){if(r!==null&&document.contains(r)&&i!==r&&!i.contains(r)&&!r.contains(i)&&Zt(r,i)>0){let e=r,t=!1;for(;e&&!e.contains(i);){if(Xt(e.getBoundingClientRect(),o,!0)){t=!0;break}e=e.parentElement}if(t)return}dn.push(e)}})}function Sn(e,t){mn.set(e,t)}function Cn(){let e=!1,t=!1;dn.forEach(n=>{let{direction:r}=n;r===`horizontal`?e=!0:t=!0});let n=0;mn.forEach(e=>{n|=e}),e&&t?Wt(`intersection`,n):e?Wt(`horizontal`,n):t?Wt(`vertical`,n):Ut()}var wn=new AbortController;function Tn(){wn.abort(),wn=new AbortController;let e={capture:!0,signal:wn.signal};hn.size&&(fn?(dn.length>0&&pn.forEach((t,n)=>{let{body:r}=n;t>0&&(r.addEventListener(`contextmenu`,yn,e),r.addEventListener(`pointerleave`,vn,e),r.addEventListener(`pointermove`,vn,e))}),window.addEventListener(`pointerup`,yn,e),window.addEventListener(`pointercancel`,yn,e)):pn.forEach((t,n)=>{let{body:r}=n;t>0&&(r.addEventListener(`pointerdown`,_n,e),r.addEventListener(`pointermove`,vn,e))}))}function En(e,t){hn.forEach(n=>{let{setResizeHandlerState:r}=n;r(e,dn.includes(n),t)})}function Dn(){let[e,t]=(0,v.useState)(0);return(0,v.useCallback)(()=>t(e=>e+1),[])}function G(e,t){if(!e)throw console.error(t),Error(t)}function On(e,t,n=Ot){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function kn(e,t,n=Ot){return On(e,t,n)===0}function An(e,t,n){return On(e,t,n)===0}function jn(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-t:t)}}}{let r=e<0?s:c,i=n[r];G(i,`No panel constraints found for index ${r}`);let{collapsedSize:a=0,collapsible:o,minSize:l=0}=i;if(o){let n=t[r];if(G(n!=null,`Previous layout not found for panel index ${r}`),An(n,l)){let t=n-a;On(t,Math.abs(e))>0&&(e=e<0?0-t:t)}}}}{let r=e<0?1:-1,i=e<0?c:s,a=0;for(;;){let e=t[i];G(e!=null,`Previous layout not found for panel index ${i}`);let o=Mn({panelConstraints:n,panelIndex:i,size:100})-e;if(a+=o,i+=r,i<0||i>=n.length)break}let o=Math.min(Math.abs(e),Math.abs(a));e=e<0?0-o:o}{let r=e<0?s:c;for(;r>=0&&r=0))break;e<0?r--:r++}}if(jn(i,o))return i;{let r=e<0?c:s,i=t[r];G(i!=null,`Previous layout not found for panel index ${r}`);let a=i+l,u=Mn({panelConstraints:n,panelIndex:r,size:a});if(o[r]=u,!An(u,a)){let t=a-u,r=e<0?c:s;for(;r>=0&&r0?r--:r++}}}return An(o.reduce((e,t)=>t+e,0),100)?o:i}function Pn({layout:e,panelsArray:t,pivotIndices:n}){let r=0,i=100,a=0,o=0,s=n[0];return G(s!=null,`No pivot index found`),t.forEach((e,t)=>{let{constraints:n}=e,{maxSize:c=100,minSize:l=0}=n;t===s?(r=l,i=c):(a+=l,o+=c)}),{valueMax:Math.min(i,100-a),valueMin:Math.max(r,100-o),valueNow:e[s]}}function Fn(e,t=document){return Array.from(t.querySelectorAll(`[${Dt.resizeHandleId}][data-panel-group-id="${e}"]`))}function In(e,t,n=document){return Fn(e,n).findIndex(e=>e.getAttribute(Dt.resizeHandleId)===t)??null}function Ln(e,t,n){let r=In(e,t,n);return r==null?[-1,-1]:[r,r+1]}function Rn(e,t=document){return t instanceof HTMLElement&&t?.dataset?.panelGroupId==e?t:t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`)||null}function zn(e,t=document){return t.querySelector(`[${Dt.resizeHandleId}="${e}"]`)||null}function Bn(e,t,n,r=document){let i=zn(t,r),a=Fn(e,r),o=i?a.indexOf(i):-1;return[n[o]?.id??null,n[o+1]?.id??null]}function Vn({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:i,panelGroupElement:a,setLayout:o}){(0,v.useRef)({didWarnAboutMissingResizeHandle:!1}),kt(()=>{if(!a)return;let e=Fn(n,a);for(let t=0;t{e.forEach((e,t)=>{e.removeAttribute(`aria-controls`),e.removeAttribute(`aria-valuemax`),e.removeAttribute(`aria-valuemin`),e.removeAttribute(`aria-valuenow`)})}},[n,r,i,a]),(0,v.useEffect)(()=>{if(!a)return;let e=t.current;G(e,`Eager values not found`);let{panelDataArray:i}=e;G(Rn(n,a)!=null,`No group found for id "${n}"`);let s=Fn(n,a);G(s,`No resize handles found for group id "${n}"`);let c=s.map(e=>{let t=e.getAttribute(Dt.resizeHandleId);G(t,`Resize handle element has no handle id attribute`);let[s,c]=Bn(n,t,i,a);if(s==null||c==null)return()=>{};let l=e=>{if(!e.defaultPrevented)switch(e.key){case`Enter`:{e.preventDefault();let c=i.findIndex(e=>e.id===s);if(c>=0){let e=i[c];G(e,`No panel data found for index ${c}`);let s=r[c],{collapsedSize:l=0,collapsible:u,minSize:d=0}=e.constraints;if(s!=null&&u){let e=Nn({delta:An(s,l)?d-l:l-s,initialLayout:r,panelConstraints:i.map(e=>e.constraints),pivotIndices:Ln(n,t,a),prevLayout:r,trigger:`keyboard`});r!==e&&o(e)}}break}}};return e.addEventListener(`keydown`,l),()=>{e.removeEventListener(`keydown`,l)}});return()=>{c.forEach(e=>e())}},[a,e,t,n,r,i,o])}function Hn(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.constraints),r=0,i=100;for(let a=0;a{let i=e[r];G(i,`Panel data not found for index ${r}`);let{callbacks:a,constraints:o,id:s}=i,{collapsedSize:c=0,collapsible:l}=o,u=n[s];if(u==null||t!==u){n[s]=t;let{onCollapse:e,onExpand:r,onResize:i}=a;i&&i(t,u),l&&(e||r)&&(r&&(u==null||kn(u,c))&&!kn(t,c)&&r(),e&&(u==null||!kn(u,c))&&kn(t,c)&&e())}})}function Jn(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function Zn(e){try{if(typeof localStorage<`u`)e.getItem=e=>localStorage.getItem(e),e.setItem=(e,t)=>{localStorage.setItem(e,t)};else throw Error(`localStorage not supported in this environment`)}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function Qn(e){return`react-resizable-panels:${e}`}function $n(e){return e.map(e=>{let{constraints:t,id:n,idIsFromProps:r,order:i}=e;return r?n:i?`${i}:${JSON.stringify(t)}`:JSON.stringify(t)}).sort((e,t)=>e.localeCompare(t)).join(`,`)}function er(e,t){try{let n=Qn(e),r=t.getItem(n);if(r){let e=JSON.parse(r);if(typeof e==`object`&&e)return e}}catch{}return null}function tr(e,t,n){return(er(e,n)??{})[$n(t)]??null}function nr(e,t,n,r,i){let a=Qn(e),o=$n(t),s=er(e,i)??{};s[o]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{i.setItem(a,JSON.stringify(s))}catch(e){console.error(e)}}function rr({layout:e,panelConstraints:t}){let n=[...e],r=n.reduce((e,t)=>e+t,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(e=>`${e}%`).join(`, `)}`);if(!An(r,100)&&n.length>0)for(let e=0;e(Zn(ar),ar.getItem(e)),setItem:(e,t)=>{Zn(ar),ar.setItem(e,t)}},or={};function sr({autoSaveId:e=null,children:t,className:n=``,direction:r,forwardedRef:i,id:a=null,onLayout:o=null,keyboardResizeBy:s=null,storage:c=ar,style:l,tagName:u=`div`,...d}){let f=Nt(a),p=(0,v.useRef)(null),[m,h]=(0,v.useState)(null),[g,_]=(0,v.useState)([]),y=Dn(),b=(0,v.useRef)({}),x=(0,v.useRef)(new Map),S=(0,v.useRef)(0),C=(0,v.useRef)({autoSaveId:e,direction:r,dragState:m,id:f,keyboardResizeBy:s,onLayout:o,storage:c}),w=(0,v.useRef)({layout:g,panelDataArray:[],panelDataArrayChanged:!1});(0,v.useRef)({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),(0,v.useImperativeHandle)(i,()=>({getId:()=>C.current.id,getLayout:()=>{let{layout:e}=w.current;return e},setLayout:e=>{let{onLayout:t}=C.current,{layout:n,panelDataArray:r}=w.current,i=rr({layout:e,panelConstraints:r.map(e=>e.constraints)});Hn(n,i)||(_(i),w.current.layout=i,t&&t(i),qn(r,i,b.current))}}),[]),kt(()=>{C.current.autoSaveId=e,C.current.direction=r,C.current.dragState=m,C.current.id=f,C.current.onLayout=o,C.current.storage=c}),Vn({committedValuesRef:C,eagerValuesRef:w,groupId:f,layout:g,panelDataArray:w.current.panelDataArray,setLayout:_,panelGroupElement:p.current}),(0,v.useEffect)(()=>{let{panelDataArray:t}=w.current;if(e){if(g.length===0||g.length!==t.length)return;let n=or[e];n??(n=Xn(nr,ir),or[e]=n);let r=[...t],i=new Map(x.current);n(e,r,i,g,c)}},[e,g,c]),(0,v.useEffect)(()=>{});let T=(0,v.useCallback)(e=>{let{onLayout:t}=C.current,{layout:n,panelDataArray:r}=w.current;if(e.constraints.collapsible){let i=r.map(e=>e.constraints),{collapsedSize:a=0,panelSize:o,pivotIndices:s}=ur(r,e,n);if(G(o!=null,`Panel size not found for panel "${e.id}"`),!kn(o,a)){x.current.set(e.id,o);let c=Nn({delta:lr(r,e)===r.length-1?o-a:a-o,initialLayout:n,panelConstraints:i,pivotIndices:s,prevLayout:n,trigger:`imperative-api`});Jn(n,c)||(_(c),w.current.layout=c,t&&t(c),qn(r,c,b.current))}}},[]),E=(0,v.useCallback)((e,t)=>{let{onLayout:n}=C.current,{layout:r,panelDataArray:i}=w.current;if(e.constraints.collapsible){let a=i.map(e=>e.constraints),{collapsedSize:o=0,panelSize:s=0,minSize:c=0,pivotIndices:l}=ur(i,e,r),u=t??c;if(kn(s,o)){let t=x.current.get(e.id),o=t!=null&&t>=u?t:u,c=Nn({delta:lr(i,e)===i.length-1?s-o:o-s,initialLayout:r,panelConstraints:a,pivotIndices:l,prevLayout:r,trigger:`imperative-api`});Jn(r,c)||(_(c),w.current.layout=c,n&&n(c),qn(i,c,b.current))}}},[]),D=(0,v.useCallback)(e=>{let{layout:t,panelDataArray:n}=w.current,{panelSize:r}=ur(n,e,t);return G(r!=null,`Panel size not found for panel "${e.id}"`),r},[]),O=(0,v.useCallback)((e,t)=>{let{panelDataArray:n}=w.current;return Yn({defaultSize:t,dragState:m,layout:g,panelData:n,panelIndex:lr(n,e)})},[m,g]),k=(0,v.useCallback)(e=>{let{layout:t,panelDataArray:n}=w.current,{collapsedSize:r=0,collapsible:i,panelSize:a}=ur(n,e,t);return G(a!=null,`Panel size not found for panel "${e.id}"`),i===!0&&kn(a,r)},[]),A=(0,v.useCallback)(e=>{let{layout:t,panelDataArray:n}=w.current,{collapsedSize:r=0,collapsible:i,panelSize:a}=ur(n,e,t);return G(a!=null,`Panel size not found for panel "${e.id}"`),!i||On(a,r)>0},[]),j=(0,v.useCallback)(e=>{let{panelDataArray:t}=w.current;t.push(e),t.sort((e,t)=>{let n=e.order,r=t.order;return n==null&&r==null?0:n==null?-1:r==null?1:n-r}),w.current.panelDataArrayChanged=!0,y()},[y]);kt(()=>{if(w.current.panelDataArrayChanged){w.current.panelDataArrayChanged=!1;let{autoSaveId:e,onLayout:t,storage:n}=C.current,{layout:r,panelDataArray:i}=w.current,a=null;if(e){let t=tr(e,i,n);t&&(x.current=new Map(Object.entries(t.expandToSizes)),a=t.layout)}a??=Kn({panelDataArray:i});let o=rr({layout:a,panelConstraints:i.map(e=>e.constraints)});Hn(r,o)||(_(o),w.current.layout=o,t&&t(o),qn(i,o,b.current))}}),kt(()=>{let e=w.current;return()=>{e.layout=[]}},[]);let M=(0,v.useCallback)(e=>{let t=!1,n=p.current;return n&&window.getComputedStyle(n,null).getPropertyValue(`direction`)===`rtl`&&(t=!0),function(n){n.preventDefault();let r=p.current;if(!r)return()=>null;let{direction:i,dragState:a,id:o,keyboardResizeBy:s,onLayout:c}=C.current,{layout:l,panelDataArray:u}=w.current,{initialLayout:d}=a??{},f=Ln(o,e,r),m=Gn(n,e,i,a,s,r),h=i===`horizontal`;h&&t&&(m=-m);let g=u.map(e=>e.constraints),v=Nn({delta:m,initialLayout:d??l,panelConstraints:g,pivotIndices:f,prevLayout:l,trigger:Gt(n)?`keyboard`:`mouse-or-touch`}),y=!Jn(l,v);(Kt(n)||qt(n))&&S.current!=m&&(S.current=m,!y&&m!==0?h?Sn(e,m<0?on:sn):Sn(e,m<0?cn:ln):Sn(e,0)),y&&(_(v),w.current.layout=v,c&&c(v),qn(u,v,b.current))}},[]),N=(0,v.useCallback)((e,t)=>{let{onLayout:n}=C.current,{layout:r,panelDataArray:i}=w.current,a=i.map(e=>e.constraints),{panelSize:o,pivotIndices:s}=ur(i,e,r);G(o!=null,`Panel size not found for panel "${e.id}"`);let c=Nn({delta:lr(i,e)===i.length-1?o-t:t-o,initialLayout:r,panelConstraints:a,pivotIndices:s,prevLayout:r,trigger:`imperative-api`});Jn(r,c)||(_(c),w.current.layout=c,n&&n(c),qn(i,c,b.current))},[]),ee=(0,v.useCallback)((e,t)=>{let{layout:n,panelDataArray:r}=w.current,{collapsedSize:i=0,collapsible:a}=t,{collapsedSize:o=0,collapsible:s,maxSize:c=100,minSize:l=0}=e.constraints,{panelSize:u}=ur(r,e,n);u!=null&&(a&&s&&kn(u,i)?kn(i,o)||N(e,o):uc&&N(e,c))},[N]),te=(0,v.useCallback)((e,t)=>{let{direction:n}=C.current,{layout:r}=w.current;if(!p.current)return;let i=zn(e,p.current);G(i,`Drag handle element not found for id "${e}"`);let a=Un(n,t);h({dragHandleId:e,dragHandleRect:i.getBoundingClientRect(),initialCursorPosition:a,initialLayout:r})},[]),P=(0,v.useCallback)(()=>{h(null)},[]),F=(0,v.useCallback)(e=>{let{panelDataArray:t}=w.current,n=lr(t,e);n>=0&&(t.splice(n,1),delete b.current[e.id],w.current.panelDataArrayChanged=!0,y())},[y]),ne=(0,v.useMemo)(()=>({collapsePanel:T,direction:r,dragState:m,expandPanel:E,getPanelSize:D,getPanelStyle:O,groupId:f,isPanelCollapsed:k,isPanelExpanded:A,reevaluatePanelConstraints:ee,registerPanel:j,registerResizeHandle:M,resizePanel:N,startDragging:te,stopDragging:P,unregisterPanel:F,panelGroupElement:p.current}),[T,m,r,E,D,O,f,k,A,ee,j,M,N,te,P,F]),re={display:`flex`,flexDirection:r===`horizontal`?`row`:`column`,height:`100%`,overflow:`hidden`,width:`100%`};return(0,v.createElement)(Et.Provider,{value:ne},(0,v.createElement)(u,{...d,children:t,className:n,id:a,ref:p,style:{...re,...l},[Dt.group]:``,[Dt.groupDirection]:r,[Dt.groupId]:f}))}var cr=(0,v.forwardRef)((e,t)=>(0,v.createElement)(sr,{...e,forwardedRef:t}));sr.displayName=`PanelGroup`,cr.displayName=`forwardRef(PanelGroup)`;function lr(e,t){return e.findIndex(e=>e===t||e.id===t.id)}function ur(e,t,n){let r=lr(e,t),i=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:i}}function dr({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){(0,v.useEffect)(()=>{if(e||n==null||r==null)return;let i=zn(t,r);if(i==null)return;let a=e=>{if(!e.defaultPrevented)switch(e.key){case`ArrowDown`:case`ArrowLeft`:case`ArrowRight`:case`ArrowUp`:case`End`:case`Home`:e.preventDefault(),n(e);break;case`F6`:{e.preventDefault();let n=i.getAttribute(Dt.groupId);G(n,`No group element found for id "${n}"`);let a=Fn(n,r),o=In(n,t,r);G(o!==null,`No resize element found for id "${t}"`),a[e.shiftKey?o>0?o-1:a.length-1:o+1{i.removeEventListener(`keydown`,a)}},[r,e,t,n])}function fr({children:e=null,className:t=``,disabled:n=!1,hitAreaMargins:r,id:i,onBlur:a,onClick:o,onDragging:s,onFocus:c,onPointerDown:l,onPointerUp:u,style:d={},tabIndex:f=0,tagName:p=`div`,...m}){let h=(0,v.useRef)(null),g=(0,v.useRef)({onClick:o,onDragging:s,onPointerDown:l,onPointerUp:u});(0,v.useEffect)(()=>{g.current.onClick=o,g.current.onDragging=s,g.current.onPointerDown=l,g.current.onPointerUp=u});let _=(0,v.useContext)(Et);if(_===null)throw Error(`PanelResizeHandle components must be rendered within a PanelGroup container`);let{direction:y,groupId:b,registerResizeHandle:x,startDragging:S,stopDragging:C,panelGroupElement:w}=_,T=Nt(i),[E,D]=(0,v.useState)(`inactive`),[O,k]=(0,v.useState)(!1),[A,j]=(0,v.useState)(null),M=(0,v.useRef)({state:E});kt(()=>{M.current.state=E}),(0,v.useEffect)(()=>{if(n)j(null);else{let e=x(T);j(()=>e)}},[n,T,x]);let N=r?.coarse??15,ee=r?.fine??5;(0,v.useEffect)(()=>{if(n||A==null)return;let e=h.current;G(e,`Element ref not attached`);let t=!1;return gn(T,e,y,{coarse:N,fine:ee},(e,n,r)=>{if(!n){D(`inactive`);return}switch(e){case`down`:{D(`drag`),t=!1,G(r,`Expected event to be defined for "down" action`),S(T,r);let{onDragging:e,onPointerDown:n}=g.current;e?.(!0),n?.();break}case`move`:{let{state:e}=M.current;t=!0,e!==`drag`&&D(`hover`),G(r,`Expected event to be defined for "move" action`),A(r);break}case`up`:{D(`hover`),C();let{onClick:e,onDragging:n,onPointerUp:r}=g.current;n?.(!1),r?.(),t||e?.();break}}})},[N,y,n,ee,x,T,A,S,C]),dr({disabled:n,handleId:T,resizeHandler:A,panelGroupElement:w});let te={touchAction:`none`,userSelect:`none`};return(0,v.createElement)(p,{...m,children:e,className:t,id:i,onBlur:()=>{k(!1),a?.()},onFocus:()=>{k(!0),c?.()},ref:h,role:`separator`,style:{...te,...d},tabIndex:f,[Dt.groupDirection]:y,[Dt.groupId]:b,[Dt.resizeHandle]:``,[Dt.resizeHandleActive]:E===`drag`?`pointer`:O?`keyboard`:void 0,[Dt.resizeHandleEnabled]:!n,[Dt.resizeHandleId]:T,[Dt.resizeHandleState]:E})}fr.displayName=`PanelResizeHandle`;function pr(e){if(typeof e==`string`||typeof e==`number`)return``+e;let t=``;if(Array.isArray(e))for(let n=0,r;n{}};function hr(){for(var e=0,t=arguments.length,n={},r;e=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error(`unknown type: `+e);return{type:e,name:n}})}gr.prototype=hr.prototype={constructor:gr,on:function(e,t){var n=this._,r=_r(e+``,n),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var n=Array(i),r=0,i,a;r=0&&(t=e.slice(0,n))!==`xmlns`&&(e=e.slice(n+1)),br.hasOwnProperty(t)?{space:br[t],local:e}:e}function Sr(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===`http://www.w3.org/1999/xhtml`&&t.documentElement.namespaceURI===`http://www.w3.org/1999/xhtml`?t.createElement(e):t.createElementNS(n,e)}}function Cr(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function wr(e){var t=xr(e);return(t.local?Cr:Sr)(t)}function Tr(){}function Er(e){return e==null?Tr:function(){return this.querySelector(e)}}function Dr(e){typeof e!=`function`&&(e=Er(e));for(var t=this._groups,n=t.length,r=Array(n),i=0;i=v&&(v=_+1);!(b=g[v])&&++v=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function ri(e){e||=ii;function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}for(var n=this._groups,r=n.length,i=Array(r),a=0;at?1:e>=t?0:NaN}function ai(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function oi(){return Array.from(this)}function si(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?yi:typeof t==`function`?xi:bi)(e,t,n??``)):Ci(this.node(),e)}function Ci(e,t){return e.style.getPropertyValue(t)||vi(e).getComputedStyle(e,null).getPropertyValue(t)}function wi(e){return function(){delete this[e]}}function Ti(e,t){return function(){this[e]=t}}function Ei(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Di(e,t){return arguments.length>1?this.each((t==null?wi:typeof t==`function`?Ei:Ti)(e,t)):this.node()[e]}function Oi(e){return e.trim().split(/^|\s+/)}function ki(e){return e.classList||new Ai(e)}function Ai(e){this._node=e,this._names=Oi(e.getAttribute(`class`)||``)}Ai.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute(`class`,this._names.join(` `)))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute(`class`,this._names.join(` `)))},contains:function(e){return this._names.indexOf(e)>=0}};function ji(e,t){for(var n=ki(e),r=-1,i=t.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function oa(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n()=>e;function Oa(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:a,x:o,y:s,dx:c,dy:l,dispatch:u}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:s,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:l,enumerable:!0,configurable:!0},_:{value:u}})}Oa.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function ka(e){return!e.ctrlKey&&!e.button}function Aa(){return this.parentNode}function ja(e,t){return t??{x:e.x,y:e.y}}function Ma(){return navigator.maxTouchPoints||`ontouchstart`in this}function Na(){var e=ka,t=Aa,n=ja,r=Ma,i={},a=hr(`start`,`drag`,`end`),o=0,s,c,l,u,d=0;function f(e){e.on(`mousedown.drag`,p).filter(r).on(`touchstart.drag`,g).on(`touchmove.drag`,_,xa).on(`touchend.drag touchcancel.drag`,v).style(`touch-action`,`none`).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}function p(n,r){if(!(u||!e.call(this,n,r))){var i=y(this,t.call(this,n,r),n,r,`mouse`);i&&(va(n.view).on(`mousemove.drag`,m,Sa).on(`mouseup.drag`,h,Sa),Ta(n.view),Ca(n),l=!1,s=n.clientX,c=n.clientY,i(`start`,n))}}function m(e){if(wa(e),!l){var t=e.clientX-s,n=e.clientY-c;l=t*t+n*n>d}i.mouse(`drag`,e)}function h(e){va(e.view).on(`mousemove.drag mouseup.drag`,null),Ea(e.view,l),wa(e),i.mouse(`end`,e)}function g(n,r){if(e.call(this,n,r)){var i=n.changedTouches,a=t.call(this,n,r),o=i.length,s,c;for(s=0;s>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?no(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?no(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Ua.exec(e))?new ao(t[1],t[2],t[3],1):(t=Wa.exec(e))?new ao(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Ga.exec(e))?no(t[1],t[2],t[3],t[4]):(t=Ka.exec(e))?no(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=qa.exec(e))?fo(t[1],t[2]/100,t[3]/100,1):(t=Ja.exec(e))?fo(t[1],t[2]/100,t[3]/100,t[4]):Ya.hasOwnProperty(e)?to(Ya[e]):e===`transparent`?new ao(NaN,NaN,NaN,0):null}function to(e){return new ao(e>>16&255,e>>8&255,e&255,1)}function no(e,t,n,r){return r<=0&&(e=t=n=NaN),new ao(e,t,n,r)}function ro(e){return e instanceof Ia||(e=eo(e)),e?(e=e.rgb(),new ao(e.r,e.g,e.b,e.opacity)):new ao}function io(e,t,n,r){return arguments.length===1?ro(e):new ao(e,t,n,r??1)}function ao(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Pa(ao,io,Fa(Ia,{brighter(e){return e=e==null?Ra:Ra**+e,new ao(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?La:La**+e,new ao(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new ao(lo(this.r),lo(this.g),lo(this.b),co(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:oo,formatHex:oo,formatHex8:K,formatRgb:so,toString:so}));function oo(){return`#${uo(this.r)}${uo(this.g)}${uo(this.b)}`}function K(){return`#${uo(this.r)}${uo(this.g)}${uo(this.b)}${uo((isNaN(this.opacity)?1:this.opacity)*255)}`}function so(){let e=co(this.opacity);return`${e===1?`rgb(`:`rgba(`}${lo(this.r)}, ${lo(this.g)}, ${lo(this.b)}${e===1?`)`:`, ${e})`}`}function co(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function lo(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function uo(e){return e=lo(e),(e<16?`0`:``)+e.toString(16)}function fo(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ho(e,t,n,r)}function po(e){if(e instanceof ho)return new ho(e.h,e.s,e.l,e.opacity);if(e instanceof Ia||(e=eo(e)),!e)return new ho;if(e instanceof ho)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=t===a?(n-r)/s+(n0&&c<1?0:o,new ho(o,s,c,e.opacity)}function mo(e,t,n,r){return arguments.length===1?po(e):new ho(e,t,n,r??1)}function ho(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Pa(ho,mo,Fa(Ia,{brighter(e){return e=e==null?Ra:Ra**+e,new ho(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?La:La**+e,new ho(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new ao(vo(e>=240?e-240:e+120,i,r),vo(e,i,r),vo(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new ho(go(this.h),_o(this.s),_o(this.l),co(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=co(this.opacity);return`${e===1?`hsl(`:`hsla(`}${go(this.h)}, ${_o(this.s)*100}%, ${_o(this.l)*100}%${e===1?`)`:`, ${e})`}`}}));function go(e){return e=(e||0)%360,e<0?e+360:e}function _o(e){return Math.max(0,Math.min(1,e||0))}function vo(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}var yo=e=>()=>e;function bo(e,t){return function(n){return e+n*t}}function xo(e,t,n){return e**=+n,t=t**+n-e,n=1/n,function(r){return(e+r*t)**+n}}function So(e){return(e=+e)==1?Co:function(t,n){return n-t?xo(t,n,e):yo(isNaN(t)?n:t)}}function Co(e,t){var n=t-e;return n?bo(e,n):yo(isNaN(e)?t:e)}var wo=(function e(t){var n=So(t);function r(e,t){var r=n((e=io(e)).r,(t=io(t)).r),i=n(e.g,t.g),a=n(e.b,t.b),o=Co(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=a(t),e.opacity=o(t),e+``}}return r.gamma=e,r})(1);function To(e,t){t||=[];var n=e?Math.min(t.length,e.length):0,r=t.slice(),i;return function(a){for(i=0;in&&(a=t.slice(n,a),s[o]?s[o]+=a:s[++o]=a),(r=r[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,c.push({i:o,x:ko(r,i)})),n=Mo.lastIndex;return n180?t+=360:t-e>180&&(e+=360),a.push({i:n.push(i(n)+`rotate(`,null,r)-2,x:ko(e,t)}))}function s(e,t,n,a){e===t?t&&n.push(i(n)+`skewX(`+t+r):a.push({i:n.push(i(n)+`skewX(`,null,r)-2,x:ko(e,t)})}function c(e,t,n,r,a,o){if(e!==n||t!==r){var s=a.push(i(a)+`scale(`,null,`,`,null,`)`);o.push({i:s-4,x:ko(e,n)},{i:s-2,x:ko(t,r)})}else (n!==1||r!==1)&&a.push(i(a)+`scale(`+n+`,`+r+`)`)}return function(t,n){var r=[],i=[];return t=e(t),n=e(n),a(t.translateX,t.translateY,n.translateX,n.translateY,r,i),o(t.rotate,n.rotate,r,i),s(t.skewX,n.skewX,r,i),c(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,i),t=n=null,function(e){for(var t=-1,n=i.length,a;++t=0&&e._call.call(void 0,t),e=e._next;--Zo}function ps(){is=(rs=os.now())+as,Zo=Qo=0;try{fs()}finally{Zo=0,hs(),is=0}}function ms(){var e=os.now(),t=e-rs;t>es&&(as-=t,rs=e)}function hs(){for(var e,t=ts,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:ts=n);ns=e,gs(r)}function gs(e){Zo||(Qo&&=clearTimeout(Qo),e-is>24?(e<1/0&&(Qo=setTimeout(ps,e-os.now()-as)),$o&&=clearInterval($o)):($o||=(rs=os.now(),setInterval(ms,es)),Zo=1,ss(ps)))}function _s(e,t,n){var r=new us;return t=t==null?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}var vs=hr(`start`,`end`,`cancel`,`interrupt`),ys=[];function bs(e,t,n,r,i,a){var o=e.__transition;if(!o)e.__transition={};else if(n in o)return;ws(e,n,{name:t,index:r,group:i,on:vs,tween:ys,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0})}function xs(e,t){var n=Cs(e,t);if(n.state>0)throw Error(`too late; already scheduled`);return n}function Ss(e,t){var n=Cs(e,t);if(n.state>3)throw Error(`too late; already running`);return n}function Cs(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error(`transition not found`);return n}function ws(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=ds(a,0,n.time);function a(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}function o(a){var l,u,d,f;if(n.state!==1)return c();for(l in r)if(f=r[l],f.name===n.name){if(f.state===3)return _s(o);f.state===4?(f.state=6,f.timer.stop(),f.on.call(`interrupt`,e,e.__data__,f.index,f.group),delete r[l]):+l2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(i?`interrupt`:`cancel`,e,e.__data__,r.index,r.group),delete n[o]}a&&delete e.__transition}}function Es(e){return this.each(function(){Ts(this,e)})}function Ds(e,t){var n,r;return function(){var i=Ss(this,e),a=i.tween;if(a!==n){r=n=a;for(var o=0,s=r.length;o=0&&(e=e.slice(0,t)),!e||e===`start`})}function rc(e,t,n){var r,i,a=nc(t)?xs:Ss;return function(){var o=a(this,e),s=o.on;s!==r&&(i=(r=s).copy()).on(t,n),o.on=i}}function ic(e,t){var n=this._id;return arguments.length<2?Cs(this.node(),n).on.on(e):this.each(rc(n,e,t))}function ac(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function oc(){return this.on(`end.remove`,ac(this._id))}function sc(e){var t=this._name,n=this._id;typeof e!=`function`&&(e=Er(e));for(var r=this._groups,i=r.length,a=Array(i),o=0;o()=>e;function Rc(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function zc(e,t,n){this.k=e,this.x=t,this.y=n}zc.prototype={constructor:zc,scale:function(e){return e===1?this:new zc(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new zc(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return`translate(`+this.x+`,`+this.y+`) scale(`+this.k+`)`}};var Bc=new zc(1,0,0);Vc.prototype=zc.prototype;function Vc(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Bc;return e.__zoom}function Hc(e){e.stopImmediatePropagation()}function Uc(e){e.preventDefault(),e.stopImmediatePropagation()}function Wc(e){return(!e.ctrlKey||e.type===`wheel`)&&!e.button}function Gc(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute(`viewBox`)?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function Kc(){return this.__zoom||Bc}function qc(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Jc(){return navigator.maxTouchPoints||`ontouchstart`in this}function Yc(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],o=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function Xc(){var e=Wc,t=Gc,n=Yc,r=qc,i=Jc,a=[0,1/0],o=[[-1/0,-1/0],[1/0,1/0]],s=250,c=Xo,l=hr(`start`,`zoom`,`end`),u,d,f,p=500,m=150,h=0,g=10;function _(e){e.property(`__zoom`,Kc).on(`wheel.zoom`,w,{passive:!1}).on(`mousedown.zoom`,T).on(`dblclick.zoom`,E).filter(i).on(`touchstart.zoom`,D).on(`touchmove.zoom`,O).on(`touchend.zoom touchcancel.zoom`,k).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}_.transform=function(e,t,n,r){var i=e.selection?e.selection():e;i.property(`__zoom`,Kc),e===i?i.interrupt().each(function(){S(this,arguments).event(r).start().zoom(null,typeof t==`function`?t.apply(this,arguments):t).end()}):x(e,t,n,r)},_.scaleBy=function(e,t,n,r){_.scaleTo(e,function(){return this.__zoom.k*(typeof t==`function`?t.apply(this,arguments):t)},n,r)},_.scaleTo=function(e,r,i,a){_.transform(e,function(){var e=t.apply(this,arguments),a=this.__zoom,s=i==null?b(e):typeof i==`function`?i.apply(this,arguments):i,c=a.invert(s),l=typeof r==`function`?r.apply(this,arguments):r;return n(y(v(a,l),s,c),e,o)},i,a)},_.translateBy=function(e,r,i,a){_.transform(e,function(){return n(this.__zoom.translate(typeof r==`function`?r.apply(this,arguments):r,typeof i==`function`?i.apply(this,arguments):i),t.apply(this,arguments),o)},null,a)},_.translateTo=function(e,r,i,a,s){_.transform(e,function(){var e=t.apply(this,arguments),s=this.__zoom,c=a==null?b(e):typeof a==`function`?a.apply(this,arguments):a;return n(Bc.translate(c[0],c[1]).scale(s.k).translate(typeof r==`function`?-r.apply(this,arguments):-r,typeof i==`function`?-i.apply(this,arguments):-i),e,o)},a,s)};function v(e,t){return t=Math.max(a[0],Math.min(a[1],t)),t===e.k?e:new zc(t,e.x,e.y)}function y(e,t,n){var r=t[0]-n[0]*e.k,i=t[1]-n[1]*e.k;return r===e.x&&i===e.y?e:new zc(e.k,r,i)}function b(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function x(e,n,r,i){e.on(`start.zoom`,function(){S(this,arguments).event(i).start()}).on(`interrupt.zoom end.zoom`,function(){S(this,arguments).event(i).end()}).tween(`zoom`,function(){var e=this,a=arguments,o=S(e,a).event(i),s=t.apply(e,a),l=r==null?b(s):typeof r==`function`?r.apply(e,a):r,u=Math.max(s[1][0]-s[0][0],s[1][1]-s[0][1]),d=e.__zoom,f=typeof n==`function`?n.apply(e,a):n,p=c(d.invert(l).concat(u/d.k),f.invert(l).concat(u/f.k));return function(e){if(e===1)e=f;else{var t=p(e),n=u/t[2];e=new zc(n,l[0]-t[0]*n,l[1]-t[1]*n)}o.zoom(null,e)}})}function S(e,t,n){return!n&&e.__zooming||new C(e,t)}function C(e,n){this.that=e,this.args=n,this.active=0,this.sourceEvent=null,this.extent=t.apply(e,n),this.taps=0}C.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit(`start`)),this},zoom:function(e,t){return this.mouse&&e!==`mouse`&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&e!==`touch`&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&e!==`touch`&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit(`zoom`),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit(`end`)),this},emit:function(e){var t=va(this.that).datum();l.call(e,this.that,new Rc(e,{sourceEvent:this.sourceEvent,target:_,type:e,transform:this.that.__zoom,dispatch:l}),t)}};function w(t,...i){if(!e.apply(this,arguments))return;var s=S(this,i).event(t),c=this.__zoom,l=Math.max(a[0],Math.min(a[1],c.k*2**r.apply(this,arguments))),u=ba(t);if(s.wheel)(s.mouse[0][0]!==u[0]||s.mouse[0][1]!==u[1])&&(s.mouse[1]=c.invert(s.mouse[0]=u)),clearTimeout(s.wheel);else if(c.k===l)return;else s.mouse=[u,c.invert(u)],Ts(this),s.start();Uc(t),s.wheel=setTimeout(d,m),s.zoom(`mouse`,n(y(v(c,l),s.mouse[0],s.mouse[1]),s.extent,o));function d(){s.wheel=null,s.end()}}function T(t,...r){if(f||!e.apply(this,arguments))return;var i=t.currentTarget,a=S(this,r,!0).event(t),s=va(t.view).on(`mousemove.zoom`,d,!0).on(`mouseup.zoom`,p,!0),c=ba(t,i),l=t.clientX,u=t.clientY;Ta(t.view),Hc(t),a.mouse=[c,this.__zoom.invert(c)],Ts(this),a.start();function d(e){if(Uc(e),!a.moved){var t=e.clientX-l,r=e.clientY-u;a.moved=t*t+r*r>h}a.event(e).zoom(`mouse`,n(y(a.that.__zoom,a.mouse[0]=ba(e,i),a.mouse[1]),a.extent,o))}function p(e){s.on(`mousemove.zoom mouseup.zoom`,null),Ea(e.view,a.moved),Uc(e),a.event(e).end()}}function E(r,...i){if(e.apply(this,arguments)){var a=this.__zoom,c=ba(r.changedTouches?r.changedTouches[0]:r,this),l=a.invert(c),u=a.k*(r.shiftKey?.5:2),d=n(y(v(a,u),c,l),t.apply(this,i),o);Uc(r),s>0?va(this).transition().duration(s).call(x,d,c,r):va(this).call(_.transform,d,c,r)}}function D(t,...n){if(e.apply(this,arguments)){var r=t.touches,i=r.length,a=S(this,n,t.changedTouches.length===i).event(t),o,s,c,l;for(Hc(t),s=0;s`[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001`,error002:()=>`It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.`,error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>`The React Flow parent container needs a width and a height to render the graph.`,error005:()=>`Only child nodes can use a parent extent.`,error006:()=>`Can't create edge. An edge needs a source and a target.`,error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e===`source`?n:r}", edge id: ${t}.`,error010:()=>`Handle: No node id found. Make sure to only use a Handle inside a custom Node.`,error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e=`react`)=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>`useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.`,error015:()=>`It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs.`},Qc=[[-1/0,-1/0],[1/0,1/0]],$c=[`Enter`,` `,`Escape`],el={"node.a11yDescription.default":`Press enter or space to select a node. Press delete to remove it and escape to cancel.`,"node.a11yDescription.keyboardDisabled":`Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.`,"node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":`Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.`,"controls.ariaLabel":`Control Panel`,"controls.zoomIn.ariaLabel":`Zoom In`,"controls.zoomOut.ariaLabel":`Zoom Out`,"controls.fitView.ariaLabel":`Fit View`,"controls.interactive.ariaLabel":`Toggle Interactivity`,"minimap.ariaLabel":`Mini Map`,"handle.ariaLabel":`Handle`},tl;(function(e){e.Strict=`strict`,e.Loose=`loose`})(tl||={});var nl;(function(e){e.Free=`free`,e.Vertical=`vertical`,e.Horizontal=`horizontal`})(nl||={});var rl;(function(e){e.Partial=`partial`,e.Full=`full`})(rl||={});var il={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null},al;(function(e){e.Bezier=`default`,e.Straight=`straight`,e.Step=`step`,e.SmoothStep=`smoothstep`,e.SimpleBezier=`simplebezier`})(al||={});var ol;(function(e){e.Arrow=`arrow`,e.ArrowClosed=`arrowclosed`})(ol||={});var q;(function(e){e.Left=`left`,e.Top=`top`,e.Right=`right`,e.Bottom=`bottom`})(q||={});var sl={[q.Left]:q.Right,[q.Right]:q.Left,[q.Top]:q.Bottom,[q.Bottom]:q.Top};function cl(e){return e===null?null:e?`valid`:`invalid`}var ll=e=>`id`in e&&`source`in e&&`target`in e,ul=e=>`id`in e&&`position`in e&&!(`source`in e)&&!(`target`in e),dl=e=>`id`in e&&`internals`in e&&!(`source`in e)&&!(`target`in e),fl=(e,t=[0,0])=>{let{width:n,height:r}=Wl(e),i=e.origin??t,a=n*i[0],o=r*i[1];return{x:e.position.x-a,y:e.position.y-o}},pl=(e,t={nodeOrigin:[0,0]})=>e.length===0?{x:0,y:0,width:0,height:0}:Ol(e.reduce((e,n)=>{let r=typeof n==`string`,i=!t.nodeLookup&&!r?n:void 0;return t.nodeLookup&&(i=r?t.nodeLookup.get(n):dl(n)?n:t.nodeLookup.get(n.id)),El(e,i?Al(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0})},{x:1/0,y:1/0,x2:-1/0,y2:-1/0})),ml=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(e=>{(t.filter===void 0||t.filter(e))&&(n=El(n,Al(e)),r=!0)}),r?Ol(n):{x:0,y:0,width:0,height:0}},hl=(e,t,[n,r,i]=[0,0,1],a=!1,o=!1)=>{let s={...Ll(t,[n,r,i]),width:t.width/i,height:t.height/i},c=[];for(let t of e.values()){let{measured:e,selectable:n=!0,hidden:r=!1}=t;if(o&&!n||r)continue;let i=e.width??t.width??t.initialWidth??null,l=e.height??t.height??t.initialHeight??null,u=Ml(s,kl(t)),d=(i??0)*(l??0),f=a&&u>0;(!t.internals.handleBounds||f||u>=d||t.dragging)&&c.push(t)}return c},gl=(e,t)=>{let n=new Set;return e.forEach(e=>{n.add(e.id)}),t.filter(e=>n.has(e.source)||n.has(e.target))};function _l(e,t){let n=new Map,r=t?.nodes?new Set(t.nodes.map(e=>e.id)):null;return e.forEach(e=>{e.measured.width&&e.measured.height&&(t?.includeHiddenNodes||!e.hidden)&&(!r||r.has(e.id))&&n.set(e.id,e)}),n}async function vl({nodes:e,width:t,height:n,panZoom:r,minZoom:i,maxZoom:a},o){if(e.size===0)return Promise.resolve(!0);let s=Vl(ml(_l(e,o)),t,n,o?.minZoom??i,o?.maxZoom??a,o?.padding??.1);return await r.setViewport(s,{duration:o?.duration,ease:o?.ease,interpolate:o?.interpolate}),Promise.resolve(!0)}function yl({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:i,onError:a}){let o=n.get(e),s=o.parentId?n.get(o.parentId):void 0,{x:c,y:l}=s?s.internals.positionAbsolute:{x:0,y:0},u=o.origin??r,d=o.extent||i;if(o.extent===`parent`&&!o.expandParent)if(!s)a?.(`005`,Zc.error005());else{let e=s.measured.width,t=s.measured.height;e&&t&&(d=[[c,l],[c+e,l+t]])}else s&&Ul(o.extent)&&(d=[[o.extent[0][0]+c,o.extent[0][1]+l],[o.extent[1][0]+c,o.extent[1][1]+l]]);let f=Ul(d)?Sl(t,d,o.measured):t;return(o.measured.width===void 0||o.measured.height===void 0)&&a?.(`015`,Zc.error015()),{position:{x:f.x-c+(o.measured.width??0)*u[0],y:f.y-l+(o.measured.height??0)*u[1]},positionAbsolute:f}}async function bl({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:i}){let a=new Set(e.map(e=>e.id)),o=[];for(let e of n){if(e.deletable===!1)continue;let t=a.has(e.id),n=!t&&e.parentId&&o.find(t=>t.id===e.parentId);(t||n)&&o.push(e)}let s=new Set(t.map(e=>e.id)),c=r.filter(e=>e.deletable!==!1),l=gl(o,c);for(let e of c)s.has(e.id)&&!l.find(t=>t.id===e.id)&&l.push(e);if(!i)return{edges:l,nodes:o};let u=await i({nodes:o,edges:l});return typeof u==`boolean`?u?{edges:l,nodes:o}:{edges:[],nodes:[]}:u}var xl=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Sl=(e={x:0,y:0},t,n)=>({x:xl(e.x,t[0][0],t[1][0]-(n?.width??0)),y:xl(e.y,t[0][1],t[1][1]-(n?.height??0))});function Cl(e,t,n){let{width:r,height:i}=Wl(n),{x:a,y:o}=n.internals.positionAbsolute;return Sl(e,[[a,o],[a+r,o+i]],t)}var wl=(e,t,n)=>en?-xl(Math.abs(e-n),1,t)/t:0,Tl=(e,t,n=15,r=40)=>[wl(e.x,r,t.width-r)*n,wl(e.y,r,t.height-r)*n],El=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Dl=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Ol=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),kl=(e,t=[0,0])=>{let{x:n,y:r}=dl(e)?e.internals.positionAbsolute:fl(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Al=(e,t=[0,0])=>{let{x:n,y:r}=dl(e)?e.internals.positionAbsolute:fl(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},jl=(e,t)=>Ol(El(Dl(e),Dl(t))),Ml=(e,t)=>{let n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},Nl=e=>Pl(e.width)&&Pl(e.height)&&Pl(e.x)&&Pl(e.y),Pl=e=>!isNaN(e)&&isFinite(e),Fl=(e,t)=>{},Il=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Ll=({x:e,y:t},[n,r,i],a=!1,o=[1,1])=>{let s={x:(e-n)/i,y:(t-r)/i};return a?Il(s,o):s},Rl=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r});function J(e,t){if(typeof e==`number`)return Math.floor((t-t/(1+e))*.5);if(typeof e==`string`&&e.endsWith(`px`)){let t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if(typeof e==`string`&&e.endsWith(`%`)){let n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function zl(e,t,n){if(typeof e==`string`||typeof e==`number`){let r=J(e,n),i=J(e,t);return{top:r,right:i,bottom:r,left:i,x:i*2,y:r*2}}if(typeof e==`object`){let r=J(e.top??e.y??0,n),i=J(e.bottom??e.y??0,n),a=J(e.left??e.x??0,t),o=J(e.right??e.x??0,t);return{top:r,right:o,bottom:i,left:a,x:a+o,y:r+i}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function Bl(e,t,n,r,i,a){let{x:o,y:s}=Rl(e,[t,n,r]),{x:c,y:l}=Rl({x:e.x+e.width,y:e.y+e.height},[t,n,r]),u=i-c,d=a-l;return{left:Math.floor(o),top:Math.floor(s),right:Math.floor(u),bottom:Math.floor(d)}}var Vl=(e,t,n,r,i,a)=>{let o=zl(a,t,n),s=(t-o.x)/e.width,c=(n-o.y)/e.height,l=xl(Math.min(s,c),r,i),u=e.x+e.width/2,d=e.y+e.height/2,f=t/2-u*l,p=n/2-d*l,m=Bl(e,f,p,l,t,n),h={left:Math.min(m.left-o.left,0),top:Math.min(m.top-o.top,0),right:Math.min(m.right-o.right,0),bottom:Math.min(m.bottom-o.bottom,0)};return{x:f-h.left+h.right,y:p-h.top+h.bottom,zoom:l}},Hl=()=>typeof navigator<`u`&&navigator?.userAgent?.indexOf(`Mac`)>=0;function Ul(e){return e!=null&&e!==`parent`}function Wl(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Gl(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function Kl(e,t={width:0,height:0},n,r,i){let a={...e},o=r.get(n);if(o){let e=o.origin||i;a.x+=o.internals.positionAbsolute.x-(t.width??0)*e[0],a.y+=o.internals.positionAbsolute.y-(t.height??0)*e[1]}return a}function ql(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Jl(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function Yl(e){return{...el,...e||{}}}function Xl(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:i}){let{x:a,y:o}=nu(e),s=Ll({x:a-(i?.left??0),y:o-(i?.top??0)},r),{x:c,y:l}=n?Il(s,t):s;return{xSnapped:c,ySnapped:l,...s}}var Zl=e=>({width:e.offsetWidth,height:e.offsetHeight}),Ql=e=>e?.getRootNode?.()||window?.document,$l=[`INPUT`,`SELECT`,`TEXTAREA`];function eu(e){let t=e.composedPath?.()?.[0]||e.target;return t?.nodeType===1?$l.includes(t.nodeName)||t.hasAttribute(`contenteditable`)||!!t.closest(`.nokey`):!1}var tu=e=>`clientX`in e,nu=(e,t)=>{let n=tu(e),r=n?e.clientX:e.touches?.[0].clientX,i=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:i-(t?.top??0)}},ru=(e,t,n,r,i)=>{let a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...Zl(t)}})};function iu({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:a,targetControlX:o,targetControlY:s}){let c=e*.125+i*.375+o*.375+n*.125,l=t*.125+a*.375+s*.375+r*.125;return[c,l,Math.abs(c-e),Math.abs(l-t)]}function au(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function ou({pos:e,x1:t,y1:n,x2:r,y2:i,c:a}){switch(e){case q.Left:return[t-au(t-r,a),n];case q.Right:return[t+au(r-t,a),n];case q.Top:return[t,n-au(n-i,a)];case q.Bottom:return[t,n+au(i-n,a)]}}function su({sourceX:e,sourceY:t,sourcePosition:n=q.Bottom,targetX:r,targetY:i,targetPosition:a=q.Top,curvature:o=.25}){let[s,c]=ou({pos:n,x1:e,y1:t,x2:r,y2:i,c:o}),[l,u]=ou({pos:a,x1:r,y1:i,x2:e,y2:t,c:o}),[d,f,p,m]=iu({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:s,sourceControlY:c,targetControlX:l,targetControlY:u});return[`M${e},${t} C${s},${c} ${l},${u} ${r},${i}`,d,f,p,m]}function cu({sourceX:e,sourceY:t,targetX:n,targetY:r}){let i=Math.abs(n-e)/2,a=n0}var du=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||``}-${n}${r||``}`,fu=(e,t)=>t.some(t=>t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle)),pu=(e,t,n={})=>{if(!e.source||!e.target)return Zc.error006(),t;let r=n.getEdgeId||du,i;return i=ll(e)?{...e}:{...e,id:r(e)},fu(i,t)?t:(i.sourceHandle===null&&delete i.sourceHandle,i.targetHandle===null&&delete i.targetHandle,t.concat(i))};function mu({sourceX:e,sourceY:t,targetX:n,targetY:r}){let[i,a,o,s]=cu({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,a,o,s]}var hu={[q.Left]:{x:-1,y:0},[q.Right]:{x:1,y:0},[q.Top]:{x:0,y:-1},[q.Bottom]:{x:0,y:1}},gu=({source:e,sourcePosition:t=q.Bottom,target:n})=>t===q.Left||t===q.Right?e.xMath.sqrt((t.x-e.x)**2+(t.y-e.y)**2);function vu({source:e,sourcePosition:t=q.Bottom,target:n,targetPosition:r=q.Top,center:i,offset:a,stepPosition:o}){let s=hu[t],c=hu[r],l={x:e.x+s.x*a,y:e.y+s.y*a},u={x:n.x+c.x*a,y:n.y+c.y*a},d=gu({source:l,sourcePosition:t,target:u}),f=d.x===0?`y`:`x`,p=d[f],m=[],h,g,_={x:0,y:0},v={x:0,y:0},[,,y,b]=cu({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(s[f]*c[f]===-1){f===`x`?(h=i.x??l.x+(u.x-l.x)*o,g=i.y??(l.y+u.y)/2):(h=i.x??(l.x+u.x)/2,g=i.y??l.y+(u.y-l.y)*o);let e=[{x:h,y:l.y},{x:h,y:u.y}],t=[{x:l.x,y:g},{x:u.x,y:g}];m=s[f]===p?f===`x`?e:t:f===`x`?t:e}else{let i=[{x:l.x,y:u.y}],o=[{x:u.x,y:l.y}];if(m=f===`x`?s.x===p?o:i:s.y===p?i:o,t===r){let t=Math.abs(e[f]-n[f]);if(t<=a){let r=Math.min(a-1,a-t);s[f]===p?_[f]=(l[f]>e[f]?-1:1)*r:v[f]=(u[f]>n[f]?-1:1)*r}}if(t!==r){let e=f===`x`?`y`:`x`,t=s[f]===c[e],n=l[e]>u[e],r=l[e]=Math.max(Math.abs(d.y-m[0].y),Math.abs(y.y-m[0].y))?(h=(d.x+y.x)/2,g=m[0].y):(h=m[0].x,g=(d.y+y.y)/2)}return[[e,{x:l.x+_.x,y:l.y+_.y},...m,{x:u.x+v.x,y:u.y+v.y},n],h,g,y,b]}function yu(e,t,n,r){let i=Math.min(_u(e,t)/2,_u(t,n)/2,r),{x:a,y:o}=t;if(e.x===a&&a===n.x||e.y===o&&o===n.y)return`L${a} ${o}`;if(e.y===o){let t=e.x{let r=``;return r=n>0&&ne.id===t):e[0])||null}function Eu(e,t){return e?typeof e==`string`?e:`${t?`${t}__`:``}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join(`&`)}`:``}function Du(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:i}){let a=new Set;return e.reduce((e,o)=>([o.markerStart||r,o.markerEnd||i].forEach(r=>{if(r&&typeof r==`object`){let i=Eu(r,t);a.has(i)||(e.push({id:i,color:r.color||n,...r}),a.add(i))}}),e),[]).sort((e,t)=>e.id.localeCompare(t.id))}var Ou=1e3,ku=10,Au={nodeOrigin:[0,0],nodeExtent:Qc,elevateNodesOnSelect:!0,zIndexMode:`basic`,defaults:{}},ju={...Au,checkEquality:!0};function Mu(e,t){let n={...e};for(let e in t)t[e]!==void 0&&(n[e]=t[e]);return n}function Nu(e,t,n){let r=Mu(Au,n);for(let n of e.values())if(n.parentId)Ru(n,e,t,r);else{let e=Sl(fl(n,r.nodeOrigin),Ul(n.extent)?n.extent:r.nodeExtent,Wl(n));n.internals.positionAbsolute=e}}function Pu(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;let n=[],r=[];for(let t of e.handles){let i={id:t.id,width:t.width??1,height:t.height??1,nodeId:e.id,x:t.x,y:t.y,position:t.position,type:t.type};t.type===`source`?n.push(i):t.type===`target`&&r.push(i)}return{source:n,target:r}}function Fu(e){return e===`manual`}function Iu(e,t,n,r={}){let i=Mu(ju,r),a={i:0},o=new Map(t),s=i?.elevateNodesOnSelect&&!Fu(i.zIndexMode)?Ou:0,c=e.length>0;t.clear(),n.clear();for(let l of e){let e=o.get(l.id);if(i.checkEquality&&l===e?.internals.userNode)t.set(l.id,e);else{let n=Sl(fl(l,i.nodeOrigin),Ul(l.extent)?l.extent:i.nodeExtent,Wl(l));e={...i.defaults,...l,measured:{width:l.measured?.width,height:l.measured?.height},internals:{positionAbsolute:n,handleBounds:Pu(l,e),z:zu(l,s,i.zIndexMode),userNode:l}},t.set(l.id,e)}(e.measured===void 0||e.measured.width===void 0||e.measured.height===void 0)&&!e.hidden&&(c=!1),l.parentId&&Ru(e,t,n,r,a)}return c}function Lu(e,t){if(!e.parentId)return;let n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function Ru(e,t,n,r,i){let{elevateNodesOnSelect:a,nodeOrigin:o,nodeExtent:s,zIndexMode:c}=Mu(Au,r),l=e.parentId,u=t.get(l);if(!u){console.warn(`Parent node ${l} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}Lu(e,n),i&&!u.parentId&&u.internals.rootParentIndex===void 0&&c===`auto`&&(u.internals.rootParentIndex=++i.i,u.internals.z=u.internals.z+i.i*ku),i&&u.internals.rootParentIndex!==void 0&&(i.i=u.internals.rootParentIndex);let{x:d,y:f,z:p}=Bu(e,u,o,s,a&&!Fu(c)?Ou:0,c),{positionAbsolute:m}=e.internals,h=d!==m.x||f!==m.y;(h||p!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:h?{x:d,y:f}:m,z:p}})}function zu(e,t,n){let r=Pl(e.zIndex)?e.zIndex:0;return Fu(n)?r:r+(e.selected?t:0)}function Bu(e,t,n,r,i,a){let{x:o,y:s}=t.internals.positionAbsolute,c=Wl(e),l=fl(e,n),u=Ul(e.extent)?Sl(l,e.extent,c):l,d=Sl({x:o+u.x,y:s+u.y},r,c);e.extent===`parent`&&(d=Cl(d,c,t));let f=zu(e,i,a),p=t.internals.z??0;return{x:d.x,y:d.y,z:p>=f?p+1:f}}function Vu(e,t,n,r=[0,0]){let i=[],a=new Map;for(let n of e){let e=t.get(n.parentId);if(!e)continue;let r=jl(a.get(n.parentId)?.expandedRect??kl(e),n.rect);a.set(n.parentId,{expandedRect:r,parent:e})}return a.size>0&&a.forEach(({expandedRect:t,parent:a},o)=>{let s=a.internals.positionAbsolute,c=Wl(a),l=a.origin??r,u=t.x0||d>0||m||h)&&(i.push({id:o,type:`position`,position:{x:a.position.x-u+m,y:a.position.y-d+h}}),n.get(o)?.forEach(t=>{e.some(e=>e.id===t.id)||i.push({id:t.id,type:`position`,position:{x:t.position.x+u,y:t.position.y+d}})})),(c.width0){let e=Vu(f,t,n,i);l.push(...e)}return{changes:l,updatedInternals:c}}async function Uu({delta:e,panZoom:t,transform:n,translateExtent:r,width:i,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);let o=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[i,a]],r),s=!!o&&(o.x!==n[0]||o.y!==n[1]||o.k!==n[2]);return Promise.resolve(s)}function Wu(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function Gu(e,t,n){e.clear(),t.clear();for(let r of n){let{source:n,target:i,sourceHandle:a=null,targetHandle:o=null}=r,s={edgeId:r.id,source:n,target:i,sourceHandle:a,targetHandle:o},c=`${n}-${a}--${i}-${o}`;Wu(`source`,s,`${i}-${o}--${n}-${a}`,e,n,a),Wu(`target`,s,c,e,i,o),t.set(r.id,r)}}function Ku(e,t){if(!e.parentId)return!1;let n=t.get(e.parentId);return n?n.selected?!0:Ku(n,t):!1}function qu(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function Ju(e,t,n,r){let i=new Map;for(let[a,o]of e)if((o.selected||o.id===r)&&(!o.parentId||!Ku(o,e))&&(o.draggable||t&&o.draggable===void 0)){let t=e.get(a);t&&i.set(a,{id:a,position:t.position||{x:0,y:0},distance:{x:n.x-t.internals.positionAbsolute.x,y:n.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return i}function Yu({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){let i=[];for(let[e,a]of t){let t=n.get(e)?.internals.userNode;t&&i.push({...t,position:a.position,dragging:r})}if(!e)return[i[0],i];let a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:i[0],i]}function Xu({dragItems:e,snapGrid:t,x:n,y:r}){let i=e.values().next().value;if(!i)return null;let a={x:n-i.distance.x,y:r-i.distance.y},o=Il(a,t);return{x:o.x-a.x,y:o.y-a.y}}function Zu({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:i}){let a={x:null,y:null},o=0,s=new Map,c=!1,l={x:0,y:0},u=null,d=!1,f=null,p=!1,m=!1,h=null;function g({noDragClassName:g,handleSelector:_,domNode:v,isSelectable:y,nodeId:b,nodeClickDistance:x=0}){f=va(v);function S({x:e,y:n}){let{nodeLookup:i,nodeExtent:o,snapGrid:c,snapToGrid:l,nodeOrigin:u,onNodeDrag:d,onSelectionDrag:f,onError:p,updateNodePositions:g}=t();a={x:e,y:n};let _=!1,v=s.size>1,y=v&&o?Dl(ml(s)):null,x=v&&l?Xu({dragItems:s,snapGrid:c,x:e,y:n}):null;for(let[t,r]of s){if(!i.has(t))continue;let a={x:e-r.distance.x,y:n-r.distance.y};l&&(a=x?{x:Math.round(a.x+x.x),y:Math.round(a.y+x.y)}:Il(a,c));let s=null;if(v&&o&&!r.extent&&y){let{positionAbsolute:e}=r.internals,t=e.x-y.x+o[0][0],n=e.x+r.measured.width-y.x2+o[1][0],i=e.y-y.y+o[0][1],a=e.y+r.measured.height-y.y2+o[1][1];s=[[t,i],[n,a]]}let{position:d,positionAbsolute:f}=yl({nodeId:t,nextPosition:a,nodeLookup:i,nodeExtent:s||o,nodeOrigin:u,onError:p});_=_||r.position.x!==d.x||r.position.y!==d.y,r.position=d,r.internals.positionAbsolute=f}if(m||=_,_&&(g(s,!0),h&&(r||d||!b&&f))){let[e,t]=Yu({nodeId:b,dragItems:s,nodeLookup:i});r?.(h,s,e,t),d?.(h,e,t),b||f?.(h,t)}}async function C(){if(!u)return;let{transform:e,panBy:n,autoPanSpeed:r,autoPanOnNodeDrag:i}=t();if(!i){c=!1,cancelAnimationFrame(o);return}let[s,d]=Tl(l,u,r);(s!==0||d!==0)&&(a.x=(a.x??0)-s/e[2],a.y=(a.y??0)-d/e[2],await n({x:s,y:d})&&S(a)),o=requestAnimationFrame(C)}function w(r){let{nodeLookup:i,multiSelectionActive:o,nodesDraggable:c,transform:l,snapGrid:f,snapToGrid:p,selectNodesOnDrag:m,onNodeDragStart:h,onSelectionDragStart:g,unselectNodesAndEdges:_}=t();d=!0,(!m||!y)&&!o&&b&&(i.get(b)?.selected||_()),y&&m&&b&&e?.(b);let v=Xl(r.sourceEvent,{transform:l,snapGrid:f,snapToGrid:p,containerBounds:u});if(a=v,s=Ju(i,c,v,b),s.size>0&&(n||h||!b&&g)){let[e,t]=Yu({nodeId:b,dragItems:s,nodeLookup:i});n?.(r.sourceEvent,s,e,t),h?.(r.sourceEvent,e,t),b||g?.(r.sourceEvent,t)}}let T=Na().clickDistance(x).on(`start`,e=>{let{domNode:n,nodeDragThreshold:r,transform:i,snapGrid:o,snapToGrid:s}=t();u=n?.getBoundingClientRect()||null,p=!1,m=!1,h=e.sourceEvent,r===0&&w(e),a=Xl(e.sourceEvent,{transform:i,snapGrid:o,snapToGrid:s,containerBounds:u}),l=nu(e.sourceEvent,u)}).on(`drag`,e=>{let{autoPanOnNodeDrag:n,transform:r,snapGrid:i,snapToGrid:o,nodeDragThreshold:f,nodeLookup:m}=t(),g=Xl(e.sourceEvent,{transform:r,snapGrid:i,snapToGrid:o,containerBounds:u});if(h=e.sourceEvent,(e.sourceEvent.type===`touchmove`&&e.sourceEvent.touches.length>1||b&&!m.has(b))&&(p=!0),!p){if(!c&&n&&d&&(c=!0,C()),!d){let t=nu(e.sourceEvent,u),n=t.x-l.x,r=t.y-l.y;Math.sqrt(n*n+r*r)>f&&w(e)}(a.x!==g.xSnapped||a.y!==g.ySnapped)&&s&&d&&(l=nu(e.sourceEvent,u),S(g))}}).on(`end`,e=>{if(!(!d||p)&&(c=!1,d=!1,cancelAnimationFrame(o),s.size>0)){let{nodeLookup:n,updateNodePositions:r,onNodeDragStop:a,onSelectionDragStop:o}=t();if(m&&=(r(s,!1),!1),i||a||!b&&o){let[t,r]=Yu({nodeId:b,dragItems:s,nodeLookup:n,dragging:!1});i?.(e.sourceEvent,s,t,r),a?.(e.sourceEvent,t,r),b||o?.(e.sourceEvent,r)}}}).filter(e=>{let t=e.target;return!e.button&&(!g||!qu(t,`.${g}`,v))&&(!_||qu(t,_,v))});f.call(T)}function _(){f?.on(`.drag`,null)}return{update:g,destroy:_}}function Qu(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())Ml(i,kl(e))>0&&r.push(e);return r}var $u=250;function ed(e,t,n,r){let i=[],a=1/0,o=Qu(e,n,t+$u);for(let n of o){let o=[...n.internals.handleBounds?.source??[],...n.internals.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=wu(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function td(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===`strict`?o.internals.handleBounds?.[t]:[...o.internals.handleBounds?.source??[],...o.internals.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...wu(o,c,c.position,!0)}:c}function nd(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function rd(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}var id=()=>!0;function ad(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:i,edgeUpdaterType:a,isTarget:o,domNode:s,nodeLookup:c,lib:l,autoPanOnConnect:u,flowId:d,panBy:f,cancelConnection:p,onConnectStart:m,onConnect:h,onConnectEnd:g,isValidConnection:_=id,onReconnectEnd:v,updateConnection:y,getTransform:b,getFromHandle:x,autoPanSpeed:S,dragThreshold:C=1,handleDomNode:w}){let T=Ql(e.target),E=0,D,{x:O,y:k}=nu(e),A=nd(a,w),j=s?.getBoundingClientRect(),M=!1;if(!j||!A)return;let N=td(i,A,r,c,t);if(!N)return;let ee=nu(e,j),te=!1,P=null,F=!1,ne=null;function re(){if(!u||!j)return;let[e,t]=Tl(ee,j,S);f({x:e,y:t}),E=requestAnimationFrame(re)}let ie={...N,nodeId:i,type:A,position:N.position},ae=c.get(i),I={inProgress:!0,isValid:null,from:wu(ae,ie,q.Left,!0),fromHandle:ie,fromPosition:ie.position,fromNode:ae,to:ee,toHandle:null,toPosition:sl[ie.position],toNode:null,pointer:ee};function L(){M=!0,y(I),m?.(e,{nodeId:i,handleId:r,handleType:A})}C===0&&L();function oe(e){if(!M){let{x:t,y:n}=nu(e),r=t-O,i=n-k;if(!(r*r+i*i>C*C))return;L()}if(!x()||!ie){se(e);return}let a=b();ee=nu(e,j),D=ed(Ll(ee,a,!1,[1,1]),n,c,ie),te||=(re(),!0);let s=od(e,{handle:D,connectionMode:t,fromNodeId:i,fromHandleId:r,fromType:o?`target`:`source`,isValidConnection:_,doc:T,lib:l,flowId:d,nodeLookup:c});ne=s.handleDomNode,P=s.connection,F=rd(!!D,s.isValid);let u=c.get(i),f=u?wu(u,ie,q.Left,!0):I.from,p={...I,from:f,isValid:F,to:s.toHandle&&F?Rl({x:s.toHandle.x,y:s.toHandle.y},a):ee,toHandle:s.toHandle,toPosition:F&&s.toHandle?s.toHandle.position:sl[ie.position],toNode:s.toHandle?c.get(s.toHandle.nodeId):null,pointer:ee};y(p),I=p}function se(e){if(!(`touches`in e&&e.touches.length>0)){if(M){(D||ne)&&P&&F&&h?.(P);let{inProgress:t,...n}=I,r={...n,toPosition:I.toHandle?I.toPosition:null};g?.(e,r),a&&v?.(e,r)}p(),cancelAnimationFrame(E),te=!1,F=!1,P=null,ne=null,T.removeEventListener(`mousemove`,oe),T.removeEventListener(`mouseup`,se),T.removeEventListener(`touchmove`,oe),T.removeEventListener(`touchend`,se)}}T.addEventListener(`mousemove`,oe),T.addEventListener(`mouseup`,se),T.addEventListener(`touchmove`,oe),T.addEventListener(`touchend`,se)}function od(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=id,nodeLookup:u}){let d=a===`target`,f=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=nu(e),h=o.elementFromPoint(p,m),g=h?.classList.contains(`${s}-flow__handle`)?h:f,_={handleDomNode:g,isValid:!1,connection:null,toHandle:null};if(g){let e=nd(void 0,g),t=g.getAttribute(`data-nodeid`),a=g.getAttribute(`data-handleid`),o=g.classList.contains(`connectable`),s=g.classList.contains(`connectableend`);if(!t||!e)return _;let c={source:d?t:r,sourceHandle:d?a:i,target:d?r:t,targetHandle:d?i:a};_.connection=c,_.isValid=o&&s&&(n===tl.Strict?d&&e===`source`||!d&&e===`target`:t!==r||a!==i)&&l(c),_.toHandle=td(t,e,a,u,n,!0)}return _}var sd={onPointerDown:ad,isValid:od};function cd({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){let i=va(e);function a({translateExtent:e,width:a,height:o,zoomStep:s=1,pannable:c=!0,zoomable:l=!0,inversePan:u=!1}){let d=e=>{if(e.sourceEvent.type!==`wheel`||!t)return;let r=n(),i=e.sourceEvent.ctrlKey&&Hl()?10:1,a=-e.sourceEvent.deltaY*(e.sourceEvent.deltaMode===1?.05:e.sourceEvent.deltaMode?1:.002)*s,o=r[2]*2**(a*i);t.scaleTo(o)},f=[0,0],p=Xc().on(`start`,e=>{(e.sourceEvent.type===`mousedown`||e.sourceEvent.type===`touchstart`)&&(f=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])}).on(`zoom`,c?i=>{let s=n();if(i.sourceEvent.type!==`mousemove`&&i.sourceEvent.type!==`touchmove`||!t)return;let c=[i.sourceEvent.clientX??i.sourceEvent.touches[0].clientX,i.sourceEvent.clientY??i.sourceEvent.touches[0].clientY],l=[c[0]-f[0],c[1]-f[1]];f=c;let d=r()*Math.max(s[2],Math.log(s[2]))*(u?-1:1),p={x:s[0]-l[0]*d,y:s[1]-l[1]*d},m=[[0,0],[a,o]];t.setViewportConstrained({x:p.x,y:p.y,zoom:s[2]},m,e)}:null).on(`zoom.wheel`,l?d:null);i.call(p,{})}function o(){i.on(`zoom`,null)}return{update:a,destroy:o,pointer:ba}}var ld=e=>({x:e.x,y:e.y,zoom:e.k}),ud=({x:e,y:t,zoom:n})=>Bc.translate(e,t).scale(n),dd=(e,t)=>e.target.closest(`.${t}`),fd=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),pd=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,md=(e,t=0,n=pd,r=()=>{})=>{let i=typeof t==`number`&&t>0;return i||r(),i?e.transition().duration(t).ease(n).on(`end`,r):e},hd=e=>{let t=e.ctrlKey&&Hl()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function gd({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:i,panOnScrollSpeed:a,zoomOnPinch:o,onPanZoomStart:s,onPanZoom:c,onPanZoomEnd:l}){return u=>{if(dd(u,t))return u.ctrlKey&&u.preventDefault(),!1;u.preventDefault(),u.stopImmediatePropagation();let d=n.property(`__zoom`).k||1;if(u.ctrlKey&&o){let e=ba(u),t=d*2**hd(u);r.scaleTo(n,t,e,u);return}let f=u.deltaMode===1?20:1,p=i===nl.Vertical?0:u.deltaX*f,m=i===nl.Horizontal?0:u.deltaY*f;!Hl()&&u.shiftKey&&i!==nl.Vertical&&(p=u.deltaY*f,m=0),r.translateBy(n,-(p/d)*a,-(m/d)*a,{internal:!0});let h=ld(n.property(`__zoom`));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(u,h),e.panScrollTimeout=setTimeout(()=>{l?.(u,h),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,s?.(u,h))}}function _d({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,i){let a=r.type===`wheel`,o=!t&&a&&!r.ctrlKey,s=dd(r,e);if(r.ctrlKey&&a&&s&&r.preventDefault(),o||s)return null;r.preventDefault(),n.call(this,r,i)}}function vd({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;let i=ld(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=i,r.sourceEvent?.type===`mousedown`&&t(!0),n&&n?.(r.sourceEvent,i)}}function yd({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:i}){return a=>{e.usedRightMouseButton=!!(n&&fd(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),i&&!a.sourceEvent?.internal&&i?.(a.sourceEvent,ld(a.transform))}}function bd({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:i,onPaneContextMenu:a}){return o=>{if(!o.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&fd(t,e.mouseButton??0)&&!e.usedRightMouseButton&&o.sourceEvent&&a(o.sourceEvent),e.usedRightMouseButton=!1,r(!1),i)){let t=ld(o.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{i?.(o.sourceEvent,t)},n?150:0)}}}function xd({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:i,zoomOnDoubleClick:a,userSelectionActive:o,noWheelClassName:s,noPanClassName:c,lib:l,connectionInProgress:u}){return d=>{let f=e||t,p=n&&d.ctrlKey,m=d.type===`wheel`;if(d.button===1&&d.type===`mousedown`&&(dd(d,`${l}-flow__node`)||dd(d,`${l}-flow__edge`)))return!0;if(!r&&!f&&!i&&!a&&!n||o||u&&!m||dd(d,s)&&m||dd(d,c)&&(!m||i&&m&&!e)||!n&&d.ctrlKey&&m)return!1;if(!n&&d.type===`touchstart`&&d.touches?.length>1)return d.preventDefault(),!1;if(!f&&!i&&!p&&m||!r&&(d.type===`mousedown`||d.type===`touchstart`)||Array.isArray(r)&&!r.includes(d.button)&&d.type===`mousedown`)return!1;let h=Array.isArray(r)&&r.includes(d.button)||!d.button||d.button<=1;return(!d.ctrlKey||m)&&h}}function Sd({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:i,onPanZoom:a,onPanZoomStart:o,onPanZoomEnd:s,onDraggingChange:c}){let l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{x:0,y:0,zoom:0},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},u=e.getBoundingClientRect(),d=Xc().scaleExtent([t,n]).translateExtent(r),f=va(e).call(d);v({x:i.x,y:i.y,zoom:xl(i.zoom,t,n)},[[0,0],[u.width,u.height]],r);let p=f.on(`wheel.zoom`),m=f.on(`dblclick.zoom`);d.wheelDelta(hd);function h(e,t){return f?new Promise(n=>{d?.interpolate(t?.interpolate===`linear`?Io:Xo).transform(md(f,t?.duration,t?.ease,()=>n(!0)),e)}):Promise.resolve(!1)}function g({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:n,userSelectionActive:r,panOnScroll:i,panOnDrag:u,panOnScrollMode:h,panOnScrollSpeed:g,preventScrolling:v,zoomOnPinch:y,zoomOnScroll:b,zoomOnDoubleClick:x,zoomActivationKeyPressed:S,lib:C,onTransformChange:w,connectionInProgress:T,paneClickDistance:E,selectionOnDrag:D}){r&&!l.isZoomingOrPanning&&_();let O=i&&!S&&!r;d.clickDistance(D?1/0:!Pl(E)||E<0?0:E);let k=O?gd({zoomPanValues:l,noWheelClassName:e,d3Selection:f,d3Zoom:d,panOnScrollMode:h,panOnScrollSpeed:g,zoomOnPinch:y,onPanZoomStart:o,onPanZoom:a,onPanZoomEnd:s}):_d({noWheelClassName:e,preventScrolling:v,d3ZoomHandler:p});if(f.on(`wheel.zoom`,k,{passive:!1}),!r){let e=vd({zoomPanValues:l,onDraggingChange:c,onPanZoomStart:o});d.on(`start`,e);let t=yd({zoomPanValues:l,panOnDrag:u,onPaneContextMenu:!!n,onPanZoom:a,onTransformChange:w});d.on(`zoom`,t);let r=bd({zoomPanValues:l,panOnDrag:u,panOnScroll:i,onPaneContextMenu:n,onPanZoomEnd:s,onDraggingChange:c});d.on(`end`,r)}let A=xd({zoomActivationKeyPressed:S,panOnDrag:u,zoomOnScroll:b,panOnScroll:i,zoomOnDoubleClick:x,zoomOnPinch:y,userSelectionActive:r,noPanClassName:t,noWheelClassName:e,lib:C,connectionInProgress:T});d.filter(A),x?f.on(`dblclick.zoom`,m):f.on(`dblclick.zoom`,null)}function _(){d.on(`zoom`,null)}async function v(e,t,n){let r=ud(e),i=d?.constrain()(r,t,n);return i&&await h(i),new Promise(e=>e(i))}async function y(e,t){let n=ud(e);return await h(n,t),new Promise(e=>e(n))}function b(e){if(f){let t=ud(e),n=f.property(`__zoom`);(n.k!==e.zoom||n.x!==e.x||n.y!==e.y)&&d?.transform(f,t,null,{sync:!0})}}function x(){let e=f?Vc(f.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}}function S(e,t){return f?new Promise(n=>{d?.interpolate(t?.interpolate===`linear`?Io:Xo).scaleTo(md(f,t?.duration,t?.ease,()=>n(!0)),e)}):Promise.resolve(!1)}function C(e,t){return f?new Promise(n=>{d?.interpolate(t?.interpolate===`linear`?Io:Xo).scaleBy(md(f,t?.duration,t?.ease,()=>n(!0)),e)}):Promise.resolve(!1)}function w(e){d?.scaleExtent(e)}function T(e){d?.translateExtent(e)}function E(e){let t=!Pl(e)||e<0?0:e;d?.clickDistance(t)}return{update:g,destroy:_,setViewport:y,setViewportConstrained:v,getViewport:x,scaleTo:S,scaleBy:C,setScaleExtent:w,setTranslateExtent:T,syncViewport:b,setClickDistance:E}}var Y;(function(e){e.Line=`line`,e.Handle=`handle`})(Y||={});function Cd({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:i,affectsY:a}){let o=e-t,s=n-r,c=[o>0?1:o<0?-1:0,s>0?1:s<0?-1:0];return o&&i&&(c[0]*=-1),s&&a&&(c[1]*=-1),c}function wd(e){return{isHorizontal:e.includes(`right`)||e.includes(`left`),isVertical:e.includes(`bottom`)||e.includes(`top`),affectsX:e.includes(`left`),affectsY:e.includes(`top`)}}function Td(e,t){return Math.max(0,t-e)}function Ed(e,t){return Math.max(0,e-t)}function Dd(e,t,n){return Math.max(0,t-e,e-n)}function Od(e,t){return e?!t:t}function kd(e,t,n,r,i,a,o,s){let{affectsX:c,affectsY:l}=t,{isHorizontal:u,isVertical:d}=t,f=u&&d,{xSnapped:p,ySnapped:m}=n,{minWidth:h,maxWidth:g,minHeight:_,maxHeight:v}=r,{x:y,y:b,width:x,height:S,aspectRatio:C}=e,w=Math.floor(u?p-e.pointerX:0),T=Math.floor(d?m-e.pointerY:0),E=x+(c?-w:w),D=S+(l?-T:T),O=-a[0]*x,k=-a[1]*S,A=Dd(E,h,g),j=Dd(D,_,v);if(o){let e=0,t=0;c&&w<0?e=Td(y+w+O,o[0][0]):!c&&w>0&&(e=Ed(y+E+O,o[1][0])),l&&T<0?t=Td(b+T+k,o[0][1]):!l&&T>0&&(t=Ed(b+D+k,o[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(s){let e=0,t=0;c&&w>0?e=Ed(y+w,s[0][0]):!c&&w<0&&(e=Td(y+E,s[1][0])),l&&T>0?t=Ed(b+T,s[0][1]):!l&&T<0&&(t=Td(b+D,s[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(i){if(u){let e=Dd(E/C,_,v)*C;if(A=Math.max(A,e),o){let e=0;e=!c&&!l||c&&!l&&f?Ed(b+k+E/C,o[1][1])*C:Td(b+k+(c?w:-w)/C,o[0][1])*C,A=Math.max(A,e)}if(s){let e=0;e=!c&&!l||c&&!l&&f?Td(b+E/C,s[1][1])*C:Ed(b+(c?w:-w)/C,s[0][1])*C,A=Math.max(A,e)}}if(d){let e=Dd(D*C,h,g)/C;if(j=Math.max(j,e),o){let e=0;e=!c&&!l||l&&!c&&f?Ed(y+D*C+O,o[1][0])/C:Td(y+(l?T:-T)*C+O,o[0][0])/C,j=Math.max(j,e)}if(s){let e=0;e=!c&&!l||l&&!c&&f?Td(y+D*C,s[1][0])/C:Ed(y+(l?T:-T)*C,s[0][0])/C,j=Math.max(j,e)}}}T+=T<0?j:-j,w+=w<0?A:-A,i&&(f?E>D*C?T=(Od(c,l)?-w:w)/C:w=(Od(c,l)?-T:T)*C:u?(T=w/C,l=c):(w=T*C,c=l));let M=c?y+w:y,N=l?b+T:b;return{width:x+(c?-w:w),height:S+(l?-T:T),x:a[0]*w*(c?-1:1)+M,y:a[1]*T*(l?-1:1)+N}}var Ad={width:0,height:0,x:0,y:0},jd={...Ad,pointerX:0,pointerY:0,aspectRatio:1};function Md(e){return[[0,0],[e.measured.width,e.measured.height]]}function Nd(e,t,n){let r=t.position.x+e.position.x,i=t.position.y+e.position.y,a=e.measured.width??0,o=e.measured.height??0,s=n[0]*a,c=n[1]*o;return[[r-s,i-c],[r+a-s,i+o-c]]}function Pd({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:i}){let a=va(e),o={controlDirection:wd(`bottom-right`),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function s({controlPosition:e,boundaries:s,keepAspectRatio:c,resizeDirection:l,onResizeStart:u,onResize:d,onResizeEnd:f,shouldResize:p}){let m={...Ad},h={...jd};o={boundaries:s,resizeDirection:l,keepAspectRatio:c,controlDirection:wd(e)};let g,_=null,v=[],y,b,x,S=!1,C=Na().on(`start`,e=>{let{nodeLookup:r,transform:i,snapGrid:a,snapToGrid:o,nodeOrigin:s,paneDomNode:c}=n();if(g=r.get(t),!g)return;_=c?.getBoundingClientRect()??null;let{xSnapped:l,ySnapped:d}=Xl(e.sourceEvent,{transform:i,snapGrid:a,snapToGrid:o,containerBounds:_});m={width:g.measured.width??0,height:g.measured.height??0,x:g.position.x??0,y:g.position.y??0},h={...m,pointerX:l,pointerY:d,aspectRatio:m.width/m.height},y=void 0,g.parentId&&(g.extent===`parent`||g.expandParent)&&(y=r.get(g.parentId),b=y&&g.extent===`parent`?Md(y):void 0),v=[],x=void 0;for(let[e,n]of r)if(n.parentId===t&&(v.push({id:e,position:{...n.position},extent:n.extent}),n.extent===`parent`||n.expandParent)){let e=Nd(n,g,n.origin??s);x=x?[[Math.min(e[0][0],x[0][0]),Math.min(e[0][1],x[0][1])],[Math.max(e[1][0],x[1][0]),Math.max(e[1][1],x[1][1])]]:e}u?.(e,{...m})}).on(`drag`,e=>{let{transform:t,snapGrid:i,snapToGrid:a,nodeOrigin:s}=n(),c=Xl(e.sourceEvent,{transform:t,snapGrid:i,snapToGrid:a,containerBounds:_}),l=[];if(!g)return;let{x:u,y:f,width:C,height:w}=m,T={},E=g.origin??s,{width:D,height:O,x:k,y:A}=kd(h,o.controlDirection,c,o.boundaries,o.keepAspectRatio,E,b,x),j=D!==C,M=O!==w,N=k!==u&&j,ee=A!==f&&M;if(!N&&!ee&&!j&&!M)return;if((N||ee||E[0]===1||E[1]===1)&&(T.x=N?k:m.x,T.y=ee?A:m.y,m.x=T.x,m.y=T.y,v.length>0)){let e=k-u,t=A-f;for(let n of v)n.position={x:n.position.x-e+E[0]*(D-C),y:n.position.y-t+E[1]*(O-w)},l.push(n)}if((j||M)&&(T.width=j&&(!o.resizeDirection||o.resizeDirection===`horizontal`)?D:m.width,T.height=M&&(!o.resizeDirection||o.resizeDirection===`vertical`)?O:m.height,m.width=T.width,m.height=T.height),y&&g.expandParent){let e=E[0]*(T.width??0);T.x&&T.x{S&&=(f?.(e,{...m}),i?.({...m}),!1)});a.call(C)}function c(){a.on(`.drag`,null)}return{update:s,destroy:c}}var Fd=o((e=>{var t=d();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),Id=o(((e,t)=>{t.exports=Fd()})),Ld=o((e=>{var t=d(),n=Id();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),Rd=l(o(((e,t)=>{t.exports=Ld()}))(),1),zd=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e)),destroy:()=>{n.clear()}},o=t=e(r,i,a);return a},Bd=e=>e?zd(e):zd,{useDebugValue:Vd}=v.default,{useSyncExternalStoreWithSelector:Hd}=Rd.default,Ud=e=>e;function Wd(e,t=Ud,n){let r=Hd(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Vd(r),r}var Gd=(e,t)=>{let n=Bd(e),r=(e,r=t)=>Wd(n,e,r);return Object.assign(r,n),r},Kd=(e,t)=>e?Gd(e,t):Gd;function qd(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var Jd=h(),Yd=(0,v.createContext)(null),Xd=Yd.Provider,Zd=Zc.error001();function Qd(e,t){let n=(0,v.useContext)(Yd);if(n===null)throw Error(Zd);return Wd(n,e,t)}function $d(){let e=(0,v.useContext)(Yd);if(e===null)throw Error(Zd);return(0,v.useMemo)(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}var ef={display:`none`},tf={position:`absolute`,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0px, 0px, 0px, 0px)`,clipPath:`inset(100%)`},nf=`react-flow__node-desc`,rf=`react-flow__edge-desc`,af=`react-flow__aria-live`,of=e=>e.ariaLiveMessage,sf=e=>e.ariaLabelConfig;function cf({rfId:e}){let t=Qd(of);return(0,H.jsx)(`div`,{id:`${af}-${e}`,"aria-live":`assertive`,"aria-atomic":`true`,style:tf,children:t})}function lf({rfId:e,disableKeyboardA11y:t}){let n=Qd(sf);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{id:`${nf}-${e}`,style:ef,children:t?n[`node.a11yDescription.default`]:n[`node.a11yDescription.keyboardDisabled`]}),(0,H.jsx)(`div`,{id:`${rf}-${e}`,style:ef,children:n[`edge.a11yDescription.default`]}),!t&&(0,H.jsx)(cf,{rfId:e})]})}var uf=(0,v.forwardRef)(({position:e=`top-left`,children:t,className:n,style:r,...i},a)=>(0,H.jsx)(`div`,{className:pr([`react-flow__panel`,n,...`${e}`.split(`-`)]),style:r,ref:a,...i,children:t}));uf.displayName=`Panel`;function df({proOptions:e,position:t=`bottom-right`}){return e?.hideAttribution?null:(0,H.jsx)(uf,{position:t,className:`react-flow__attribution`,"data-message":`Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev`,children:(0,H.jsx)(`a`,{href:`https://reactflow.dev`,target:`_blank`,rel:`noopener noreferrer`,"aria-label":`React Flow attribution`,children:`React Flow`})})}var ff=e=>{let t=[],n=[];for(let[,n]of e.nodeLookup)n.selected&&t.push(n.internals.userNode);for(let[,t]of e.edgeLookup)t.selected&&n.push(t);return{selectedNodes:t,selectedEdges:n}},pf=e=>e.id;function mf(e,t){return qd(e.selectedNodes.map(pf),t.selectedNodes.map(pf))&&qd(e.selectedEdges.map(pf),t.selectedEdges.map(pf))}function hf({onSelectionChange:e}){let t=$d(),{selectedNodes:n,selectedEdges:r}=Qd(ff,mf);return(0,v.useEffect)(()=>{let i={nodes:n,edges:r};e?.(i),t.getState().onSelectionChangeHandlers.forEach(e=>e(i))},[n,r,e]),null}var gf=e=>!!e.onSelectionChangeHandlers;function _f({onSelectionChange:e}){let t=Qd(gf);return e||t?(0,H.jsx)(hf,{onSelectionChange:e}):null}var vf=[0,0],yf={x:0,y:0,zoom:1},bf=[...`nodes.edges.defaultNodes.defaultEdges.onConnect.onConnectStart.onConnectEnd.onClickConnectStart.onClickConnectEnd.nodesDraggable.autoPanOnNodeFocus.nodesConnectable.nodesFocusable.edgesFocusable.edgesReconnectable.elevateNodesOnSelect.elevateEdgesOnSelect.minZoom.maxZoom.nodeExtent.onNodesChange.onEdgesChange.elementsSelectable.connectionMode.snapGrid.snapToGrid.translateExtent.connectOnClick.defaultEdgeOptions.fitView.fitViewOptions.onNodesDelete.onEdgesDelete.onDelete.onNodeDrag.onNodeDragStart.onNodeDragStop.onSelectionDrag.onSelectionDragStart.onSelectionDragStop.onMoveStart.onMove.onMoveEnd.noPanClassName.nodeOrigin.autoPanOnConnect.autoPanOnNodeDrag.onError.connectionRadius.isValidConnection.selectNodesOnDrag.nodeDragThreshold.connectionDragThreshold.onBeforeDelete.debug.autoPanSpeed.ariaLabelConfig.zIndexMode`.split(`.`),`rfId`],xf=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),Sf={translateExtent:Qc,nodeOrigin:vf,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:`nopan`,rfId:`1`};function Cf(e){let{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:i,setTranslateExtent:a,setNodeExtent:o,reset:s,setDefaultNodesAndEdges:c}=Qd(xf,qd),l=$d();(0,v.useEffect)(()=>(c(e.defaultNodes,e.defaultEdges),()=>{u.current=Sf,s()}),[]);let u=(0,v.useRef)(Sf);return(0,v.useEffect)(()=>{for(let s of bf){let c=e[s];c!==u.current[s]&&e[s]!==void 0&&(s===`nodes`?t(c):s===`edges`?n(c):s===`minZoom`?r(c):s===`maxZoom`?i(c):s===`translateExtent`?a(c):s===`nodeExtent`?o(c):s===`ariaLabelConfig`?l.setState({ariaLabelConfig:Yl(c)}):s===`fitView`?l.setState({fitViewQueued:c}):s===`fitViewOptions`?l.setState({fitViewOptions:c}):l.setState({[s]:c}))}u.current=e},bf.map(t=>e[t])),null}function wf(){return typeof window>`u`||!window.matchMedia?null:window.matchMedia(`(prefers-color-scheme: dark)`)}function Tf(e){let[t,n]=(0,v.useState)(e===`system`?null:e);return(0,v.useEffect)(()=>{if(e!==`system`){n(e);return}let t=wf(),r=()=>n(t?.matches?`dark`:`light`);return r(),t?.addEventListener(`change`,r),()=>{t?.removeEventListener(`change`,r)}},[e]),t===null?wf()?.matches?`dark`:`light`:t}var Ef=typeof document<`u`?document:null;function Df(e=null,t={target:Ef,actInsideInputWithModifier:!0}){let[n,r]=(0,v.useState)(!1),i=(0,v.useRef)(!1),a=(0,v.useRef)(new Set([])),[o,s]=(0,v.useMemo)(()=>{if(e!==null){let t=(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`).map(e=>e.replace(`+`,` +`).replace(` + +`,` ++`).split(` +`));return[t,t.reduce((e,t)=>e.concat(...t),[])]}return[[],[]]},[e]);return(0,v.useEffect)(()=>{let n=t?.target??Ef,c=t?.actInsideInputWithModifier??!0;if(e!==null){let e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!c)&&eu(e))return!1;let n=kf(e.code,s);if(a.current.add(e[n]),Of(o,a.current,!1)){let n=e.composedPath?.()?.[0]||e.target,a=n?.nodeName===`BUTTON`||n?.nodeName===`A`;t.preventDefault!==!1&&(i.current||!a)&&e.preventDefault(),r(!0)}},l=e=>{let t=kf(e.code,s);Of(o,a.current,!0)?(r(!1),a.current.clear()):a.current.delete(e[t]),e.key===`Meta`&&a.current.clear(),i.current=!1},u=()=>{a.current.clear(),r(!1)};return n?.addEventListener(`keydown`,e),n?.addEventListener(`keyup`,l),window.addEventListener(`blur`,u),window.addEventListener(`contextmenu`,u),()=>{n?.removeEventListener(`keydown`,e),n?.removeEventListener(`keyup`,l),window.removeEventListener(`blur`,u),window.removeEventListener(`contextmenu`,u)}}},[e,r]),n}function Of(e,t,n){return e.filter(e=>n||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function kf(e,t){return t.includes(e)?`code`:`key`}var Af=()=>{let e=$d();return(0,v.useMemo)(()=>({zoomIn:t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomOut:t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomTo:(t,n)=>{let{panZoom:r}=e.getState();return r?r.scaleTo(t,{duration:n?.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{let{transform:[r,i,a],panZoom:o}=e.getState();return o?(await o.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??a},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{let[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{let{width:r,height:i,minZoom:a,maxZoom:o,panZoom:s}=e.getState(),c=Vl(t,r,i,a,o,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{let{transform:r,snapGrid:i,snapToGrid:a,domNode:o}=e.getState();if(!o)return t;let{x:s,y:c}=o.getBoundingClientRect(),l={x:t.x-s,y:t.y-c},u=n.snapGrid??i;return Ll(l,r,n.snapToGrid??a,u)},flowToScreenPosition:t=>{let{transform:n,domNode:r}=e.getState();if(!r)return t;let{x:i,y:a}=r.getBoundingClientRect(),o=Rl(t,n);return{x:o.x+i,y:o.y+a}}}),[])};function jf(e,t){let n=[],r=new Map,i=[];for(let t of e)if(t.type===`add`){i.push(t);continue}else if(t.type===`remove`||t.type===`replace`)r.set(t.id,[t]);else{let e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}for(let e of t){let t=r.get(e.id);if(!t){n.push(e);continue}if(t[0].type===`remove`)continue;if(t[0].type===`replace`){n.push({...t[0].item});continue}let i={...e};for(let e of t)Mf(e,i);n.push(i)}return i.length&&i.forEach(e=>{e.index===void 0?n.push({...e.item}):n.splice(e.index,0,{...e.item})}),n}function Mf(e,t){switch(e.type){case`select`:t.selected=e.selected;break;case`position`:e.position!==void 0&&(t.position=e.position),e.dragging!==void 0&&(t.dragging=e.dragging);break;case`dimensions`:e.dimensions!==void 0&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes===`width`)&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes===`height`)&&(t.height=e.dimensions.height))),typeof e.resizing==`boolean`&&(t.resizing=e.resizing);break}}function Nf(e,t){return jf(e,t)}function Pf(e,t){return jf(e,t)}function Ff(e,t){return{id:e,type:`select`,selected:t}}function If(e,t=new Set,n=!1){let r=[];for(let[i,a]of e){let e=t.has(i);!(a.selected===void 0&&!e)&&a.selected!==e&&(n&&(a.selected=e),r.push(Ff(a.id,e)))}return r}function Lf({items:e=[],lookup:t}){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let[r,i]of e.entries()){let e=t.get(i.id),a=e?.internals?.userNode??e;a!==void 0&&a!==i&&n.push({id:i.id,item:i,type:`replace`}),a===void 0&&n.push({item:i,type:`add`,index:r})}for(let[e]of t)r.get(e)===void 0&&n.push({id:e,type:`remove`});return n}function Rf(e){return{id:e.id,type:`remove`}}var zf=e=>ul(e),Bf=e=>ll(e);function Vf(e){return(0,v.forwardRef)(e)}var Hf=typeof window<`u`?v.useLayoutEffect:v.useEffect;function Uf(e){let[t,n]=(0,v.useState)(BigInt(0)),[r]=(0,v.useState)(()=>Wf(()=>n(e=>e+BigInt(1))));return Hf(()=>{let t=r.get();t.length&&(e(t),r.reset())},[t]),r}function Wf(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}var Gf=(0,v.createContext)(null);function Kf({children:e}){let t=$d(),n=Uf((0,v.useCallback)(e=>{let{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:a,nodeLookup:o,fitViewQueued:s,onNodesChangeMiddlewareMap:c}=t.getState(),l=n;for(let t of e)l=typeof t==`function`?t(l):t;let u=Lf({items:l,lookup:o});for(let e of c.values())u=e(u);i&&r(l),u.length>0?a?.(u):s&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:n,setNodes:r}=t.getState();e&&r(n)})},[])),r=Uf((0,v.useCallback)(e=>{let{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:a,edgeLookup:o}=t.getState(),s=n;for(let t of e)s=typeof t==`function`?t(s):t;i?r(s):a&&a(Lf({items:s,lookup:o}))},[])),i=(0,v.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,H.jsx)(Gf.Provider,{value:i,children:e})}function qf(){let e=(0,v.useContext)(Gf);if(!e)throw Error(`useBatchContext must be used within a BatchProvider`);return e}var Jf=e=>!!e.panZoom;function Yf(){let e=Af(),t=$d(),n=qf(),r=Qd(Jf),i=(0,v.useMemo)(()=>{let e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},a=e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState(),i=zf(e)?e:n.get(e.id),a=i.parentId?Kl(i.position,i.measured,i.parentId,n,r):i.position;return kl({...i,position:a,width:i.measured?.width??i.width,height:i.measured?.height??i.height})},o=(e,t,n={replace:!1})=>{r(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&zf(e)?e:{...r,...e}}return r}))},s=(e,t,n={replace:!1})=>{i(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&Bf(e)?e:{...r,...e}}return r}))};return{getNodes:()=>t.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=t.getState();return e.map(e=>({...e}))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{let t=Array.isArray(e)?e:[e];n.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];n.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,a,o]=r;return{nodes:e.map(e=>({...e})),edges:n.map(e=>({...e})),viewport:{x:i,y:a,zoom:o}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{let{nodes:r,edges:i,onNodesDelete:a,onEdgesDelete:o,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:l,onBeforeDelete:u}=t.getState(),{nodes:d,edges:f}=await bl({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:u}),p=f.length>0,m=d.length>0;if(p){let e=f.map(Rf);o?.(f),c(e)}if(m){let e=d.map(Rf);a?.(d),s(e)}return(m||p)&&l?.({nodes:d,edges:f}),{deletedNodes:d,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{let i=Nl(e),o=i?e:a(e),s=r!==void 0;return o?(r||t.getState().nodes).filter(r=>{let a=t.getState().nodeLookup.get(r.id);if(a&&!i&&(r.id===e.id||!a.internals.positionAbsolute))return!1;let c=kl(s?r:a),l=Ml(c,o);return n&&l>0||l>=c.width*c.height||l>=o.width*o.height}):[]},isNodeIntersecting:(e,t,n=!0)=>{let r=Nl(e)?e:a(e);if(!r)return!1;let i=Ml(r,t);return n&&i>0||i>=t.width*t.height||i>=r.width*r.height},updateNode:o,updateNodeData:(e,t,n={replace:!1})=>{o(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},getNodesBounds:e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState();return pl(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:``}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:``}`)?.values()??[]),fitView:async e=>{let r=t.getState().fitViewResolver??Jl();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push(e=>[...e]),r.promise}}},[]);return(0,v.useMemo)(()=>({...i,...e,viewportInitialized:r}),[r])}var Xf=e=>e.selected,Zf=typeof window<`u`?window:void 0;function Qf({deleteKeyCode:e,multiSelectionKeyCode:t}){let n=$d(),{deleteElements:r}=Yf(),i=Df(e,{actInsideInputWithModifier:!1}),a=Df(t,{target:Zf});(0,v.useEffect)(()=>{if(i){let{edges:e,nodes:t}=n.getState();r({nodes:t.filter(Xf),edges:e.filter(Xf)}),n.setState({nodesSelectionActive:!1})}},[i]),(0,v.useEffect)(()=>{n.setState({multiSelectionActive:a})},[a])}function $f(e){let t=$d();(0,v.useEffect)(()=>{let n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;let n=Zl(e.current);(n.height===0||n.width===0)&&t.getState().onError?.(`004`,Zc.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener(`resize`,n);let t=new ResizeObserver(()=>n());return t.observe(e.current),()=>{window.removeEventListener(`resize`,n),t&&e.current&&t.unobserve(e.current)}}},[])}var ep={position:`absolute`,width:`100%`,height:`100%`,top:0,left:0},tp=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function np({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:i=.5,panOnScrollMode:a=nl.Free,zoomOnDoubleClick:o=!0,panOnDrag:s=!0,defaultViewport:c,translateExtent:l,minZoom:u,maxZoom:d,zoomActivationKeyCode:f,preventScrolling:p=!0,children:m,noWheelClassName:h,noPanClassName:g,onViewportChange:_,isControlledViewport:y,paneClickDistance:b,selectionOnDrag:x}){let S=$d(),C=(0,v.useRef)(null),{userSelectionActive:w,lib:T,connectionInProgress:E}=Qd(tp,qd),D=Df(f),O=(0,v.useRef)();$f(C);let k=(0,v.useCallback)(e=>{_?.({x:e[0],y:e[1],zoom:e[2]}),y||S.setState({transform:e})},[_,y]);return(0,v.useEffect)(()=>{if(C.current){O.current=Sd({domNode:C.current,minZoom:u,maxZoom:d,translateExtent:l,viewport:c,onDraggingChange:e=>S.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:n,onMoveStart:r}=S.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:n,onMove:r}=S.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:n,onMoveEnd:r}=S.getState();r?.(e,t),n?.(t)}});let{x:e,y:t,zoom:n}=O.current.getViewport();return S.setState({panZoom:O.current,transform:[e,t,n],domNode:C.current.closest(`.react-flow`)}),()=>{O.current?.destroy()}}},[]),(0,v.useEffect)(()=>{O.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:i,panOnScrollMode:a,zoomOnDoubleClick:o,panOnDrag:s,zoomActivationKeyPressed:D,preventScrolling:p,noPanClassName:g,userSelectionActive:w,noWheelClassName:h,lib:T,onTransformChange:k,connectionInProgress:E,selectionOnDrag:x,paneClickDistance:b})},[e,t,n,r,i,a,o,s,D,p,g,w,h,T,k,E,x,b]),(0,H.jsx)(`div`,{className:`react-flow__renderer`,ref:C,style:ep,children:m})}var rp=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function ip(){let{userSelectionActive:e,userSelectionRect:t}=Qd(rp,qd);return e&&t?(0,H.jsx)(`div`,{className:`react-flow__selection react-flow__container`,style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var ap=(e,t)=>n=>{n.target===t.current&&e?.(n)},op=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function sp({isSelecting:e,selectionKeyPressed:t,selectionMode:n=rl.Full,panOnDrag:r,paneClickDistance:i,selectionOnDrag:a,onSelectionStart:o,onSelectionEnd:s,onPaneClick:c,onPaneContextMenu:l,onPaneScroll:u,onPaneMouseEnter:d,onPaneMouseMove:f,onPaneMouseLeave:p,children:m}){let h=$d(),{userSelectionActive:g,elementsSelectable:_,dragging:y,connectionInProgress:b}=Qd(op,qd),x=_&&(e||g),S=(0,v.useRef)(null),C=(0,v.useRef)(),w=(0,v.useRef)(new Set),T=(0,v.useRef)(new Set),E=(0,v.useRef)(!1),D=e=>{if(E.current||b){E.current=!1;return}c?.(e),h.getState().resetSelectedElements(),h.setState({nodesSelectionActive:!1})},O=e=>{if(Array.isArray(r)&&r?.includes(2)){e.preventDefault();return}l?.(e)},k=u?e=>u(e):void 0;return(0,H.jsxs)(`div`,{className:pr([`react-flow__pane`,{draggable:r===!0||Array.isArray(r)&&r.includes(0),dragging:y,selection:e}]),onClick:x?void 0:ap(D,S),onContextMenu:ap(O,S),onWheel:ap(k,S),onPointerEnter:x?void 0:d,onPointerMove:x?e=>{let{userSelectionRect:r,transform:a,nodeLookup:s,edgeLookup:c,connectionLookup:l,triggerNodeChanges:u,triggerEdgeChanges:d,defaultEdgeOptions:f,resetSelectedElements:p}=h.getState();if(!C.current||!r)return;let{x:m,y:g}=nu(e.nativeEvent,C.current),{startX:_,startY:v}=r;if(!E.current){let n=t?0:i;if(Math.hypot(m-_,g-v)<=n)return;p(),o?.(e)}E.current=!0;let y={startX:_,startY:v,x:m<_?m:_,y:ge.id)),T.current=new Set;let S=f?.selectable??!0;for(let e of w.current){let t=l.get(e);if(t)for(let{edgeId:e}of t.values()){let t=c.get(e);t&&(t.selectable??S)&&T.current.add(e)}}ql(b,w.current)||u(If(s,w.current,!0)),ql(x,T.current)||d(If(c,T.current)),h.setState({userSelectionRect:y,userSelectionActive:!0,nodesSelectionActive:!1})}:f,onPointerUp:x?e=>{e.button===0&&(e.target?.releasePointerCapture?.(e.pointerId),!g&&e.target===S.current&&h.getState().userSelectionRect&&D?.(e),h.setState({userSelectionActive:!1,userSelectionRect:null}),E.current&&(s?.(e),h.setState({nodesSelectionActive:w.current.size>0})))}:void 0,onPointerDownCapture:x?n=>{let{domNode:r}=h.getState();if(C.current=r?.getBoundingClientRect(),!C.current)return;let i=n.target===S.current;if(!i&&n.target.closest(`.nokey`)||!e||!(a&&i||t)||n.button!==0||!n.isPrimary)return;n.target?.setPointerCapture?.(n.pointerId),E.current=!1;let{x:o,y:s}=nu(n.nativeEvent,C.current);h.setState({userSelectionRect:{width:0,height:0,startX:o,startY:s,x:o,y:s}}),i||(n.stopPropagation(),n.preventDefault())}:void 0,onClickCapture:x?e=>{E.current&&=(e.stopPropagation(),!1)}:void 0,onPointerLeave:p,ref:S,style:ep,children:[m,(0,H.jsx)(ip,{})]})}function cp({id:e,store:t,unselect:n=!1,nodeRef:r}){let{addSelectedNodes:i,unselectNodesAndEdges:a,multiSelectionActive:o,nodeLookup:s,onError:c}=t.getState(),l=s.get(e);if(!l){c?.(`012`,Zc.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&o)&&(a({nodes:[l],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):i([e])}function lp({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:a,nodeClickDistance:o}){let s=$d(),[c,l]=(0,v.useState)(!1),u=(0,v.useRef)();return(0,v.useEffect)(()=>{u.current=Zu({getStoreItems:()=>s.getState(),onNodeMouseDown:t=>{cp({id:t,store:s,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}})},[]),(0,v.useEffect)(()=>{if(!(t||!e.current||!u.current))return u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:a,nodeId:i,nodeClickDistance:o}),()=>{u.current?.destroy()}},[n,r,t,a,e,i,o]),c}var up=e=>t=>t.selected&&(t.draggable||e&&t.draggable===void 0);function dp(){let e=$d();return(0,v.useCallback)(t=>{let{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:a,onError:o,updateNodePositions:s,nodeLookup:c,nodeOrigin:l}=e.getState(),u=new Map,d=up(a),f=r?i[0]:5,p=r?i[1]:5,m=t.direction.x*f*t.factor,h=t.direction.y*p*t.factor;for(let[,e]of c){if(!d(e))continue;let t={x:e.internals.positionAbsolute.x+m,y:e.internals.positionAbsolute.y+h};r&&(t=Il(t,i));let{position:a,positionAbsolute:s}=yl({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:l,onError:o});e.position=a,e.internals.positionAbsolute=s,u.set(e.id,e)}s(u)},[])}var fp=(0,v.createContext)(null),pp=fp.Provider;fp.Consumer;var mp=()=>(0,v.useContext)(fp),hp=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),gp=(e,t,n)=>r=>{let{connectionClickStartHandle:i,connectionMode:a,connection:o}=r,{fromHandle:s,toHandle:c,isValid:l}=o,u=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:u,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:a===tl.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:u&&l}};function _p({type:e=`source`,position:t=q.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:a=!0,id:o,onConnect:s,children:c,className:l,onMouseDown:u,onTouchStart:d,...f},p){let m=o||null,h=e===`target`,g=$d(),_=mp(),{connectOnClick:v,noPanClassName:y,rfId:b}=Qd(hp,qd),{connectingFrom:x,connectingTo:S,clickConnecting:C,isPossibleEndHandle:w,connectionInProcess:T,clickConnectionInProcess:E,valid:D}=Qd(gp(_,m,e),qd);_||g.getState().onError?.(`010`,Zc.error010());let O=e=>{let{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=g.getState(),i={...t,...e};if(r){let{edges:e,setEdges:t}=g.getState();t(pu(i,e))}n?.(i),s?.(i)},k=e=>{if(!_)return;let t=tu(e.nativeEvent);if(i&&(t&&e.button===0||!t)){let t=g.getState();sd.onPointerDown(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:h,handleId:m,nodeId:_,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>g.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:O,isValidConnection:n||((...e)=>g.getState().isValidConnection?.(...e)??!0),getTransform:()=>g.getState().transform,getFromHandle:()=>g.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?u?.(e):d?.(e)};return(0,H.jsx)(`div`,{"data-handleid":m,"data-nodeid":_,"data-handlepos":t,"data-id":`${b}-${_}-${m}-${e}`,className:pr([`react-flow__handle`,`react-flow__handle-${t}`,`nodrag`,y,l,{source:!h,target:h,connectable:r,connectablestart:i,connectableend:a,clickconnecting:C,connectingfrom:x,connectingto:S,valid:D,connectionindicator:r&&(!T||w)&&(T||E?a:i)}]),onMouseDown:k,onTouchStart:k,onClick:v?t=>{let{onClickConnectStart:r,onClickConnectEnd:a,connectionClickStartHandle:o,connectionMode:s,isValidConnection:c,lib:l,rfId:u,nodeLookup:d,connection:f}=g.getState();if(!_||!o&&!i)return;if(!o){r?.(t.nativeEvent,{nodeId:_,handleId:m,handleType:e}),g.setState({connectionClickStartHandle:{nodeId:_,type:e,id:m}});return}let p=Ql(t.target),h=n||c,{connection:v,isValid:y}=sd.isValid(t.nativeEvent,{handle:{nodeId:_,id:m,type:e},connectionMode:s,fromNodeId:o.nodeId,fromHandleId:o.id||null,fromType:o.type,isValidConnection:h,flowId:u,doc:p,lib:l,nodeLookup:d});y&&v&&O(v);let b=structuredClone(f);delete b.inProgress,b.toPosition=b.toHandle?b.toHandle.position:null,a?.(t,b),g.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f,children:c})}var vp=(0,v.memo)(Vf(_p));function yp({data:e,isConnectable:t,sourcePosition:n=q.Bottom}){return(0,H.jsxs)(H.Fragment,{children:[e?.label,(0,H.jsx)(vp,{type:`source`,position:n,isConnectable:t})]})}function bp({data:e,isConnectable:t,targetPosition:n=q.Top,sourcePosition:r=q.Bottom}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:n,isConnectable:t}),e?.label,(0,H.jsx)(vp,{type:`source`,position:r,isConnectable:t})]})}function xp(){return null}function Sp({data:e,isConnectable:t,targetPosition:n=q.Top}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:n,isConnectable:t}),e?.label]})}var Cp={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},wp={input:yp,default:bp,output:Sp,group:xp};function Tp(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}var Ep=e=>{let{width:t,height:n,x:r,y:i}=ml(e.nodeLookup,{filter:e=>!!e.selected});return{width:Pl(t)?t:null,height:Pl(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function Dp({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){let r=$d(),{width:i,height:a,transformString:o,userSelectionActive:s}=Qd(Ep,qd),c=dp(),l=(0,v.useRef)(null);(0,v.useEffect)(()=>{n||l.current?.focus({preventScroll:!0})},[n]);let u=!s&&i!==null&&a!==null;if(lp({nodeRef:l,disabled:!u}),!u)return null;let d=e?t=>{e(t,r.getState().nodes.filter(e=>e.selected))}:void 0;return(0,H.jsx)(`div`,{className:pr([`react-flow__nodesselection`,`react-flow__container`,t]),style:{transform:o},children:(0,H.jsx)(`div`,{ref:l,className:`react-flow__nodesselection-rect`,onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(Cp,e.key)&&(e.preventDefault(),c({direction:Cp[e.key],factor:e.shiftKey?4:1}))},style:{width:i,height:a}})})}var Op=typeof window<`u`?window:void 0,kp=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function Ap({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,paneClickDistance:s,deleteKeyCode:c,selectionKeyCode:l,selectionOnDrag:u,selectionMode:d,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:g,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:b,panOnScrollSpeed:x,panOnScrollMode:S,zoomOnDoubleClick:C,panOnDrag:w,defaultViewport:T,translateExtent:E,minZoom:D,maxZoom:O,preventScrolling:k,onSelectionContextMenu:A,noWheelClassName:j,noPanClassName:M,disableKeyboardA11y:N,onViewportChange:ee,isControlledViewport:te}){let{nodesSelectionActive:P,userSelectionActive:F}=Qd(kp,qd),ne=Df(l,{target:Op}),re=Df(h,{target:Op}),ie=re||w,ae=re||b,I=u&&ie!==!0,L=ne||F||I;return Qf({deleteKeyCode:c,multiSelectionKeyCode:m}),(0,H.jsx)(np,{onPaneContextMenu:a,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:ae,panOnScrollSpeed:x,panOnScrollMode:S,zoomOnDoubleClick:C,panOnDrag:!ne&&ie,defaultViewport:T,translateExtent:E,minZoom:D,maxZoom:O,zoomActivationKeyCode:g,preventScrolling:k,noWheelClassName:j,noPanClassName:M,onViewportChange:ee,isControlledViewport:te,paneClickDistance:s,selectionOnDrag:I,children:(0,H.jsxs)(sp,{onSelectionStart:f,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,panOnDrag:ie,isSelecting:!!L,selectionMode:d,selectionKeyPressed:ne,paneClickDistance:s,selectionOnDrag:I,children:[e,P&&(0,H.jsx)(Dp,{onSelectionContextMenu:A,noPanClassName:M,disableKeyboardA11y:N})]})})}Ap.displayName=`FlowRenderer`;var jp=(0,v.memo)(Ap),Mp=e=>t=>e?hl(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(e=>e.id):Array.from(t.nodeLookup.keys());function Np(e){return Qd((0,v.useCallback)(Mp(e),[e]),qd)}var Pp=e=>e.updateNodeInternals;function Fp(){let e=Qd(Pp),[t]=(0,v.useState)(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(t=>{let n=new Map;t.forEach(e=>{let t=e.target.getAttribute(`data-id`);n.set(t,{id:t,nodeElement:e.target,force:!0})}),e(n)}));return(0,v.useEffect)(()=>()=>{t?.disconnect()},[t]),t}function Ip({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){let i=$d(),a=(0,v.useRef)(null),o=(0,v.useRef)(null),s=(0,v.useRef)(e.sourcePosition),c=(0,v.useRef)(e.targetPosition),l=(0,v.useRef)(t),u=n&&!!e.internals.handleBounds;return(0,v.useEffect)(()=>{a.current&&!e.hidden&&(!u||o.current!==a.current)&&(o.current&&r?.unobserve(o.current),r?.observe(a.current),o.current=a.current)},[u,e.hidden]),(0,v.useEffect)(()=>()=>{o.current&&=(r?.unobserve(o.current),null)},[]),(0,v.useEffect)(()=>{if(a.current){let n=l.current!==t,r=s.current!==e.sourcePosition,o=c.current!==e.targetPosition;(n||r||o)&&(l.current=t,s.current=e.sourcePosition,c.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:a.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),a}function Lp({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:i,onContextMenu:a,onDoubleClick:o,nodesDraggable:s,elementsSelectable:c,nodesConnectable:l,nodesFocusable:u,resizeObserver:d,noDragClassName:f,noPanClassName:p,disableKeyboardA11y:m,rfId:h,nodeTypes:g,nodeClickDistance:_,onError:v}){let{node:y,internals:b,isParent:x}=Qd(t=>{let n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}},qd),S=y.type||`default`,C=g?.[S]||wp[S];C===void 0&&(v?.(`003`,Zc.error003(S)),S=`default`,C=g?.default||wp.default);let w=!!(y.draggable||s&&y.draggable===void 0),T=!!(y.selectable||c&&y.selectable===void 0),E=!!(y.connectable||l&&y.connectable===void 0),D=!!(y.focusable||u&&y.focusable===void 0),O=$d(),k=Gl(y),A=Ip({node:y,nodeType:S,hasDimensions:k,resizeObserver:d}),j=lp({nodeRef:A,disabled:y.hidden||!w,noDragClassName:f,handleSelector:y.dragHandle,nodeId:e,isSelectable:T,nodeClickDistance:_}),M=dp();if(y.hidden)return null;let N=Wl(y),ee=Tp(y),te=T||w||t||n||r||i,P=n?e=>n(e,{...b.userNode}):void 0,F=r?e=>r(e,{...b.userNode}):void 0,ne=i?e=>i(e,{...b.userNode}):void 0,re=a?e=>a(e,{...b.userNode}):void 0,ie=o?e=>o(e,{...b.userNode}):void 0,ae=n=>{let{selectNodesOnDrag:r,nodeDragThreshold:i}=O.getState();T&&(!r||!w||i>0)&&cp({id:e,store:O,nodeRef:A}),t&&t(n,{...b.userNode})},I=t=>{if(!(eu(t.nativeEvent)||m)){if($c.includes(t.key)&&T)cp({id:e,store:O,unselect:t.key===`Escape`,nodeRef:A});else if(w&&y.selected&&Object.prototype.hasOwnProperty.call(Cp,t.key)){t.preventDefault();let{ariaLabelConfig:e}=O.getState();O.setState({ariaLiveMessage:e[`node.a11yDescription.ariaLiveMessage`]({direction:t.key.replace(`Arrow`,``).toLowerCase(),x:~~b.positionAbsolute.x,y:~~b.positionAbsolute.y})}),M({direction:Cp[t.key],factor:t.shiftKey?4:1})}}},L=()=>{if(m||!A.current?.matches(`:focus-visible`))return;let{transform:t,width:n,height:r,autoPanOnNodeFocus:i,setCenter:a}=O.getState();i&&(hl(new Map([[e,y]]),{x:0,y:0,width:n,height:r},t,!0).length>0||a(y.position.x+N.width/2,y.position.y+N.height/2,{zoom:t[2]}))};return(0,H.jsx)(`div`,{className:pr([`react-flow__node`,`react-flow__node-${S}`,{[p]:w},y.className,{selected:y.selected,selectable:T,parent:x,draggable:w,dragging:j}]),ref:A,style:{zIndex:b.z,transform:`translate(${b.positionAbsolute.x}px,${b.positionAbsolute.y}px)`,pointerEvents:te?`all`:`none`,visibility:k?`visible`:`hidden`,...y.style,...ee},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:P,onMouseMove:F,onMouseLeave:ne,onContextMenu:re,onClick:ae,onDoubleClick:ie,onKeyDown:D?I:void 0,tabIndex:D?0:void 0,onFocus:D?L:void 0,role:y.ariaRole??(D?`group`:void 0),"aria-roledescription":`node`,"aria-describedby":m?void 0:`${nf}-${h}`,"aria-label":y.ariaLabel,...y.domAttributes,children:(0,H.jsx)(pp,{value:e,children:(0,H.jsx)(C,{id:e,data:y.data,type:S,positionAbsoluteX:b.positionAbsolute.x,positionAbsoluteY:b.positionAbsolute.y,selected:y.selected??!1,selectable:T,draggable:w,deletable:y.deletable??!0,isConnectable:E,sourcePosition:y.sourcePosition,targetPosition:y.targetPosition,dragging:j,dragHandle:y.dragHandle,zIndex:b.z,parentId:y.parentId,...N})})})}var Rp=(0,v.memo)(Lp),zp=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function Bp(e){let{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,onError:a}=Qd(zp,qd),o=Np(e.onlyRenderVisibleElements),s=Fp();return(0,H.jsx)(`div`,{className:`react-flow__nodes`,style:ep,children:o.map(o=>(0,H.jsx)(Rp,{id:o,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:s,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,nodeClickDistance:e.nodeClickDistance,onError:a},o))})}Bp.displayName=`NodeRenderer`;var Vp=(0,v.memo)(Bp);function Hp(e){return Qd((0,v.useCallback)(t=>{if(!e)return t.edges.map(e=>e.id);let n=[];if(t.width&&t.height)for(let e of t.edges){let r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&uu({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n},[e]),qd)}var Up=({color:e=`none`,strokeWidth:t=1})=>(0,H.jsx)(`polyline`,{className:`arrow`,style:{strokeWidth:t,...e&&{stroke:e}},strokeLinecap:`round`,fill:`none`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4`}),Wp=({color:e=`none`,strokeWidth:t=1})=>(0,H.jsx)(`polyline`,{className:`arrowclosed`,style:{strokeWidth:t,...e&&{stroke:e,fill:e}},strokeLinecap:`round`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4 -5,-4`}),Gp={[ol.Arrow]:Up,[ol.ArrowClosed]:Wp};function Kp(e){let t=$d();return(0,v.useMemo)(()=>Object.prototype.hasOwnProperty.call(Gp,e)?Gp[e]:(t.getState().onError?.(`009`,Zc.error009(e)),null),[e])}var qp=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:a=`strokeWidth`,strokeWidth:o,orient:s=`auto-start-reverse`})=>{let c=Kp(t);return c?(0,H.jsx)(`marker`,{className:`react-flow__arrowhead`,id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:`-10 -10 20 20`,markerUnits:a,orient:s,refX:`0`,refY:`0`,children:(0,H.jsx)(c,{color:n,strokeWidth:o})}):null},Jp=({defaultColor:e,rfId:t})=>{let n=Qd(e=>e.edges),r=Qd(e=>e.defaultEdgeOptions),i=(0,v.useMemo)(()=>Du(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return i.length?(0,H.jsx)(`svg`,{className:`react-flow__marker`,"aria-hidden":`true`,children:(0,H.jsx)(`defs`,{children:i.map(e=>(0,H.jsx)(qp,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};Jp.displayName=`MarkerDefinitions`;var Yp=(0,v.memo)(Jp);function Xp({x:e,y:t,label:n,labelStyle:r,labelShowBg:i=!0,labelBgStyle:a,labelBgPadding:o=[2,4],labelBgBorderRadius:s=2,children:c,className:l,...u}){let[d,f]=(0,v.useState)({x:1,y:0,width:0,height:0}),p=pr([`react-flow__edge-textwrapper`,l]),m=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(m.current){let e=m.current.getBBox();f({x:e.x,y:e.y,width:e.width,height:e.height})}},[n]),n?(0,H.jsxs)(`g`,{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?`visible`:`hidden`,...u,children:[i&&(0,H.jsx)(`rect`,{width:d.width+2*o[0],x:-o[0],y:-o[1],height:d.height+2*o[1],className:`react-flow__edge-textbg`,style:a,rx:s,ry:s}),(0,H.jsx)(`text`,{className:`react-flow__edge-text`,y:d.height/2,dy:`0.3em`,ref:m,style:r,children:n}),c]}):null}Xp.displayName=`EdgeText`;var Zp=(0,v.memo)(Xp);function Qp({path:e,labelX:t,labelY:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c,interactionWidth:l=20,...u}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`path`,{...u,d:e,fill:`none`,className:pr([`react-flow__edge-path`,u.className])}),l?(0,H.jsx)(`path`,{d:e,fill:`none`,strokeOpacity:0,strokeWidth:l,className:`react-flow__edge-interaction`}):null,r&&Pl(t)&&Pl(n)?(0,H.jsx)(Zp,{x:t,y:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c}):null]})}function $p({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===q.Left||e===q.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function em({sourceX:e,sourceY:t,sourcePosition:n=q.Bottom,targetX:r,targetY:i,targetPosition:a=q.Top}){let[o,s]=$p({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,l]=$p({pos:a,x1:r,y1:i,x2:e,y2:t}),[u,d,f,p]=iu({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:o,sourceControlY:s,targetControlX:c,targetControlY:l});return[`M${e},${t} C${o},${s} ${c},${l} ${r},${i}`,u,d,f,p]}function tm(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o,targetPosition:s,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})=>{let[v,y,b]=em({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s});return(0,H.jsx)(Qp,{id:e.isInternal?void 0:t,path:v,labelX:y,labelY:b,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})})}var nm=tm({isInternal:!1}),rm=tm({isInternal:!0});nm.displayName=`SimpleBezierEdge`,rm.displayName=`SimpleBezierEdgeInternal`;function im(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,sourcePosition:p=q.Bottom,targetPosition:m=q.Top,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,x]=bu({sourceX:n,sourceY:r,sourcePosition:p,targetX:i,targetY:a,targetPosition:m,borderRadius:_?.borderRadius,offset:_?.offset,stepPosition:_?.stepPosition});return(0,H.jsx)(Qp,{id:e.isInternal?void 0:t,path:y,labelX:b,labelY:x,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:g,interactionWidth:v})})}var am=im({isInternal:!1}),om=im({isInternal:!0});am.displayName=`SmoothStepEdge`,om.displayName=`SmoothStepEdgeInternal`;function sm(e){return(0,v.memo)(({id:t,...n})=>{let r=e.isInternal?void 0:t;return(0,H.jsx)(am,{...n,id:r,pathOptions:(0,v.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}var cm=sm({isInternal:!1}),lm=sm({isInternal:!0});cm.displayName=`StepEdge`,lm.displayName=`StepEdgeInternal`;function um(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})=>{let[g,_,v]=mu({sourceX:n,sourceY:r,targetX:i,targetY:a});return(0,H.jsx)(Qp,{id:e.isInternal?void 0:t,path:g,labelX:_,labelY:v,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})})}var dm=um({isInternal:!1}),fm=um({isInternal:!0});dm.displayName=`StraightEdge`,fm.displayName=`StraightEdgeInternal`;function pm(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o=q.Bottom,targetPosition:s=q.Top,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,x]=su({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s,curvature:_?.curvature});return(0,H.jsx)(Qp,{id:e.isInternal?void 0:t,path:y,labelX:b,labelY:x,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:v})})}var mm=pm({isInternal:!1}),hm=pm({isInternal:!0});mm.displayName=`BezierEdge`,hm.displayName=`BezierEdgeInternal`;var gm={default:hm,straight:fm,step:lm,smoothstep:om,simplebezier:rm},_m={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},vm=(e,t,n)=>n===q.Left?e-t:n===q.Right?e+t:e,ym=(e,t,n)=>n===q.Top?e-t:n===q.Bottom?e+t:e,bm=`react-flow__edgeupdater`;function xm({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:a,onMouseOut:o,type:s}){return(0,H.jsx)(`circle`,{onMouseDown:i,onMouseEnter:a,onMouseOut:o,className:pr([bm,`${bm}-${s}`]),cx:vm(t,r,e),cy:ym(n,r,e),r,stroke:`transparent`,fill:`transparent`})}function Sm({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:i,targetX:a,targetY:o,sourcePosition:s,targetPosition:c,onReconnect:l,onReconnectStart:u,onReconnectEnd:d,setReconnecting:f,setUpdateHover:p}){let m=$d(),h=(e,t)=>{if(e.button!==0)return;let{autoPanOnConnect:r,domNode:i,connectionMode:a,connectionRadius:o,lib:s,onConnectStart:c,cancelConnection:p,nodeLookup:h,rfId:g,panBy:_,updateConnection:v}=m.getState(),y=t.type===`target`;sd.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:o,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:h,isTarget:y,edgeUpdaterType:t.type,lib:s,flowId:g,cancelConnection:p,panBy:_,isValidConnection:(...e)=>m.getState().isValidConnection?.(...e)??!0,onConnect:e=>l?.(n,e),onConnectStart:(r,i)=>{f(!0),u?.(e,n,t.type),c?.(r,i)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,r)=>{f(!1),d?.(e,n,t.type,r)},updateConnection:v,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},g=e=>h(e,{nodeId:n.target,id:n.targetHandle??null,type:`target`}),_=e=>h(e,{nodeId:n.source,id:n.sourceHandle??null,type:`source`}),v=()=>p(!0),y=()=>p(!1);return(0,H.jsxs)(H.Fragment,{children:[(e===!0||e===`source`)&&(0,H.jsx)(xm,{position:s,centerX:r,centerY:i,radius:t,onMouseDown:g,onMouseEnter:v,onMouseOut:y,type:`source`}),(e===!0||e===`target`)&&(0,H.jsx)(xm,{position:c,centerX:a,centerY:o,radius:t,onMouseDown:_,onMouseEnter:v,onMouseOut:y,type:`target`})]})}function Cm({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:i,onDoubleClick:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,rfId:m,edgeTypes:h,noPanClassName:g,onError:_,disableKeyboardA11y:y}){let b=Qd(t=>t.edgeLookup.get(e)),x=Qd(e=>e.defaultEdgeOptions);b=x?{...x,...b}:b;let S=b.type||`default`,C=h?.[S]||gm[S];C===void 0&&(_?.(`011`,Zc.error011(S)),S=`default`,C=h?.default||gm.default);let w=!!(b.focusable||t&&b.focusable===void 0),T=d!==void 0&&(b.reconnectable||n&&b.reconnectable===void 0),E=!!(b.selectable||r&&b.selectable===void 0),D=(0,v.useRef)(null),[O,k]=(0,v.useState)(!1),[A,j]=(0,v.useState)(!1),M=$d(),{zIndex:N,sourceX:ee,sourceY:te,targetX:P,targetY:F,sourcePosition:ne,targetPosition:re}=Qd((0,v.useCallback)(t=>{let n=t.nodeLookup.get(b.source),r=t.nodeLookup.get(b.target);if(!n||!r)return{zIndex:b.zIndex,..._m};let i=Su({id:e,sourceNode:n,targetNode:r,sourceHandle:b.sourceHandle||null,targetHandle:b.targetHandle||null,connectionMode:t.connectionMode,onError:_});return{zIndex:lu({selected:b.selected,zIndex:b.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode}),...i||_m}},[b.source,b.target,b.sourceHandle,b.targetHandle,b.selected,b.zIndex]),qd),ie=(0,v.useMemo)(()=>b.markerStart?`url('#${Eu(b.markerStart,m)}')`:void 0,[b.markerStart,m]),ae=(0,v.useMemo)(()=>b.markerEnd?`url('#${Eu(b.markerEnd,m)}')`:void 0,[b.markerEnd,m]);if(b.hidden||ee===null||te===null||P===null||F===null)return null;let I=t=>{let{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:a}=M.getState();E&&(M.setState({nodesSelectionActive:!1}),b.selected&&a?(r({nodes:[],edges:[b]}),D.current?.blur()):n([e])),i&&i(t,b)},L=a?e=>{a(e,{...b})}:void 0,oe=o?e=>{o(e,{...b})}:void 0,se=s?e=>{s(e,{...b})}:void 0,ce=c?e=>{c(e,{...b})}:void 0,le=l?e=>{l(e,{...b})}:void 0;return(0,H.jsx)(`svg`,{style:{zIndex:N},children:(0,H.jsxs)(`g`,{className:pr([`react-flow__edge`,`react-flow__edge-${S}`,b.className,g,{selected:b.selected,animated:b.animated,inactive:!E&&!i,updating:O,selectable:E}]),onClick:I,onDoubleClick:L,onContextMenu:oe,onMouseEnter:se,onMouseMove:ce,onMouseLeave:le,onKeyDown:w?t=>{if(!y&&$c.includes(t.key)&&E){let{unselectNodesAndEdges:n,addSelectedEdges:r}=M.getState();t.key===`Escape`?(D.current?.blur(),n({edges:[b]})):r([e])}}:void 0,tabIndex:w?0:void 0,role:b.ariaRole??(w?`group`:`img`),"aria-roledescription":`edge`,"data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":b.ariaLabel===null?void 0:b.ariaLabel||`Edge from ${b.source} to ${b.target}`,"aria-describedby":w?`${rf}-${m}`:void 0,ref:D,...b.domAttributes,children:[!A&&(0,H.jsx)(C,{id:e,source:b.source,target:b.target,type:b.type,selected:b.selected,animated:b.animated,selectable:E,deletable:b.deletable??!0,label:b.label,labelStyle:b.labelStyle,labelShowBg:b.labelShowBg,labelBgStyle:b.labelBgStyle,labelBgPadding:b.labelBgPadding,labelBgBorderRadius:b.labelBgBorderRadius,sourceX:ee,sourceY:te,targetX:P,targetY:F,sourcePosition:ne,targetPosition:re,data:b.data,style:b.style,sourceHandleId:b.sourceHandle,targetHandleId:b.targetHandle,markerStart:ie,markerEnd:ae,pathOptions:`pathOptions`in b?b.pathOptions:void 0,interactionWidth:b.interactionWidth}),T&&(0,H.jsx)(Sm,{edge:b,isReconnectable:T,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,sourceX:ee,sourceY:te,targetX:P,targetY:F,sourcePosition:ne,targetPosition:re,setUpdateHover:k,setReconnecting:j})]})})}var wm=(0,v.memo)(Cm),Tm=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Em({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:i,onReconnect:a,onEdgeContextMenu:o,onEdgeMouseEnter:s,onEdgeMouseMove:c,onEdgeMouseLeave:l,onEdgeClick:u,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,disableKeyboardA11y:h}){let{edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,onError:y}=Qd(Tm,qd),b=Hp(t);return(0,H.jsxs)(`div`,{className:`react-flow__edges`,children:[(0,H.jsx)(Yp,{defaultColor:e,rfId:n}),b.map(e=>(0,H.jsx)(wm,{id:e,edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,noPanClassName:i,onReconnect:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,onClick:u,reconnectRadius:d,onDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,rfId:n,onError:y,edgeTypes:r,disableKeyboardA11y:h},e))]})}Em.displayName=`EdgeRenderer`;var Dm=(0,v.memo)(Em),Om=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function km({children:e}){return(0,H.jsx)(`div`,{className:`react-flow__viewport xyflow__viewport react-flow__container`,style:{transform:Qd(Om)},children:e})}function Am(e){let t=Yf(),n=(0,v.useRef)(!1);(0,v.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var jm=e=>e.panZoom?.syncViewport;function Mm(e){let t=Qd(jm),n=$d();return(0,v.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function Nm(e){return e.connection.inProgress?{...e.connection,to:Ll(e.connection.to,e.transform)}:{...e.connection}}function Pm(e){return e?t=>e(Nm(t)):Nm}function Fm(e){return Qd(Pm(e),qd)}var Im=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Lm({containerStyle:e,style:t,type:n,component:r}){let{nodesConnectable:i,width:a,height:o,isValid:s,inProgress:c}=Qd(Im,qd);return a&&i&&c?(0,H.jsx)(`svg`,{style:e,width:a,height:o,className:`react-flow__connectionline react-flow__container`,children:(0,H.jsx)(`g`,{className:pr([`react-flow__connection`,cl(s)]),children:(0,H.jsx)(Rm,{style:t,type:n,CustomComponent:r,isValid:s})})}):null}var Rm=({style:e,type:t=al.Bezier,CustomComponent:n,isValid:r})=>{let{inProgress:i,from:a,fromNode:o,fromHandle:s,fromPosition:c,to:l,toNode:u,toHandle:d,toPosition:f,pointer:p}=Fm();if(!i)return;if(n)return(0,H.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:o,fromHandle:s,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:c,toPosition:f,connectionStatus:cl(r),toNode:u,toHandle:d,pointer:p});let m=``,h={sourceX:a.x,sourceY:a.y,sourcePosition:c,targetX:l.x,targetY:l.y,targetPosition:f};switch(t){case al.Bezier:[m]=su(h);break;case al.SimpleBezier:[m]=em(h);break;case al.Step:[m]=bu({...h,borderRadius:0});break;case al.SmoothStep:[m]=bu(h);break;default:[m]=mu(h)}return(0,H.jsx)(`path`,{d:m,fill:`none`,className:`react-flow__connection-path`,style:e})};Rm.displayName=`ConnectionLine`;var zm={};function Bm(e=zm){(0,v.useRef)(e),$d(),(0,v.useEffect)(()=>{},[e])}function Vm(){$d(),(0,v.useRef)(!1),(0,v.useEffect)(()=>{},[])}function Hm({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:i,onNodeDoubleClick:a,onEdgeDoubleClick:o,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:p,connectionLineType:m,connectionLineStyle:h,connectionLineComponent:g,connectionLineContainerStyle:_,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,multiSelectionKeyCode:x,panActivationKeyCode:S,zoomActivationKeyCode:C,deleteKeyCode:w,onlyRenderVisibleElements:T,elementsSelectable:E,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,preventScrolling:j,defaultMarkerColor:M,zoomOnScroll:N,zoomOnPinch:ee,panOnScroll:te,panOnScrollSpeed:P,panOnScrollMode:F,zoomOnDoubleClick:ne,panOnDrag:re,onPaneClick:ie,onPaneMouseEnter:ae,onPaneMouseMove:I,onPaneMouseLeave:L,onPaneScroll:oe,onPaneContextMenu:se,paneClickDistance:ce,nodeClickDistance:le,onEdgeContextMenu:ue,onEdgeMouseEnter:de,onEdgeMouseMove:fe,onEdgeMouseLeave:pe,reconnectRadius:me,onReconnect:he,onReconnectStart:ge,onReconnectEnd:_e,noDragClassName:ve,noWheelClassName:ye,noPanClassName:be,disableKeyboardA11y:xe,nodeExtent:Se,rfId:Ce,viewport:we,onViewportChange:Te}){return Bm(e),Bm(t),Vm(),Am(n),Mm(we),(0,H.jsx)(jp,{onPaneClick:ie,onPaneMouseEnter:ae,onPaneMouseMove:I,onPaneMouseLeave:L,onPaneContextMenu:se,onPaneScroll:oe,paneClickDistance:ce,deleteKeyCode:w,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:x,panActivationKeyCode:S,zoomActivationKeyCode:C,elementsSelectable:E,zoomOnScroll:N,zoomOnPinch:ee,zoomOnDoubleClick:ne,panOnScroll:te,panOnScrollSpeed:P,panOnScrollMode:F,panOnDrag:re,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,onSelectionContextMenu:d,preventScrolling:j,noDragClassName:ve,noWheelClassName:ye,noPanClassName:be,disableKeyboardA11y:xe,onViewportChange:Te,isControlledViewport:!!we,children:(0,H.jsxs)(km,{children:[(0,H.jsx)(Dm,{edgeTypes:t,onEdgeClick:i,onEdgeDoubleClick:o,onReconnect:he,onReconnectStart:ge,onReconnectEnd:_e,onlyRenderVisibleElements:T,onEdgeContextMenu:ue,onEdgeMouseEnter:de,onEdgeMouseMove:fe,onEdgeMouseLeave:pe,reconnectRadius:me,defaultMarkerColor:M,noPanClassName:be,disableKeyboardA11y:xe,rfId:Ce}),(0,H.jsx)(Lm,{style:h,type:m,component:g,containerStyle:_}),(0,H.jsx)(`div`,{className:`react-flow__edgelabel-renderer`}),(0,H.jsx)(Vp,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:a,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,nodeClickDistance:le,onlyRenderVisibleElements:T,noPanClassName:be,noDragClassName:ve,disableKeyboardA11y:xe,nodeExtent:Se,rfId:Ce}),(0,H.jsx)(`div`,{className:`react-flow__viewport-portal`})]})})}Hm.displayName=`GraphView`;var Um=(0,v.memo)(Hm),Wm=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c=.5,maxZoom:l=2,nodeOrigin:u,nodeExtent:d,zIndexMode:f=`basic`}={})=>{let p=new Map,m=new Map,h=new Map,g=new Map,_=r??t??[],v=n??e??[],y=u??[0,0],b=d??Qc;Gu(h,g,_);let x=Iu(v,p,m,{nodeOrigin:y,nodeExtent:b,zIndexMode:f}),S=[0,0,1];if(o&&i&&a){let{x:e,y:t,zoom:n}=Vl(ml(p,{filter:e=>!!((e.width||e.initialWidth)&&(e.height||e.initialHeight))}),i,a,c,l,s?.padding??.1);S=[e,t,n]}return{rfId:`1`,width:i??0,height:a??0,transform:S,nodes:v,nodesInitialized:x,nodeLookup:p,parentLookup:m,edges:_,edgeLookup:g,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:l,translateExtent:Qc,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:tl.Strict,domNode:null,paneDragging:!1,noPanClassName:`nopan`,nodeOrigin:y,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:o??!1,fitViewOptions:s,fitViewResolver:null,connection:{...il},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:``,autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:Fl,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:`react`,debug:!1,ariaLabelConfig:el,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},Gm=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f})=>Kd((p,m)=>{async function h(){let{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:a,minZoom:o,maxZoom:s}=m();t&&(await vl({nodes:e,width:i,height:a,panZoom:t,minZoom:o,maxZoom:s},n),r?.resolve(!0),p({fitViewResolver:null}))}return{...Wm({nodes:e,edges:t,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:e=>{let{nodeLookup:t,parentLookup:n,nodeOrigin:r,elevateNodesOnSelect:i,fitViewQueued:a,zIndexMode:o}=m(),s=Iu(e,t,n,{nodeOrigin:r,nodeExtent:d,elevateNodesOnSelect:i,checkEquality:!0,zIndexMode:o});a&&s?(h(),p({nodes:e,nodesInitialized:s,fitViewQueued:!1,fitViewOptions:void 0})):p({nodes:e,nodesInitialized:s})},setEdges:e=>{let{connectionLookup:t,edgeLookup:n}=m();Gu(t,n,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=m();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=m();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:a,nodeExtent:o,debug:s,fitViewQueued:c,zIndexMode:l}=m(),{changes:u,updatedInternals:d}=Hu(e,n,r,i,a,o,l);d&&(Nu(n,r,{nodeOrigin:a,nodeExtent:o,zIndexMode:l}),c?(h(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),u?.length>0&&(s&&console.log(`React Flow: trigger node changes`,u),t?.(u)))},updateNodePositions:(e,t=!1)=>{let n=[],r=[],{nodeLookup:i,triggerNodeChanges:a,connection:o,updateConnection:s,onNodesChangeMiddlewareMap:c}=m();for(let[a,c]of e){let e=i.get(a),l=!!(e?.expandParent&&e?.parentId&&c?.position),u={id:a,type:`position`,position:l?{x:Math.max(0,c.position.x),y:Math.max(0,c.position.y)}:c.position,dragging:t};if(e&&o.inProgress&&o.fromNode.id===e.id){let t=wu(e,o.fromHandle,q.Left,!0);s({...o,from:t})}l&&e.parentId&&n.push({id:a,parentId:e.parentId,rect:{...c.internals.positionAbsolute,width:c.measured.width??0,height:c.measured.height??0}}),r.push(u)}if(n.length>0){let{parentLookup:e,nodeOrigin:t}=m(),a=Vu(n,i,e,t);r.push(...a)}for(let e of c.values())r=e(r);a(r)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:a}=m();e?.length&&(i&&n(Nf(e,r)),a&&console.log(`React Flow: trigger node changes`,e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:a}=m();e?.length&&(i&&n(Pf(e,r)),a&&console.log(`React Flow: trigger edge changes`,e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){i(e.map(e=>Ff(e,!0)));return}i(If(r,new Set([...e]),!0)),a(If(n))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){a(e.map(e=>Ff(e,!0)));return}a(If(n,new Set([...e]))),i(If(r,new Set,!0))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:a,triggerEdgeChanges:o}=m(),s=e||r,c=t||n,l=[];for(let e of s){if(!e.selected)continue;let t=i.get(e.id);t&&(t.selected=!1),l.push(Ff(e.id,!1))}let u=[];for(let e of c)e.selected&&u.push(Ff(e.id,!1));a(l),o(u)},setMinZoom:e=>{let{panZoom:t,maxZoom:n}=m();t?.setScaleExtent([e,n]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:n}=m();t?.setScaleExtent([n,e]),p({maxZoom:e})},setTranslateExtent:e=>{m().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r,elementsSelectable:i}=m();if(!i)return;let a=t.reduce((e,t)=>t.selected?[...e,Ff(t.id,!1)]:e,[]),o=e.reduce((e,t)=>t.selected?[...e,Ff(t.id,!1)]:e,[]);n(a),r(o)},setNodeExtent:e=>{let{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:a,nodeExtent:o,zIndexMode:s}=m();e[0][0]===o[0][0]&&e[0][1]===o[0][1]&&e[1][0]===o[1][0]&&e[1][1]===o[1][1]||(Iu(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:a,checkEquality:!1,zIndexMode:s}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:n,height:r,panZoom:i,translateExtent:a}=m();return Uu({delta:e,panZoom:i,transform:t,translateExtent:a,width:n,height:r})},setCenter:async(e,t,n)=>{let{width:r,height:i,maxZoom:a,panZoom:o}=m();if(!o)return Promise.resolve(!1);let s=n?.zoom===void 0?a:n.zoom;return await o.setViewport({x:r/2-e*s,y:i/2-t*s,zoom:s},{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{p({connection:{...il}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...Wm()})}},Object.is);function Km({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:i,initialHeight:a,initialMinZoom:o,initialMaxZoom:s,initialFitViewOptions:c,fitView:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f,children:p}){let[m]=(0,v.useState)(()=>Gm({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:l,minZoom:o,maxZoom:s,fitViewOptions:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f}));return(0,H.jsx)(Xd,{value:m,children:(0,H.jsx)(Kf,{children:p})})}function qm({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:i,width:a,height:o,fitView:s,fitViewOptions:c,minZoom:l,maxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p}){return(0,v.useContext)(Yd)?(0,H.jsx)(H.Fragment,{children:e}):(0,H.jsx)(Km,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:i,initialWidth:a,initialHeight:o,fitView:s,initialFitViewOptions:c,initialMinZoom:l,initialMaxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p,children:e})}var Jm={width:`100%`,height:`100%`,overflow:`hidden`,position:`relative`,zIndex:0};function Ym({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:a,edgeTypes:o,onNodeClick:s,onEdgeClick:c,onInit:l,onMove:u,onMoveStart:d,onMoveEnd:f,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,onNodeMouseEnter:y,onNodeMouseMove:b,onNodeMouseLeave:x,onNodeContextMenu:S,onNodeDoubleClick:C,onNodeDragStart:w,onNodeDrag:T,onNodeDragStop:E,onNodesDelete:D,onEdgesDelete:O,onDelete:k,onSelectionChange:A,onSelectionDragStart:j,onSelectionDrag:M,onSelectionDragStop:N,onSelectionContextMenu:ee,onSelectionStart:te,onSelectionEnd:P,onBeforeDelete:F,connectionMode:ne,connectionLineType:re=al.Bezier,connectionLineStyle:ie,connectionLineComponent:ae,connectionLineContainerStyle:I,deleteKeyCode:L=`Backspace`,selectionKeyCode:oe=`Shift`,selectionOnDrag:se=!1,selectionMode:ce=rl.Full,panActivationKeyCode:le=`Space`,multiSelectionKeyCode:ue=Hl()?`Meta`:`Control`,zoomActivationKeyCode:de=Hl()?`Meta`:`Control`,snapToGrid:fe,snapGrid:pe,onlyRenderVisibleElements:me=!1,selectNodesOnDrag:he,nodesDraggable:ge,autoPanOnNodeFocus:_e,nodesConnectable:ve,nodesFocusable:ye,nodeOrigin:be=vf,edgesFocusable:xe,edgesReconnectable:Se,elementsSelectable:Ce=!0,defaultViewport:we=yf,minZoom:Te=.5,maxZoom:Ee=2,translateExtent:De=Qc,preventScrolling:Oe=!0,nodeExtent:ke,defaultMarkerColor:Ae=`#b1b1b7`,zoomOnScroll:je=!0,zoomOnPinch:Me=!0,panOnScroll:Ne=!1,panOnScrollSpeed:Pe=.5,panOnScrollMode:Fe=nl.Free,zoomOnDoubleClick:Ie=!0,panOnDrag:Le=!0,onPaneClick:Re,onPaneMouseEnter:ze,onPaneMouseMove:Be,onPaneMouseLeave:Ve,onPaneScroll:He,onPaneContextMenu:Ue,paneClickDistance:R=1,nodeClickDistance:We=0,children:z,onReconnect:Ge,onReconnectStart:Ke,onReconnectEnd:qe,onEdgeContextMenu:Je,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Xe,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qe,reconnectRadius:$e=10,onNodesChange:et,onEdgesChange:B,noDragClassName:V=`nodrag`,noWheelClassName:tt=`nowheel`,noPanClassName:nt=`nopan`,fitView:rt,fitViewOptions:it,connectOnClick:at,attributionPosition:ot,proOptions:st,defaultEdgeOptions:ct,elevateNodesOnSelect:lt=!0,elevateEdgesOnSelect:ut=!1,disableKeyboardA11y:dt=!1,autoPanOnConnect:ft,autoPanOnNodeDrag:pt,autoPanSpeed:mt,connectionRadius:ht,isValidConnection:gt,onError:U,style:W,id:_t,nodeDragThreshold:vt,connectionDragThreshold:yt,viewport:bt,onViewportChange:xt,width:St,height:Ct,colorMode:wt=`light`,debug:Tt,onScroll:Et,ariaLabelConfig:Dt,zIndexMode:Ot=`basic`,...kt},At){let jt=_t||`1`,Mt=Tf(wt),Nt=(0,v.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:`instant`}),Et?.(e)},[Et]);return(0,H.jsx)(`div`,{"data-testid":`rf__wrapper`,...kt,onScroll:Nt,style:{...W,...Jm},ref:At,className:pr([`react-flow`,i,Mt]),id:_t,role:`application`,children:(0,H.jsxs)(qm,{nodes:e,edges:t,width:St,height:Ct,fitView:rt,fitViewOptions:it,minZoom:Te,maxZoom:Ee,nodeOrigin:be,nodeExtent:ke,zIndexMode:Ot,children:[(0,H.jsx)(Um,{onInit:l,onNodeClick:s,onEdgeClick:c,onNodeMouseEnter:y,onNodeMouseMove:b,onNodeMouseLeave:x,onNodeContextMenu:S,onNodeDoubleClick:C,nodeTypes:a,edgeTypes:o,connectionLineType:re,connectionLineStyle:ie,connectionLineComponent:ae,connectionLineContainerStyle:I,selectionKeyCode:oe,selectionOnDrag:se,selectionMode:ce,deleteKeyCode:L,multiSelectionKeyCode:ue,panActivationKeyCode:le,zoomActivationKeyCode:de,onlyRenderVisibleElements:me,defaultViewport:we,translateExtent:De,minZoom:Te,maxZoom:Ee,preventScrolling:Oe,zoomOnScroll:je,zoomOnPinch:Me,zoomOnDoubleClick:Ie,panOnScroll:Ne,panOnScrollSpeed:Pe,panOnScrollMode:Fe,panOnDrag:Le,onPaneClick:Re,onPaneMouseEnter:ze,onPaneMouseMove:Be,onPaneMouseLeave:Ve,onPaneScroll:He,onPaneContextMenu:Ue,paneClickDistance:R,nodeClickDistance:We,onSelectionContextMenu:ee,onSelectionStart:te,onSelectionEnd:P,onReconnect:Ge,onReconnectStart:Ke,onReconnectEnd:qe,onEdgeContextMenu:Je,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Xe,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qe,reconnectRadius:$e,defaultMarkerColor:Ae,noDragClassName:V,noWheelClassName:tt,noPanClassName:nt,rfId:jt,disableKeyboardA11y:dt,nodeExtent:ke,viewport:bt,onViewportChange:xt}),(0,H.jsx)(Cf,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,nodesDraggable:ge,autoPanOnNodeFocus:_e,nodesConnectable:ve,nodesFocusable:ye,edgesFocusable:xe,edgesReconnectable:Se,elementsSelectable:Ce,elevateNodesOnSelect:lt,elevateEdgesOnSelect:ut,minZoom:Te,maxZoom:Ee,nodeExtent:ke,onNodesChange:et,onEdgesChange:B,snapToGrid:fe,snapGrid:pe,connectionMode:ne,translateExtent:De,connectOnClick:at,defaultEdgeOptions:ct,fitView:rt,fitViewOptions:it,onNodesDelete:D,onEdgesDelete:O,onDelete:k,onNodeDragStart:w,onNodeDrag:T,onNodeDragStop:E,onSelectionDrag:M,onSelectionDragStart:j,onSelectionDragStop:N,onMove:u,onMoveStart:d,onMoveEnd:f,noPanClassName:nt,nodeOrigin:be,rfId:jt,autoPanOnConnect:ft,autoPanOnNodeDrag:pt,autoPanSpeed:mt,onError:U,connectionRadius:ht,isValidConnection:gt,selectNodesOnDrag:he,nodeDragThreshold:vt,connectionDragThreshold:yt,onBeforeDelete:F,debug:Tt,ariaLabelConfig:Dt,zIndexMode:Ot}),(0,H.jsx)(_f,{onSelectionChange:A}),z,(0,H.jsx)(df,{proOptions:st,position:ot}),(0,H.jsx)(lf,{rfId:jt,disableKeyboardA11y:dt})]})})}var Xm=Vf(Ym),Zm=e=>e.domNode?.querySelector(`.react-flow__edgelabel-renderer`);function Qm({children:e}){let t=Qd(Zm);return t?(0,Jd.createPortal)(e,t):null}function $m(e){let[t,n]=(0,v.useState)(e);return[t,n,(0,v.useCallback)(e=>n(t=>Nf(e,t)),[])]}function eh(e){let[t,n]=(0,v.useState)(e);return[t,n,(0,v.useCallback)(e=>n(t=>Pf(e,t)),[])]}Zc.error014();function th({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,H.jsx)(`path`,{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:pr([`react-flow__background-pattern`,n,r])})}function nh({radius:e,className:t}){return(0,H.jsx)(`circle`,{cx:e,cy:e,r:e,className:pr([`react-flow__background-pattern`,`dots`,t])})}var rh;(function(e){e.Lines=`lines`,e.Dots=`dots`,e.Cross=`cross`})(rh||={});var ih={[rh.Dots]:1,[rh.Lines]:1,[rh.Cross]:6},ah=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function oh({id:e,variant:t=rh.Dots,gap:n=20,size:r,lineWidth:i=1,offset:a=0,color:o,bgColor:s,style:c,className:l,patternClassName:u}){let d=(0,v.useRef)(null),{transform:f,patternId:p}=Qd(ah,qd),m=r||ih[t],h=t===rh.Dots,g=t===rh.Cross,_=Array.isArray(n)?n:[n,n],y=[_[0]*f[2]||1,_[1]*f[2]||1],b=m*f[2],x=Array.isArray(a)?a:[a,a],S=g?[b,b]:y,C=[x[0]*f[2]||1+S[0]/2,x[1]*f[2]||1+S[1]/2],w=`${p}${e||``}`;return(0,H.jsxs)(`svg`,{className:pr([`react-flow__background`,l]),style:{...c,...ep,"--xy-background-color-props":s,"--xy-background-pattern-color-props":o},ref:d,"data-testid":`rf__background`,children:[(0,H.jsx)(`pattern`,{id:w,x:f[0]%y[0],y:f[1]%y[1],width:y[0],height:y[1],patternUnits:`userSpaceOnUse`,patternTransform:`translate(-${C[0]},-${C[1]})`,children:h?(0,H.jsx)(nh,{radius:b/2,className:u}):(0,H.jsx)(th,{dimensions:S,lineWidth:i,variant:t,className:u})}),(0,H.jsx)(`rect`,{x:`0`,y:`0`,width:`100%`,height:`100%`,fill:`url(#${w})`})]})}oh.displayName=`Background`;var sh=(0,v.memo)(oh);function ch(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 32`,children:(0,H.jsx)(`path`,{d:`M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z`})})}function lh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 5`,children:(0,H.jsx)(`path`,{d:`M0 0h32v4.2H0z`})})}function uh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 30`,children:(0,H.jsx)(`path`,{d:`M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z`})})}function dh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,H.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z`})})}function fh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,H.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z`})})}function ph({children:e,className:t,...n}){return(0,H.jsx)(`button`,{type:`button`,className:pr([`react-flow__controls-button`,t]),...n,children:e})}var mh=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function hh({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:a,onZoomOut:o,onFitView:s,onInteractiveChange:c,className:l,children:u,position:d=`bottom-left`,orientation:f=`vertical`,"aria-label":p}){let m=$d(),{isInteractive:h,minZoomReached:g,maxZoomReached:_,ariaLabelConfig:v}=Qd(mh,qd),{zoomIn:y,zoomOut:b,fitView:x}=Yf();return(0,H.jsxs)(uf,{className:pr([`react-flow__controls`,f===`horizontal`?`horizontal`:`vertical`,l]),position:d,style:e,"data-testid":`rf__controls`,"aria-label":p??v[`controls.ariaLabel`],children:[t&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(ph,{onClick:()=>{y(),a?.()},className:`react-flow__controls-zoomin`,title:v[`controls.zoomIn.ariaLabel`],"aria-label":v[`controls.zoomIn.ariaLabel`],disabled:_,children:(0,H.jsx)(ch,{})}),(0,H.jsx)(ph,{onClick:()=>{b(),o?.()},className:`react-flow__controls-zoomout`,title:v[`controls.zoomOut.ariaLabel`],"aria-label":v[`controls.zoomOut.ariaLabel`],disabled:g,children:(0,H.jsx)(lh,{})})]}),n&&(0,H.jsx)(ph,{className:`react-flow__controls-fitview`,onClick:()=>{x(i),s?.()},title:v[`controls.fitView.ariaLabel`],"aria-label":v[`controls.fitView.ariaLabel`],children:(0,H.jsx)(uh,{})}),r&&(0,H.jsx)(ph,{className:`react-flow__controls-interactive`,onClick:()=>{m.setState({nodesDraggable:!h,nodesConnectable:!h,elementsSelectable:!h}),c?.(!h)},title:v[`controls.interactive.ariaLabel`],"aria-label":v[`controls.interactive.ariaLabel`],children:h?(0,H.jsx)(fh,{}):(0,H.jsx)(dh,{})}),u]})}hh.displayName=`Controls`;var gh=(0,v.memo)(hh);function _h({id:e,x:t,y:n,width:r,height:i,style:a,color:o,strokeColor:s,strokeWidth:c,className:l,borderRadius:u,shapeRendering:d,selected:f,onClick:p}){let{background:m,backgroundColor:h}=a||{},g=o||m||h;return(0,H.jsx)(`rect`,{className:pr([`react-flow__minimap-node`,{selected:f},l]),x:t,y:n,rx:u,ry:u,width:r,height:i,style:{fill:g,stroke:s,strokeWidth:c},shapeRendering:d,onClick:p?t=>p(t,e):void 0})}var vh=(0,v.memo)(_h),yh=e=>e.nodes.map(e=>e.id),bh=e=>e instanceof Function?e:()=>e;function xh({nodeStrokeColor:e,nodeColor:t,nodeClassName:n=``,nodeBorderRadius:r=5,nodeStrokeWidth:i,nodeComponent:a=vh,onClick:o}){let s=Qd(yh,qd),c=bh(t),l=bh(e),u=bh(n),d=typeof window>`u`||window.chrome?`crispEdges`:`geometricPrecision`;return(0,H.jsx)(H.Fragment,{children:s.map(e=>(0,H.jsx)(Ch,{id:e,nodeColorFunc:c,nodeStrokeColorFunc:l,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:i,NodeComponent:a,onClick:o,shapeRendering:d},e))})}function Sh({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:i,nodeStrokeWidth:a,shapeRendering:o,NodeComponent:s,onClick:c}){let{node:l,x:u,y:d,width:f,height:p}=Qd(t=>{let n=t.nodeLookup.get(e);if(!n)return{node:void 0,x:0,y:0,width:0,height:0};let r=n.internals.userNode,{x:i,y:a}=n.internals.positionAbsolute,{width:o,height:s}=Wl(r);return{node:r,x:i,y:a,width:o,height:s}},qd);return!l||l.hidden||!Gl(l)?null:(0,H.jsx)(s,{x:u,y:d,width:f,height:p,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:i,strokeColor:n(l),strokeWidth:a,shapeRendering:o,onClick:c,id:l.id})}var Ch=(0,v.memo)(Sh),wh=(0,v.memo)(xh),Th=200,Eh=150,Dh=e=>!e.hidden,Oh=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?jl(ml(e.nodeLookup,{filter:Dh}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},kh=`react-flow__minimap-desc`;function Ah({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:i=``,nodeBorderRadius:a=5,nodeStrokeWidth:o,nodeComponent:s,bgColor:c,maskColor:l,maskStrokeColor:u,maskStrokeWidth:d,position:f=`bottom-right`,onClick:p,onNodeClick:m,pannable:h=!1,zoomable:g=!1,ariaLabel:_,inversePan:y,zoomStep:b=1,offsetScale:x=5}){let S=$d(),C=(0,v.useRef)(null),{boundingRect:w,viewBB:T,rfId:E,panZoom:D,translateExtent:O,flowWidth:k,flowHeight:A,ariaLabelConfig:j}=Qd(Oh,qd),M=e?.width??Th,N=e?.height??Eh,ee=w.width/M,te=w.height/N,P=Math.max(ee,te),F=P*M,ne=P*N,re=x*P,ie=w.x-(F-w.width)/2-re,ae=w.y-(ne-w.height)/2-re,I=F+re*2,L=ne+re*2,oe=`${kh}-${E}`,se=(0,v.useRef)(0),ce=(0,v.useRef)();se.current=P,(0,v.useEffect)(()=>{if(C.current&&D)return ce.current=cd({domNode:C.current,panZoom:D,getTransform:()=>S.getState().transform,getViewScale:()=>se.current}),()=>{ce.current?.destroy()}},[D]),(0,v.useEffect)(()=>{ce.current?.update({translateExtent:O,width:k,height:A,inversePan:y,pannable:h,zoomStep:b,zoomable:g})},[h,g,y,b,O,k,A]);let le=p?e=>{let[t,n]=ce.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,ue=m?(0,v.useCallback)((e,t)=>{let n=S.getState().nodeLookup.get(t).internals.userNode;m(e,n)},[]):void 0,de=_??j[`minimap.ariaLabel`];return(0,H.jsx)(uf,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof c==`string`?c:void 0,"--xy-minimap-mask-background-color-props":typeof l==`string`?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof u==`string`?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof d==`number`?d*P:void 0,"--xy-minimap-node-background-color-props":typeof r==`string`?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n==`string`?n:void 0,"--xy-minimap-node-stroke-width-props":typeof o==`number`?o:void 0},className:pr([`react-flow__minimap`,t]),"data-testid":`rf__minimap`,children:(0,H.jsxs)(`svg`,{width:M,height:N,viewBox:`${ie} ${ae} ${I} ${L}`,className:`react-flow__minimap-svg`,role:`img`,"aria-labelledby":oe,ref:C,onClick:le,children:[de&&(0,H.jsx)(`title`,{id:oe,children:de}),(0,H.jsx)(wh,{onClick:ue,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:i,nodeStrokeWidth:o,nodeComponent:s}),(0,H.jsx)(`path`,{className:`react-flow__minimap-mask`,d:`M${ie-re},${ae-re}h${I+re*2}v${L+re*2}h${-I-re*2}z + M${T.x},${T.y}h${T.width}v${T.height}h${-T.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}Ah.displayName=`MiniMap`;var jh=(0,v.memo)(Ah),Mh=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,Nh={[Y.Line]:`right`,[Y.Handle]:`bottom-right`};function Ph({nodeId:e,position:t,variant:n=Y.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let y=mp(),b=typeof e==`string`?e:y,x=$d(),S=(0,v.useRef)(null),C=n===Y.Handle,w=Qd((0,v.useCallback)(Mh(C&&p),[C,p]),qd),T=(0,v.useRef)(null),E=t??Nh[n];return(0,v.useEffect)(()=>{if(!(!S.current||!b))return T.current||=Pd({domNode:S.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=x.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=x.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=Vu([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...Kl({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};x.getState().triggerNodeChanges([n])}}),T.current.update({controlPosition:E,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{T.current?.destroy()}},[E,s,c,l,u,d,h,g,_,m]),(0,H.jsx)(`div`,{className:pr([`react-flow__resize-control`,`nodrag`,...E.split(`-`),n,r]),ref:S,style:{...i,scale:w,...o&&{[C?`backgroundColor`:`borderColor`]:o}},children:a})}(0,v.memo)(Ph);function Fh(e){return e.join(`.`)}function Ih(e,t){return`${Fh(e)}::${t}`}function Lh(e){let t=e.indexOf(`::`);if(t===-1)return{contextPath:[],name:e};let n=e.slice(0,t),r=e.slice(t+2);return{contextPath:n===``?[]:n.split(`.`).map(e=>Number(e)),name:r}}function Rh(e,t){return Ih(e,t)}function zh(e){return e.includes(`::`)}function Bh(e){let t=e.indexOf(`[`);return t<=0||!e.endsWith(`]`)?null:{group:e.slice(0,t),key:e.slice(t+1,-1)}}function Vh(e,t){if(t.length===0)return null;let n=e[t[0]];for(let e=1;ee.nodes),n=B(e=>e.subworkflowContexts),r=e?.iterationContextPath,i=e?.contextPath??[],a=e?.name,o=r?r.join(`.`):``;return(0,v.useMemo)(()=>{if(r&&r.length>0){let e=Vh(n,r);return e?{name:a??``,status:e.status,type:`workflow`,activity:[],error_message:e.workflowFailure?.message,error_type:e.workflowFailure?.error_type}:void 0}if(a)return i.length===0?t[a]:Vh(n,i)?.nodes[a]},[`${i.join(`.`)}::${a??``}`,o,t,n])}function Uh(){let e=B(e=>e.selectedNode),t=B(e=>e.nodes),n=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>{if(!e)return;let{contextPath:r,name:i}=Lh(e),a=(r.length===0?t:Vh(n,r)?.nodes)?.[i];if(a)return a;if(Bh(i)){let e=r.length===0?n:Vh(n,r)?.children??[],t;for(let n=e.length-1;n>=0;n--)if(e[n].slotKey===i){t=e[n];break}if(t)return{name:i,status:t.status,type:`workflow`,activity:[],tokens:t.totalTokens||void 0,cost_usd:t.totalCost||void 0,error_message:t.workflowFailure?.message,error_type:t.workflowFailure?.error_type}}},[e,t,n])}function Wh(){let e=B(e=>e.viewContextPath),t=B(e=>e.groupProgress),n=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>e.length===0?t:Vh(n,e)?.groupProgress??t,[e,t,n])}function Gh(){let e=B(e=>e.viewContextPath),t=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>e.length===0?t:Vh(t,e)?.children??[],[e,t])}function Kh(){let e=B(e=>e.viewContextPath),t=B(e=>e.agents),n=B(e=>e.routes),r=B(e=>e.parallelGroups),i=B(e=>e.forEachGroups),a=B(e=>e.nodes),o=B(e=>e.groupProgress),s=B(e=>e.entryPoint),c=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>{if(e.length===0)return{agents:t,routes:n,parallelGroups:r,forEachGroups:i,nodes:a,groupProgress:o,entryPoint:s,subworkflowContexts:c,parentAgent:null,basePath:[]};let l=Vh(c,e);return l?{agents:l.agents,routes:l.routes,parallelGroups:l.parallelGroups,forEachGroups:l.forEachGroups,nodes:l.nodes,groupProgress:l.groupProgress,entryPoint:l.entryPoint,subworkflowContexts:l.children,parentAgent:l.parentAgent,basePath:e}:{agents:t,routes:n,parallelGroups:r,forEachGroups:i,nodes:a,groupProgress:o,entryPoint:s,subworkflowContexts:c,parentAgent:null,basePath:[]}},[e,t,n,r,i,a,o,s,c])}var qh=0;function Jh(e,t=Date.now()){qh=Math.max(qh,t+e)}function Yh(e=Date.now()){return e{var n=`\0`,r=`\0`,i=``,a=class{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>void 0;_defaultEdgeLabelFn=()=>void 0;_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(e){e&&(this._isDirected=Object.hasOwn(e,`directed`)?e.directed:!0,this._isMultigraph=Object.hasOwn(e,`multigraph`)?e.multigraph:!1,this._isCompound=Object.hasOwn(e,`compound`)?e.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[r]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return this._defaultNodeLabelFn=e,typeof e!=`function`&&(this._defaultNodeLabelFn=()=>e),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var e=this;return this.nodes().filter(t=>Object.keys(e._in[t]).length===0)}sinks(){var e=this;return this.nodes().filter(t=>Object.keys(e._out[t]).length===0)}setNodes(e,t){var n=arguments,r=this;return e.forEach(function(e){n.length>1?r.setNode(e,t):r.setNode(e)}),this}setNode(e,t){return Object.hasOwn(this._nodes,e)?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]=r,this._children[e]={},this._children[r][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return Object.hasOwn(this._nodes,e)}removeNode(e){var t=this;if(Object.hasOwn(this._nodes,e)){var n=e=>t.removeEdge(t._edgeObjs[e]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(function(e){t.setParent(e)}),delete this._children[e]),Object.keys(this._in[e]).forEach(n),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(n),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw Error(`Cannot set parent in a non-compound graph`);if(t===void 0)t=r;else{t+=``;for(var n=t;n!==void 0;n=this.parent(n))if(n===e)throw Error(`Setting `+t+` as parent of `+e+` would create a cycle`);this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}parent(e){if(this._isCompound){var t=this._parent[e];if(t!==r)return t}}children(e=r){if(this._isCompound){var t=this._children[e];if(t)return Object.keys(t)}else if(e===r)return this.nodes();else if(this.hasNode(e))return[]}predecessors(e){var t=this._preds[e];if(t)return Object.keys(t)}successors(e){var t=this._sucs[e];if(t)return Object.keys(t)}neighbors(e){var t=this.predecessors(e);if(t){let r=new Set(t);for(var n of this.successors(e))r.add(n);return Array.from(r.values())}}isLeaf(e){return(this.isDirected()?this.successors(e):this.neighbors(e)).length===0}filterNodes(e){var t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph());var n=this;Object.entries(this._nodes).forEach(function([n,r]){e(n)&&t.setNode(n,r)}),Object.values(this._edgeObjs).forEach(function(e){t.hasNode(e.v)&&t.hasNode(e.w)&&t.setEdge(e,n.edge(e))});var r={};function i(e){var a=n.parent(e);return a===void 0||t.hasNode(a)?(r[e]=a,a):a in r?r[a]:i(a)}return this._isCompound&&t.nodes().forEach(e=>t.setParent(e,i(e))),t}setDefaultEdgeLabel(e){return this._defaultEdgeLabelFn=e,typeof e!=`function`&&(this._defaultEdgeLabelFn=()=>e),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,t){var n=this,r=arguments;return e.reduce(function(e,i){return r.length>1?n.setEdge(e,i,t):n.setEdge(e,i),i}),this}setEdge(){var e,t,n,r,i=!1,a=arguments[0];typeof a==`object`&&a&&`v`in a?(e=a.v,t=a.w,n=a.name,arguments.length===2&&(r=arguments[1],i=!0)):(e=a,t=arguments[1],n=arguments[3],arguments.length>2&&(r=arguments[2],i=!0)),e=``+e,t=``+t,n!==void 0&&(n=``+n);var s=c(this._isDirected,e,t,n);if(Object.hasOwn(this._edgeLabels,s))return i&&(this._edgeLabels[s]=r),this;if(n!==void 0&&!this._isMultigraph)throw Error(`Cannot set a named edge when isMultigraph = false`);this.setNode(e),this.setNode(t),this._edgeLabels[s]=i?r:this._defaultEdgeLabelFn(e,t,n);var u=l(this._isDirected,e,t,n);return e=u.v,t=u.w,Object.freeze(u),this._edgeObjs[s]=u,o(this._preds[t],e),o(this._sucs[e],t),this._in[t][s]=u,this._out[e][s]=u,this._edgeCount++,this}edge(e,t,n){var r=arguments.length===1?u(this._isDirected,arguments[0]):c(this._isDirected,e,t,n);return this._edgeLabels[r]}edgeAsObj(){let e=this.edge(...arguments);return typeof e==`object`?e:{label:e}}hasEdge(e,t,n){var r=arguments.length===1?u(this._isDirected,arguments[0]):c(this._isDirected,e,t,n);return Object.hasOwn(this._edgeLabels,r)}removeEdge(e,t,n){var r=arguments.length===1?u(this._isDirected,arguments[0]):c(this._isDirected,e,t,n),i=this._edgeObjs[r];return i&&(e=i.v,t=i.w,delete this._edgeLabels[r],delete this._edgeObjs[r],s(this._preds[t],e),s(this._sucs[e],t),delete this._in[t][r],delete this._out[e][r],this._edgeCount--),this}inEdges(e,t){var n=this._in[e];if(n){var r=Object.values(n);return t?r.filter(e=>e.v===t):r}}outEdges(e,t){var n=this._out[e];if(n){var r=Object.values(n);return t?r.filter(e=>e.w===t):r}}nodeEdges(e,t){var n=this.inEdges(e,t);if(n)return n.concat(this.outEdges(e,t))}};function o(e,t){e[t]?e[t]++:e[t]=1}function s(e,t){--e[t]||delete e[t]}function c(e,t,r,a){var o=``+t,s=``+r;if(!e&&o>s){var c=o;o=s,s=c}return o+i+s+i+(a===void 0?n:a)}function l(e,t,n,r){var i=``+t,a=``+n;if(!e&&i>a){var o=i;i=a,a=o}var s={v:i,w:a};return r&&(s.name=r),s}function u(e,t){return c(e,t.v,t.w,t.name)}t.exports=a})),Zh=o(((e,t)=>{t.exports=`2.2.4`})),Qh=o(((e,t)=>{t.exports={Graph:Xh(),version:Zh()}})),$h=o(((e,t)=>{var n=Xh();t.exports={write:r,read:o};function r(e){var t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:i(e),edges:a(e)};return e.graph()!==void 0&&(t.value=structuredClone(e.graph())),t}function i(e){return e.nodes().map(function(t){var n=e.node(t),r=e.parent(t),i={v:t};return n!==void 0&&(i.value=n),r!==void 0&&(i.parent=r),i})}function a(e){return e.edges().map(function(t){var n=e.edge(t),r={v:t.v,w:t.w};return t.name!==void 0&&(r.name=t.name),n!==void 0&&(r.value=n),r})}function o(e){var t=new n(e.options).setGraph(e.value);return e.nodes.forEach(function(e){t.setNode(e.v,e.value),e.parent&&t.setParent(e.v,e.parent)}),e.edges.forEach(function(e){t.setEdge({v:e.v,w:e.w,name:e.name},e.value)}),t}})),eg=o(((e,t)=>{t.exports=n;function n(e){var t={},n=[],r;function i(n){Object.hasOwn(t,n)||(t[n]=!0,r.push(n),e.successors(n).forEach(i),e.predecessors(n).forEach(i))}return e.nodes().forEach(function(e){r=[],i(e),r.length&&n.push(r)}),n}})),tg=o(((e,t)=>{t.exports=class{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(e){return e.key})}has(e){return Object.hasOwn(this._keyIndices,e)}priority(e){var t=this._keyIndices[e];if(t!==void 0)return this._arr[t].priority}min(){if(this.size()===0)throw Error(`Queue underflow`);return this._arr[0].key}add(e,t){var n=this._keyIndices;if(e=String(e),!Object.hasOwn(n,e)){var r=this._arr,i=r.length;return n[e]=i,r.push({key:e,priority:t}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,t){var n=this._keyIndices[e];if(t>this._arr[n].priority)throw Error(`New priority is greater than current priority. Key: `+e+` Old: `+this._arr[n].priority+` New: `+t);this._arr[n].priority=t,this._decrease(n)}_heapify(e){var t=this._arr,n=2*e,r=n+1,i=e;n>1,!(t[r].priority{var n=tg();t.exports=i;var r=()=>1;function i(e,t,n,i){return a(e,String(t),n||r,i||function(t){return e.outEdges(t)})}function a(e,t,r,i){var a={},o=new n,s,c,l=function(e){var t=e.v===s?e.w:e.v,n=a[t],i=r(e),l=c.distance+i;if(i<0)throw Error(`dijkstra does not allow negative edge weights. Bad edge: `+e+` Weight: `+i);l0&&(s=o.removeMin(),c=a[s],c.distance!==1/0);)i(s).forEach(l);return a}})),rg=o(((e,t)=>{var n=ng();t.exports=r;function r(e,t,r){return e.nodes().reduce(function(i,a){return i[a]=n(e,a,t,r),i},{})}})),ig=o(((e,t)=>{t.exports=n;function n(e){var t=0,n=[],r={},i=[];function a(o){var s=r[o]={onStack:!0,lowlink:t,index:t++};if(n.push(o),e.successors(o).forEach(function(e){Object.hasOwn(r,e)?r[e].onStack&&(s.lowlink=Math.min(s.lowlink,r[e].index)):(a(e),s.lowlink=Math.min(s.lowlink,r[e].lowlink))}),s.lowlink===s.index){var c=[],l;do l=n.pop(),r[l].onStack=!1,c.push(l);while(o!==l);i.push(c)}}return e.nodes().forEach(function(e){Object.hasOwn(r,e)||a(e)}),i}})),ag=o(((e,t)=>{var n=ig();t.exports=r;function r(e){return n(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}})),og=o(((e,t)=>{t.exports=r;var n=()=>1;function r(e,t,r){return i(e,t||n,r||function(t){return e.outEdges(t)})}function i(e,t,n){var r={},i=e.nodes();return i.forEach(function(e){r[e]={},r[e][e]={distance:0},i.forEach(function(t){e!==t&&(r[e][t]={distance:1/0})}),n(e).forEach(function(n){var i=n.v===e?n.w:n.v,a=t(n);r[e][i]={distance:a,predecessor:e}})}),i.forEach(function(e){var t=r[e];i.forEach(function(n){var a=r[n];i.forEach(function(n){var r=a[e],i=t[n],o=a[n],s=r.distance+i.distance;s{function n(e){var t={},n={},i=[];function a(o){if(Object.hasOwn(n,o))throw new r;Object.hasOwn(t,o)||(n[o]=!0,t[o]=!0,e.predecessors(o).forEach(a),delete n[o],i.push(o))}if(e.sinks().forEach(a),Object.keys(t).length!==e.nodeCount())throw new r;return i}var r=class extends Error{constructor(){super(...arguments)}};t.exports=n,n.CycleException=r})),cg=o(((e,t)=>{var n=sg();t.exports=r;function r(e){try{n(e)}catch(e){if(e instanceof n.CycleException)return!1;throw e}return!0}})),lg=o(((e,t)=>{t.exports=n;function n(e,t,n){Array.isArray(t)||(t=[t]);var a=e.isDirected()?t=>e.successors(t):t=>e.neighbors(t),o=n===`post`?r:i,s=[],c={};return t.forEach(t=>{if(!e.hasNode(t))throw Error(`Graph does not have node: `+t);o(t,a,c,s)}),s}function r(e,t,n,r){for(var i=[[e,!1]];i.length>0;){var o=i.pop();o[1]?r.push(o[0]):Object.hasOwn(n,o[0])||(n[o[0]]=!0,i.push([o[0],!0]),a(t(o[0]),e=>i.push([e,!1])))}}function i(e,t,n,r){for(var i=[e];i.length>0;){var o=i.pop();Object.hasOwn(n,o)||(n[o]=!0,r.push(o),a(t(o),e=>i.push(e)))}}function a(e,t){for(var n=e.length;n--;)t(e[n],n,e);return e}})),ug=o(((e,t)=>{var n=lg();t.exports=r;function r(e,t){return n(e,t,`post`)}})),dg=o(((e,t)=>{var n=lg();t.exports=r;function r(e,t){return n(e,t,`pre`)}})),fg=o(((e,t)=>{var n=Xh(),r=tg();t.exports=i;function i(e,t){var i=new n,a={},o=new r,s;function c(e){var n=e.v===s?e.w:e.v,r=o.priority(n);if(r!==void 0){var i=t(e);i0;){if(s=o.removeMin(),Object.hasOwn(a,s))i.setEdge(s,a[s]);else if(l)throw Error(`Input graph is not connected: `+e);else l=!0;e.nodeEdges(s).forEach(c)}return i}})),pg=o(((e,t)=>{t.exports={components:eg(),dijkstra:ng(),dijkstraAll:rg(),findCycles:ag(),floydWarshall:og(),isAcyclic:cg(),postorder:ug(),preorder:dg(),prim:fg(),tarjan:ig(),topsort:sg()}})),mg=o(((e,t)=>{var n=Qh();t.exports={Graph:n.Graph,json:$h(),alg:pg(),version:n.version}})),hg=o(((e,t)=>{var n=class{constructor(){let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return r(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&r(e),e._next=t._next,t._next._prev=e,t._next=e,e._prev=t}toString(){let e=[],t=this._sentinel,n=t._prev;for(;n!==t;)e.push(JSON.stringify(n,i)),n=n._prev;return`[`+e.join(`, `)+`]`}};function r(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function i(e,t){if(e!==`_next`&&e!==`_prev`)return t}t.exports=n})),gg=o(((e,t)=>{var n=mg().Graph,r=hg();t.exports=a;var i=()=>1;function a(e,t){if(e.nodeCount()<=1)return[];let n=c(e,t||i);return o(n.graph,n.buckets,n.zeroIdx).flatMap(t=>e.outEdges(t.v,t.w))}function o(e,t,n){let r=[],i=t[t.length-1],a=t[0],o;for(;e.nodeCount();){for(;o=a.dequeue();)s(e,t,n,o);for(;o=i.dequeue();)s(e,t,n,o);if(e.nodeCount()){for(let i=t.length-2;i>0;--i)if(o=t[i].dequeue(),o){r=r.concat(s(e,t,n,o,!0));break}}}return r}function s(e,t,n,r,i){let a=i?[]:void 0;return e.inEdges(r.v).forEach(r=>{let o=e.edge(r),s=e.node(r.v);i&&a.push({v:r.v,w:r.w}),s.out-=o,l(t,n,s)}),e.outEdges(r.v).forEach(r=>{let i=e.edge(r),a=r.w,o=e.node(a);o.in-=i,l(t,n,o)}),e.removeNode(r.v),a}function c(e,t){let i=new n,a=0,o=0;e.nodes().forEach(e=>{i.setNode(e,{v:e,in:0,out:0})}),e.edges().forEach(e=>{let n=i.edge(e.v,e.w)||0,r=t(e),s=n+r;i.setEdge(e.v,e.w,s),o=Math.max(o,i.node(e.v).out+=r),a=Math.max(a,i.node(e.w).in+=r)});let s=u(o+a+3).map(()=>new r),c=a+1;return i.nodes().forEach(e=>{l(s,c,i.node(e))}),{graph:i,buckets:s,zeroIdx:c}}function l(e,t,n){n.out?n.in?e[n.out-n.in+t].enqueue(n):e[e.length-1].enqueue(n):e[0].enqueue(n)}function u(e){let t=[];for(let n=0;n{var n=mg().Graph;t.exports={addBorderNode:f,addDummyNode:r,applyWithChunking:h,asNonCompoundGraph:a,buildLayerMatrix:l,intersectRect:c,mapValues:w,maxRank:g,normalizeRanks:u,notime:y,partition:_,pick:C,predecessorWeights:s,range:S,removeEmptyRanks:d,simplify:i,successorWeights:o,time:v,uniqueId:x,zipObject:T};function r(e,t,n,r){for(var i=r;e.hasNode(i);)i=x(r);return n.dummy=t,e.setNode(i,n),i}function i(e){let t=new n().setGraph(e.graph());return e.nodes().forEach(n=>t.setNode(n,e.node(n))),e.edges().forEach(n=>{let r=t.edge(n.v,n.w)||{weight:0,minlen:1},i=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)})}),t}function a(e){let t=new n({multigraph:e.isMultigraph()}).setGraph(e.graph());return e.nodes().forEach(n=>{e.children(n).length||t.setNode(n,e.node(n))}),e.edges().forEach(n=>{t.setEdge(n,e.edge(n))}),t}function o(e){let t=e.nodes().map(t=>{let n={};return e.outEdges(t).forEach(t=>{n[t.w]=(n[t.w]||0)+e.edge(t).weight}),n});return T(e.nodes(),t)}function s(e){let t=e.nodes().map(t=>{let n={};return e.inEdges(t).forEach(t=>{n[t.v]=(n[t.v]||0)+e.edge(t).weight}),n});return T(e.nodes(),t)}function c(e,t){let n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2;if(!i&&!a)throw Error(`Not possible to find intersection inside of the rectangle`);let c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=s*i/a,l=s):(i<0&&(o=-o),c=o,l=o*a/i),{x:n+c,y:r+l}}function l(e){let t=S(g(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),i=r.rank;i!==void 0&&(t[i][r.order]=n)}),t}function u(e){let t=e.nodes().map(t=>{let n=e.node(t).rank;return n===void 0?Number.MAX_VALUE:n}),n=h(Math.min,t);e.nodes().forEach(t=>{let r=e.node(t);Object.hasOwn(r,`rank`)&&(r.rank-=n)})}function d(e){let t=e.nodes().map(t=>e.node(t).rank),n=h(Math.min,t),r=[];e.nodes().forEach(t=>{let i=e.node(t).rank-n;r[i]||(r[i]=[]),r[i].push(t)});let i=0,a=e.graph().nodeRankFactor;Array.from(r).forEach((t,n)=>{t===void 0&&n%a!==0?--i:t!==void 0&&i&&t.forEach(t=>e.node(t).rank+=i)})}function f(e,t,n,i){let a={width:0,height:0};return arguments.length>=4&&(a.rank=n,a.order=i),r(e,`border`,a,t)}function p(e,t=m){let n=[];for(let r=0;rm){let n=p(t);return e.apply(null,n.map(t=>e.apply(null,t)))}else return e.apply(null,t)}function g(e){let t=e.nodes().map(t=>{let n=e.node(t).rank;return n===void 0?Number.MIN_VALUE:n});return h(Math.max,t)}function _(e,t){let n={lhs:[],rhs:[]};return e.forEach(e=>{t(e)?n.lhs.push(e):n.rhs.push(e)}),n}function v(e,t){let n=Date.now();try{return t()}finally{console.log(e+` time: `+(Date.now()-n)+`ms`)}}function y(e,t){return t()}var b=0;function x(e){return e+(``+ ++b)}function S(e,t,n=1){t??(t=e,e=0);let r=e=>ete[t]),Object.entries(e).reduce((e,[t,r])=>(e[t]=n(r,t),e),{})}function T(e,t){return e.reduce((e,n,r)=>(e[n]=t[r],e),{})}})),vg=o(((e,t)=>{var n=gg(),r=_g().uniqueId;t.exports={run:i,undo:o};function i(e){(e.graph().acyclicer===`greedy`?n(e,t(e)):a(e)).forEach(t=>{let n=e.edge(t);e.removeEdge(t),n.forwardName=t.name,n.reversed=!0,e.setEdge(t.w,t.v,n,r(`rev`))});function t(e){return t=>e.edge(t).weight}}function a(e){let t=[],n={},r={};function i(a){Object.hasOwn(r,a)||(r[a]=!0,n[a]=!0,e.outEdges(a).forEach(e=>{Object.hasOwn(n,e.w)?t.push(e):i(e.w)}),delete n[a])}return e.nodes().forEach(i),t}function o(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.reversed){e.removeEdge(t);let r=n.forwardName;delete n.reversed,delete n.forwardName,e.setEdge(t.w,t.v,n,r)}})}})),yg=o(((e,t)=>{var n=_g();t.exports={run:r,undo:a};function r(e){e.graph().dummyChains=[],e.edges().forEach(t=>i(e,t))}function i(e,t){let r=t.v,i=e.node(r).rank,a=t.w,o=e.node(a).rank,s=t.name,c=e.edge(t),l=c.labelRank;if(o===i+1)return;e.removeEdge(t);let u,d,f;for(f=0,++i;i{let n=e.node(t),r=n.edgeLabel,i;for(e.setEdge(n.edgeObj,r);n.dummy;)i=e.successors(t)[0],e.removeNode(t),r.points.push({x:n.x,y:n.y}),n.dummy===`edge-label`&&(r.x=n.x,r.y=n.y,r.width=n.width,r.height=n.height),t=i,n=e.node(t)})}})),bg=o(((e,t)=>{var{applyWithChunking:n}=_g();t.exports={longestPath:r,slack:i};function r(e){var t={};function r(i){var a=e.node(i);if(Object.hasOwn(t,i))return a.rank;t[i]=!0;let o=e.outEdges(i).map(t=>t==null?1/0:r(t.w)-e.edge(t).minlen);var s=n(Math.min,o);return s===1/0&&(s=0),a.rank=s}e.sources().forEach(r)}function i(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}})),xg=o(((e,t)=>{var n=mg().Graph,r=bg().slack;t.exports=i;function i(e){var t=new n({directed:!1}),i=e.nodes()[0],c=e.nodeCount();t.setNode(i,{});for(var l,u;a(t,e){var o=a.v,s=i===o?a.w:o;!e.hasNode(s)&&!r(t,a)&&(e.setNode(s,{}),e.setEdge(i,s,{}),n(s))})}return e.nodes().forEach(n),e.nodeCount()}function o(e,t){return t.edges().reduce((n,i)=>{let a=1/0;return e.hasNode(i.v)!==e.hasNode(i.w)&&(a=r(t,i)),at.node(e).rank+=n)}})),Sg=o(((e,t)=>{var n=xg(),r=bg().slack,i=bg().longestPath,a=mg().alg.preorder,o=mg().alg.postorder,s=_g().simplify;t.exports=c,c.initLowLimValues=f,c.initCutValues=l,c.calcCutValue=d,c.leaveEdge=m,c.enterEdge=h,c.exchangeEdges=g;function c(e){e=s(e),i(e);var t=n(e);f(t),l(t,e);for(var r,a;r=m(t);)a=h(t,e,r),g(t,e,r,a)}function l(e,t){var n=o(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(n=>u(e,t,n))}function u(e,t,n){var r=e.node(n).parent;e.edge(n,r).cutvalue=d(e,t,n)}function d(e,t,n){var r=e.node(n).parent,i=!0,a=t.edge(n,r),o=0;return a||=(i=!1,t.edge(r,n)),o=a.weight,t.nodeEdges(n).forEach(a=>{var s=a.v===n,c=s?a.w:a.v;if(c!==r){var l=s===i,u=t.edge(a).weight;if(o+=l?u:-u,v(e,n,c)){var d=e.edge(n,c).cutvalue;o+=l?-d:d}}}),o}function f(e,t){arguments.length<2&&(t=e.nodes()[0]),p(e,{},1,t)}function p(e,t,n,r,i){var a=n,o=e.node(r);return t[r]=!0,e.neighbors(r).forEach(i=>{Object.hasOwn(t,i)||(n=p(e,t,n,i,r))}),o.low=a,o.lim=n++,i?o.parent=i:delete o.parent,n}function m(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function h(e,t,n){var i=n.v,a=n.w;t.hasEdge(i,a)||(i=n.w,a=n.v);var o=e.node(i),s=e.node(a),c=o,l=!1;return o.lim>s.lim&&(c=s,l=!0),t.edges().filter(t=>l===y(e,e.node(t.v),c)&&l!==y(e,e.node(t.w),c)).reduce((e,n)=>r(t,n)!t.node(e).parent));n=n.slice(1),n.forEach(n=>{var r=e.node(n).parent,i=t.edge(n,r),a=!1;i||(i=t.edge(r,n),a=!0),t.node(n).rank=t.node(r).rank+(a?i.minlen:-i.minlen)})}function v(e,t,n){return e.hasEdge(t,n)}function y(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}})),Cg=o(((e,t)=>{var n=bg().longestPath,r=xg(),i=Sg();t.exports=a;function a(e){var t=e.graph().ranker;if(t instanceof Function)return t(e);switch(e.graph().ranker){case`network-simplex`:c(e);break;case`tight-tree`:s(e);break;case`longest-path`:o(e);break;case`none`:break;default:c(e)}}var o=n;function s(e){n(e),r(e)}function c(e){i(e)}})),wg=o(((e,t)=>{t.exports=n;function n(e){let t=i(e);e.graph().dummyChains.forEach(n=>{let i=e.node(n),a=i.edgeObj,o=r(e,t,a.v,a.w),s=o.path,c=o.lca,l=0,u=s[l],d=!0;for(;n!==a.w;){if(i=e.node(n),d){for(;(u=s[l])!==c&&e.node(u).maxRanko||s>t[c].lim));for(l=c,c=r;(c=e.parent(c))!==l;)a.push(c);return{path:i.concat(a.reverse()),lca:l}}function i(e){let t={},n=0;function r(i){let a=n;e.children(i).forEach(r),t[i]={low:a,lim:n++}}return e.children().forEach(r),t}})),Tg=o(((e,t)=>{var n=_g();t.exports={run:r,cleanup:s};function r(e){let t=n.addDummyNode(e,`root`,{},`_root`),r=a(e),s=Object.values(r),c=n.applyWithChunking(Math.max,s)-1,l=2*c+1;e.graph().nestingRoot=t,e.edges().forEach(t=>e.edge(t).minlen*=l);let u=o(e)+1;e.children().forEach(n=>i(e,t,l,u,c,r,n)),e.graph().nodeRankFactor=l}function i(e,t,r,a,o,s,c){let l=e.children(c);if(!l.length){c!==t&&e.setEdge(t,c,{weight:0,minlen:r});return}let u=n.addBorderNode(e,`_bt`),d=n.addBorderNode(e,`_bb`),f=e.node(c);e.setParent(u,c),f.borderTop=u,e.setParent(d,c),f.borderBottom=d,l.forEach(n=>{i(e,t,r,a,o,s,n);let l=e.node(n),f=l.borderTop?l.borderTop:n,p=l.borderBottom?l.borderBottom:n,m=l.borderTop?a:2*a,h=f===p?o-s[c]+1:1;e.setEdge(u,f,{weight:m,minlen:h,nestingEdge:!0}),e.setEdge(p,d,{weight:m,minlen:h,nestingEdge:!0})}),e.parent(c)||e.setEdge(t,u,{weight:0,minlen:o+s[c]})}function a(e){var t={};function n(r,i){var a=e.children(r);a&&a.length&&a.forEach(e=>n(e,i+1)),t[r]=i}return e.children().forEach(e=>n(e,1)),t}function o(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function s(e){var t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(t=>{e.edge(t).nestingEdge&&e.removeEdge(t)})}})),Eg=o(((e,t)=>{var n=_g();t.exports=r;function r(e){function t(n){let r=e.children(n),a=e.node(n);if(r.length&&r.forEach(t),Object.hasOwn(a,`minRank`)){a.borderLeft=[],a.borderRight=[];for(let t=a.minRank,r=a.maxRank+1;t{t.exports={adjust:n,undo:r};function n(e){let t=e.graph().rankdir.toLowerCase();(t===`lr`||t===`rl`)&&i(e)}function r(e){let t=e.graph().rankdir.toLowerCase();(t===`bt`||t===`rl`)&&o(e),(t===`lr`||t===`rl`)&&(c(e),i(e))}function i(e){e.nodes().forEach(t=>a(e.node(t))),e.edges().forEach(t=>a(e.edge(t)))}function a(e){let t=e.width;e.width=e.height,e.height=t}function o(e){e.nodes().forEach(t=>s(e.node(t))),e.edges().forEach(t=>{let n=e.edge(t);n.points.forEach(s),Object.hasOwn(n,`y`)&&s(n)})}function s(e){e.y=-e.y}function c(e){e.nodes().forEach(t=>l(e.node(t))),e.edges().forEach(t=>{let n=e.edge(t);n.points.forEach(l),Object.hasOwn(n,`x`)&&l(n)})}function l(e){let t=e.x;e.x=e.y,e.y=t}})),Og=o(((e,t)=>{var n=_g();t.exports=r;function r(e){let t={},r=e.nodes().filter(t=>!e.children(t).length),i=r.map(t=>e.node(t).rank),a=n.applyWithChunking(Math.max,i),o=n.range(a+1).map(()=>[]);function s(n){t[n]||(t[n]=!0,o[e.node(n).rank].push(n),e.successors(n).forEach(s))}return r.sort((t,n)=>e.node(t).rank-e.node(n).rank).forEach(s),o}})),kg=o(((e,t)=>{var n=_g().zipObject;t.exports=r;function r(e,t){let n=0;for(let r=1;rt)),a=t.flatMap(t=>e.outEdges(t).map(t=>({pos:i[t.w],weight:e.edge(t).weight})).sort((e,t)=>e.pos-t.pos)),o=1;for(;o{let t=e.pos+o;c[t]+=e.weight;let n=0;for(;t>0;)t%2&&(n+=c[t+1]),t=t-1>>1,c[t]+=e.weight;l+=e.weight*n}),l}})),Ag=o(((e,t)=>{t.exports=n;function n(e,t=[]){return t.map(t=>{let n=e.inEdges(t);if(n.length){let r=n.reduce((t,n)=>{let r=e.edge(n),i=e.node(n.v);return{sum:t.sum+r.weight*i.order,weight:t.weight+r.weight}},{sum:0,weight:0});return{v:t,barycenter:r.sum/r.weight,weight:r.weight}}else return{v:t}})}})),jg=o(((e,t)=>{var n=_g();t.exports=r;function r(e,t){let n={};return e.forEach((e,t)=>{let r=n[e.v]={indegree:0,in:[],out:[],vs:[e.v],i:t};e.barycenter!==void 0&&(r.barycenter=e.barycenter,r.weight=e.weight)}),t.edges().forEach(e=>{let t=n[e.v],r=n[e.w];t!==void 0&&r!==void 0&&(r.indegree++,t.out.push(n[e.w]))}),i(Object.values(n).filter(e=>!e.indegree))}function i(e){let t=[];function r(e){return t=>{t.merged||(t.barycenter===void 0||e.barycenter===void 0||t.barycenter>=e.barycenter)&&a(e,t)}}function i(t){return n=>{n.in.push(t),--n.indegree===0&&e.push(n)}}for(;e.length;){let n=e.pop();t.push(n),n.in.reverse().forEach(r(n)),n.out.forEach(i(n))}return t.filter(e=>!e.merged).map(e=>n.pick(e,[`vs`,`i`,`barycenter`,`weight`]))}function a(e,t){let n=0,r=0;e.weight&&(n+=e.barycenter*e.weight,r+=e.weight),t.weight&&(n+=t.barycenter*t.weight,r+=t.weight),e.vs=t.vs.concat(e.vs),e.barycenter=n/r,e.weight=r,e.i=Math.min(t.i,e.i),t.merged=!0}})),Mg=o(((e,t)=>{var n=_g();t.exports=r;function r(e,t){let r=n.partition(e,e=>Object.hasOwn(e,`barycenter`)),o=r.lhs,s=r.rhs.sort((e,t)=>t.i-e.i),c=[],l=0,u=0,d=0;o.sort(a(!!t)),d=i(c,s,d),o.forEach(e=>{d+=e.vs.length,c.push(e.vs),l+=e.barycenter*e.weight,u+=e.weight,d=i(c,s,d)});let f={vs:c.flat(!0)};return u&&(f.barycenter=l/u,f.weight=u),f}function i(e,t,n){let r;for(;t.length&&(r=t[t.length-1]).i<=n;)t.pop(),e.push(r.vs),n++;return n}function a(e){return(t,n)=>t.barycentern.barycenter?1:e?n.i-t.i:t.i-n.i}})),Ng=o(((e,t)=>{var n=Ag(),r=jg(),i=Mg();t.exports=a;function a(e,t,c,l){let u=e.children(t),d=e.node(t),f=d?d.borderLeft:void 0,p=d?d.borderRight:void 0,m={};f&&(u=u.filter(e=>e!==f&&e!==p));let h=n(e,u);h.forEach(t=>{if(e.children(t.v).length){let n=a(e,t.v,c,l);m[t.v]=n,Object.hasOwn(n,`barycenter`)&&s(t,n)}});let g=r(h,c);o(g,m);let _=i(g,l);if(f&&(_.vs=[f,_.vs,p].flat(!0),e.predecessors(f).length)){let t=e.node(e.predecessors(f)[0]),n=e.node(e.predecessors(p)[0]);Object.hasOwn(_,`barycenter`)||(_.barycenter=0,_.weight=0),_.barycenter=(_.barycenter*_.weight+t.order+n.order)/(_.weight+2),_.weight+=2}return _}function o(e,t){e.forEach(e=>{e.vs=e.vs.flatMap(e=>t[e]?t[e].vs:e)})}function s(e,t){e.barycenter===void 0?(e.barycenter=t.barycenter,e.weight=t.weight):(e.barycenter=(e.barycenter*e.weight+t.barycenter*t.weight)/(e.weight+t.weight),e.weight+=t.weight)}})),Pg=o(((e,t)=>{var n=mg().Graph,r=_g();t.exports=i;function i(e,t,r,i){i||=e.nodes();let o=a(e),s=new n({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(t=>e.node(t));return i.forEach(n=>{let i=e.node(n),a=e.parent(n);(i.rank===t||i.minRank<=t&&t<=i.maxRank)&&(s.setNode(n),s.setParent(n,a||o),e[r](n).forEach(t=>{let r=t.v===n?t.w:t.v,i=s.edge(r,n),a=i===void 0?0:i.weight;s.setEdge(r,n,{weight:e.edge(t).weight+a})}),Object.hasOwn(i,`minRank`)&&s.setNode(n,{borderLeft:i.borderLeft[t],borderRight:i.borderRight[t]}))}),s}function a(e){for(var t;e.hasNode(t=r.uniqueId(`_root`)););return t}})),Fg=o(((e,t)=>{t.exports=n;function n(e,t,n){let r={},i;n.forEach(n=>{let a=e.parent(n),o,s;for(;a;){if(o=e.parent(a),o?(s=r[o],r[o]=a):(s=i,i=a),s&&s!==a){t.setEdge(s,a);return}a=o}})}})),Ig=o(((e,t)=>{var n=Og(),r=kg(),i=Ng(),a=Pg(),o=Fg(),s=mg().Graph,c=_g();t.exports=l;function l(e,t){if(t&&typeof t.customOrder==`function`){t.customOrder(e,l);return}let i=c.maxRank(e),a=u(e,c.range(1,i+1),`inEdges`),o=u(e,c.range(i-1,-1,-1),`outEdges`),s=n(e);if(f(e,s),t&&t.disableOptimalOrderHeuristic)return;let p=1/0,m;for(let t=0,n=0;n<4;++t,++n){d(t%2?a:o,t%4>=2),s=c.buildLayerMatrix(e);let i=r(e,s);i{r.has(e)||r.set(e,[]),r.get(e).push(t)};for(let t of e.nodes()){let n=e.node(t);if(typeof n.rank==`number`&&i(n.rank,t),typeof n.minRank==`number`&&typeof n.maxRank==`number`)for(let e=n.minRank;e<=n.maxRank;e++)e!==n.rank&&i(e,t)}return t.map(function(t){return a(e,t,n,r.get(t)||[])})}function d(e,t){let n=new s;e.forEach(function(e){let r=e.graph().root,a=i(e,r,n,t);a.vs.forEach((t,n)=>e.node(t).order=n),o(e,n,a.vs)})}function f(e,t){Object.values(t).forEach(t=>t.forEach((t,n)=>e.node(t).order=n))}})),Lg=o(((e,t)=>{var n=mg().Graph,r=_g();t.exports={positionX:h,findType1Conflicts:i,findType2Conflicts:a,addConflict:s,hasConflict:c,verticalAlignment:l,horizontalCompaction:u,alignCoordinates:p,findSmallestWidthAlignment:f,balance:m};function i(e,t){let n={};function r(t,r){let i=0,a=0,c=t.length,l=r[r.length-1];return r.forEach((t,u)=>{let d=o(e,t),f=d?e.node(d).order:c;(d||t===l)&&(r.slice(a,u+1).forEach(t=>{e.predecessors(t).forEach(r=>{let a=e.node(r),o=a.order;(o{l=t[r],e.node(l).dummy&&e.predecessors(l).forEach(t=>{let r=e.node(t);r.dummy&&(r.orderc)&&s(n,t,l)})})}function a(t,n){let r=-1,a,o=0;return n.forEach((s,c)=>{if(e.node(s).dummy===`border`){let t=e.predecessors(s);t.length&&(a=e.node(t[0]).order,i(n,o,c,r,a),o=c,r=a)}i(n,o,n.length,a,t.length)}),n}return t.length&&t.reduce(a),n}function o(e,t){if(e.node(t).dummy)return e.predecessors(t).find(t=>e.node(t).dummy)}function s(e,t,n){if(t>n){let e=t;t=n,n=e}let r=e[t];r||(e[t]=r={}),r[n]=!0}function c(e,t,n){if(t>n){let e=t;t=n,n=e}return!!e[t]&&Object.hasOwn(e[t],n)}function l(e,t,n,r){let i={},a={},o={};return t.forEach(e=>{e.forEach((e,t)=>{i[e]=e,a[e]=e,o[e]=t})}),t.forEach(e=>{let t=-1;e.forEach(e=>{let s=r(e);if(s.length){s=s.sort((e,t)=>o[e]-o[t]);let r=(s.length-1)/2;for(let l=Math.floor(r),u=Math.ceil(r);l<=u;++l){let r=s[l];a[e]===e&&tMath.max(e,a[t.v]+o.edge(t)),0)}function u(t){let n=o.outEdges(t).reduce((e,t)=>Math.min(e,a[t.w]-o.edge(t)),1/0),r=e.node(t);n!==1/0&&r.borderType!==s&&(a[t]=Math.max(a[t],n))}return c(l,o.predecessors.bind(o)),c(u,o.successors.bind(o)),Object.keys(r).forEach(e=>a[e]=a[n[e]]),a}function d(e,t,r,i){let a=new n,o=e.graph(),s=g(o.nodesep,o.edgesep,i);return t.forEach(t=>{let n;t.forEach(t=>{let i=r[t];if(a.setNode(i),n){var o=r[n],c=a.edge(o,i);a.setEdge(o,i,Math.max(s(e,t,n),c||0))}n=t})}),a}function f(e,t){return Object.values(t).reduce((t,n)=>{let r=-1/0,i=1/0;Object.entries(n).forEach(([t,n])=>{let a=_(e,t)/2;r=Math.max(n+a,r),i=Math.min(n-a,i)});let a=r-i;return a{[`l`,`r`].forEach(o=>{let s=n+o,c=e[s];if(c===t)return;let l=Object.values(c),u=i-r.applyWithChunking(Math.min,l);o!==`l`&&(u=a-r.applyWithChunking(Math.max,l)),u&&(e[s]=r.mapValues(c,e=>e+u))})})}function m(e,t){return r.mapValues(e.ul,(n,r)=>{if(t)return e[t.toLowerCase()][r];{let t=Object.values(e).map(e=>e[r]).sort((e,t)=>e-t);return(t[1]+t[2])/2}})}function h(e){let t=r.buildLayerMatrix(e),n=Object.assign(i(e,t),a(e,t)),o={},s;return[`u`,`d`].forEach(i=>{s=i===`u`?t:Object.values(t).reverse(),[`l`,`r`].forEach(t=>{t===`r`&&(s=s.map(e=>Object.values(e).reverse()));let a=(i===`u`?e.predecessors:e.successors).bind(e),c=l(e,s,n,a),d=u(e,s,c.root,c.align,t===`r`);t===`r`&&(d=r.mapValues(d,e=>-e)),o[i+t]=d})}),p(o,f(e,o)),m(o,e.graph().align)}function g(e,t,n){return(r,i,a)=>{let o=r.node(i),s=r.node(a),c=0,l;if(c+=o.width/2,Object.hasOwn(o,`labelpos`))switch(o.labelpos.toLowerCase()){case`l`:l=-o.width/2;break;case`r`:l=o.width/2;break}if(l&&(c+=n?l:-l),l=0,c+=(o.dummy?t:e)/2,c+=(s.dummy?t:e)/2,c+=s.width/2,Object.hasOwn(s,`labelpos`))switch(s.labelpos.toLowerCase()){case`l`:l=s.width/2;break;case`r`:l=-s.width/2;break}return l&&(c+=n?l:-l),l=0,c}}function _(e,t){return e.node(t).width}})),Rg=o(((e,t)=>{var n=_g(),r=Lg().positionX;t.exports=i;function i(e){e=n.asNonCompoundGraph(e),a(e),Object.entries(r(e)).forEach(([t,n])=>e.node(t).x=n)}function a(e){let t=n.buildLayerMatrix(e),r=e.graph().ranksep,i=0;t.forEach(t=>{let n=t.reduce((t,n)=>{let r=e.node(n).height;return t>r?t:r},0);t.forEach(t=>e.node(t).y=i+n/2),i+=n+r})}})),zg=o(((e,t)=>{var n=vg(),r=yg(),i=Cg(),a=_g().normalizeRanks,o=wg(),s=_g().removeEmptyRanks,c=Tg(),l=Eg(),u=Dg(),d=Ig(),f=Rg(),p=_g(),m=mg().Graph;t.exports=h;function h(e,t){let n=t&&t.debugTiming?p.time:p.notime;n(`layout`,()=>{let r=n(` buildLayoutGraph`,()=>E(e));n(` runLayout`,()=>g(r,n,t)),n(` updateInputGraph`,()=>_(e,r))})}function g(e,t,m){t(` makeSpaceForEdgeLabels`,()=>D(e)),t(` removeSelfEdges`,()=>P(e)),t(` acyclic`,()=>n.run(e)),t(` nestingGraph.run`,()=>c.run(e)),t(` rank`,()=>i(p.asNonCompoundGraph(e))),t(` injectEdgeLabelProxies`,()=>O(e)),t(` removeEmptyRanks`,()=>s(e)),t(` nestingGraph.cleanup`,()=>c.cleanup(e)),t(` normalizeRanks`,()=>a(e)),t(` assignRankMinMax`,()=>k(e)),t(` removeEdgeLabelProxies`,()=>A(e)),t(` normalize.run`,()=>r.run(e)),t(` parentDummyChains`,()=>o(e)),t(` addBorderSegments`,()=>l(e)),t(` order`,()=>d(e,m)),t(` insertSelfEdges`,()=>F(e)),t(` adjustCoordinateSystem`,()=>u.adjust(e)),t(` position`,()=>f(e)),t(` positionSelfEdges`,()=>ne(e)),t(` removeBorderNodes`,()=>te(e)),t(` normalize.undo`,()=>r.undo(e)),t(` fixupEdgeLabelCoords`,()=>N(e)),t(` undoCoordinateSystem`,()=>u.undo(e)),t(` translateGraph`,()=>j(e)),t(` assignNodeIntersects`,()=>M(e)),t(` reversePoints`,()=>ee(e)),t(` acyclic.undo`,()=>n.undo(e))}function _(e,t){e.nodes().forEach(n=>{let r=e.node(n),i=t.node(n);r&&(r.x=i.x,r.y=i.y,r.rank=i.rank,t.children(n).length&&(r.width=i.width,r.height=i.height))}),e.edges().forEach(n=>{let r=e.edge(n),i=t.edge(n);r.points=i.points,Object.hasOwn(i,`x`)&&(r.x=i.x,r.y=i.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var v=[`nodesep`,`edgesep`,`ranksep`,`marginx`,`marginy`],y={ranksep:50,edgesep:20,nodesep:50,rankdir:`tb`},b=[`acyclicer`,`ranker`,`rankdir`,`align`],x=[`width`,`height`,`rank`],S={width:0,height:0},C=[`minlen`,`weight`,`width`,`height`,`labeloffset`],w={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:`r`},T=[`labelpos`];function E(e){let t=new m({multigraph:!0,compound:!0}),n=ie(e.graph());return t.setGraph(Object.assign({},y,re(n,v),p.pick(n,b))),e.nodes().forEach(n=>{let r=re(ie(e.node(n)),x);Object.keys(S).forEach(e=>{r[e]===void 0&&(r[e]=S[e])}),t.setNode(n,r),t.setParent(n,e.parent(n))}),e.edges().forEach(n=>{let r=ie(e.edge(n));t.setEdge(n,Object.assign({},w,re(r,C),p.pick(r,T)))}),t}function D(e){let t=e.graph();t.ranksep/=2,e.edges().forEach(n=>{let r=e.edge(n);r.minlen*=2,r.labelpos.toLowerCase()!==`c`&&(t.rankdir===`TB`||t.rankdir===`BT`?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function O(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let n=e.node(t.v),r={rank:(e.node(t.w).rank-n.rank)/2+n.rank,e:t};p.addDummyNode(e,`edge-proxy`,r,`_ep`)}})}function k(e){let t=0;e.nodes().forEach(n=>{let r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=Math.max(t,r.maxRank))}),e.graph().maxRank=t}function A(e){e.nodes().forEach(t=>{let n=e.node(t);n.dummy===`edge-proxy`&&(e.edge(n.e).labelRank=n.rank,e.removeNode(t))})}function j(e){let t=1/0,n=0,r=1/0,i=0,a=e.graph(),o=a.marginx||0,s=a.marginy||0;function c(e){let a=e.x,o=e.y,s=e.width,c=e.height;t=Math.min(t,a-s/2),n=Math.max(n,a+s/2),r=Math.min(r,o-c/2),i=Math.max(i,o+c/2)}e.nodes().forEach(t=>c(e.node(t))),e.edges().forEach(t=>{let n=e.edge(t);Object.hasOwn(n,`x`)&&c(n)}),t-=o,r-=s,e.nodes().forEach(n=>{let i=e.node(n);i.x-=t,i.y-=r}),e.edges().forEach(n=>{let i=e.edge(n);i.points.forEach(e=>{e.x-=t,e.y-=r}),Object.hasOwn(i,`x`)&&(i.x-=t),Object.hasOwn(i,`y`)&&(i.y-=r)}),a.width=n-t+o,a.height=i-r+s}function M(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),i=e.node(t.w),a,o;n.points?(a=n.points[0],o=n.points[n.points.length-1]):(n.points=[],a=i,o=r),n.points.unshift(p.intersectRect(r,a)),n.points.push(p.intersectRect(i,o))})}function N(e){e.edges().forEach(t=>{let n=e.edge(t);if(Object.hasOwn(n,`x`))switch((n.labelpos===`l`||n.labelpos===`r`)&&(n.width-=n.labeloffset),n.labelpos){case`l`:n.x-=n.width/2+n.labeloffset;break;case`r`:n.x+=n.width/2+n.labeloffset;break}})}function ee(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function te(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),i=e.node(n.borderBottom),a=e.node(n.borderLeft[n.borderLeft.length-1]),o=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(o.x-a.x),n.height=Math.abs(i.y-r.y),n.x=a.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy===`border`&&e.removeNode(t)})}function P(e){e.edges().forEach(t=>{if(t.v===t.w){var n=e.node(t.v);n.selfEdges||=[],n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function F(e){p.buildLayerMatrix(e).forEach(t=>{var n=0;t.forEach((t,r)=>{var i=e.node(t);i.order=r+n,(i.selfEdges||[]).forEach(t=>{p.addDummyNode(e,`selfedge`,{width:t.label.width,height:t.label.height,rank:i.rank,order:r+ ++n,e:t.e,label:t.label},`_se`)}),delete i.selfEdges})})}function ne(e){e.nodes().forEach(t=>{var n=e.node(t);if(n.dummy===`selfedge`){var r=e.node(n.e.v),i=r.x+r.width/2,a=r.y,o=n.x-i,s=r.height/2;e.setEdge(n.e,n.label),e.removeNode(t),n.label.points=[{x:i+2*o/3,y:a-s},{x:i+5*o/6,y:a-s},{x:i+o,y:a},{x:i+5*o/6,y:a+s},{x:i+2*o/3,y:a+s}],n.label.x=n.x,n.label.y=n.y}})}function re(e,t){return p.mapValues(p.pick(e,t),Number)}function ie(e){var t={};return e&&Object.entries(e).forEach(([e,n])=>{typeof e==`string`&&(e=e.toLowerCase()),t[e]=n}),t}})),Bg=o(((e,t)=>{var n=_g(),r=mg().Graph;t.exports={debugOrdering:i};function i(e){let t=n.buildLayerMatrix(e),i=new r({compound:!0,multigraph:!0}).setGraph({});return e.nodes().forEach(t=>{i.setNode(t,{label:t}),i.setParent(t,`layer`+e.node(t).rank)}),e.edges().forEach(e=>i.setEdge(e.v,e.w,{},e.name)),t.forEach((e,t)=>{let n=`layer`+t;i.setNode(n,{rank:`same`}),e.reduce((e,t)=>(i.setEdge(e,t,{style:`invis`}),t))}),i}})),Vg=o(((e,t)=>{t.exports=`1.1.8`})),Hg=l(o(((e,t)=>{t.exports={graphlib:mg(),layout:zg(),debug:Bg(),util:{time:_g().time,notime:_g().notime},version:Vg()}}))(),1),Ug=200,Wg=56,Gg=20,Kg=40,qg=20,Jg=12,Yg=16,Xg=46,Zg=16,Qg=Ug,$g=14;function e_(e){return{agents:e.agents,routes:e.routes,parallelGroups:e.parallelGroups,forEachGroups:e.forEachGroups,nodes:e.nodes,groupProgress:e.groupProgress,entryPoint:e.entryPoint,parentAgent:e.parentAgent,children:e.children}}function t_(e,t,n){let{nodes:r,edges:i}=s_(e,t,n);return{nodes:r,edges:i}}function n_(e,t,n){let r=[],i=(e,t,n)=>{for(let a of e){if((a.type||`agent`)!==`workflow`)continue;let e=-1;for(let n=t.length-1;n>=0;n--)if(t[n].slotKey===a.name){e=n;break}if(e<0)continue;let o=t[e];o.agents.length!==0&&(r.push(Fh([...n,e])),i(o.agents,o.children,[...n,e]))}let a=new Set;for(let e of t){let t=Bh(e.slotKey);!t||a.has(t.group)||(a.add(t.group),r.push(Rh(n,t.group)))}};return i(e,t,n),r}function r_(e,t){let n=[],r=e,i=[];for(let e of t){let t=r[e];if(!t)break;let a=Bh(t.slotKey);a&&n.push(Rh(i,a.group)),i.push(e),n.push(Fh(i)),r=t.children}return n}function i_(e,t){let n=[];for(let r=0;r0,m=p&&r.has(u),h={label:f?f.key:c.slotKey,name:c.slotKey,contextPath:t,type:`workflow`,status:c.status||`pending`,canExpand:p,expanded:m,childContextKey:u,childName:c.workflowName||void 0,iterationContextPath:e,isForEachIteration:!0};if(m){let t=s_(e_(c),e,r,!0),l=t.width+Yg*2,u=t.height+Xg+Zg;i.push({id:d,type:`workflowNode`,position:{x:Yg,y:o},parentId:n,extent:`parent`,data:h,style:{width:l,height:u}});for(let e of t.nodes)e.parentId||(e.parentId=d,e.extent=`parent`,e.position={x:e.position.x+Yg,y:e.position.y+Xg}),i.push(e);for(let e of t.edges)a.push(e);o+=u+$g,s=Math.max(s,l)}else i.push({id:d,type:`workflowNode`,position:{x:Yg,y:o},parentId:n,extent:`parent`,data:h}),o+=70}return{nodes:i,edges:a,width:s+Yg*2,height:(e.length>0?o-$g:Xg)+Zg}}function o_(e){return e===`script`?`scriptNode`:e===`set`?`setNode`:e===`mcp`?`mcpNode`:e===`human_gate`||e===`questions`?`gateNode`:e===`workflow`?`workflowNode`:e===`wait`?`waitNode`:e===`terminate`?`terminateNode`:`agentNode`}function s_(e,t,n,r=!1){let i=[],a=[],o=new Set,s=new Set,c=e.parentAgent!=null,l=e=>Ih(t,e),u=[],d=[],f=[],p=new Map(e.agents.map(e=>[e.name,e.type||`agent`])),m=new Map;for(let t of e.parallelGroups)for(let e of t.agents)s.add(e),m.set(e,t.name);for(let n of e.parallelGroups){let r=e.nodes[n.name],a=n.agents.length,s=Kg+a*Wg+(a-1)*Jg+qg;i.push({id:l(n.name),type:`groupNode`,position:{x:0,y:0},data:{label:n.name,name:n.name,contextPath:t,type:`parallel_group`,status:r?.status||`pending`,groupName:n.name,progress:e.groupProgress[n.name]},style:{width:240,height:s}});for(let r=0;r0,u=Rh(t,r.name);if(c&&n.has(u)){let o=a_(s,t,u,n);i.push({id:l(r.name),type:`groupNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:`for_each_group`,status:a?.status||`pending`,groupName:r.name,progress:e.groupProgress[r.name],expanded:!0,canExpand:!0,groupExpansionKey:u},style:{width:o.width,height:o.height}});for(let e of o.nodes)d.push(e);for(let e of o.edges)f.push(e)}else i.push({id:l(r.name),type:`groupNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:`for_each_group`,status:a?.status||`pending`,groupName:r.name,progress:e.groupProgress[r.name],expanded:!1,canExpand:c,groupExpansionKey:c?u:void 0}});o.add(r.name)}for(let r of e.agents){if(o.has(r.name)||s.has(r.name))continue;let a=r.type||`agent`,c=e.nodes[r.name],d=o_(a);if(a===`workflow`){let s=-1;for(let t=e.children.length-1;t>=0;t--)if(e.children[t].slotKey===r.name){s=t;break}let d=s>=0?e.children[s]:void 0,f=s>=0?Fh([...t,s]):void 0,p=!!d&&d.agents.length>0;if(p&&f!=null&&n.has(f)&&d){let e=s_(e_(d),[...t,s],n,!0),o=e.width+Yg*2,p=e.height+Xg+Zg;i.push({id:l(r.name),type:`workflowNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:a,status:c?.status||`pending`,expanded:!0,canExpand:!0,childContextKey:f,childName:d.workflowName||void 0},style:{width:o,height:p}}),u.push({containerId:l(r.name),sub:e})}else i.push({id:l(r.name),type:`workflowNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:a,status:c?.status||`pending`,expanded:!1,canExpand:p,childContextKey:f,childName:d?.workflowName||void 0}});o.add(r.name);continue}i.push({id:l(r.name),type:d,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:a,status:c?.status||`pending`}}),o.add(r.name)}let h=!1;for(let t of e.routes)t.to===`$end`&&(h=!0);if(h){let n=e.nodes.$end;i.push({id:l(`$end`),type:c?`egressNode`:`endNode`,position:{x:0,y:0},data:{label:`$end`,name:`$end`,contextPath:t,type:c?`egress`:`end`,status:n?.status||`pending`,...c&&!r?{parentAgent:e.parentAgent??void 0}:{}}})}if(e.entryPoint){let n=e.nodes.$start;i.push({id:l(`$start`),type:c?`ingressNode`:`startNode`,position:{x:0,y:0},data:{label:`$start`,name:`$start`,contextPath:t,type:c?`ingress`:`start`,status:n?.status||`pending`,...c&&!r?{parentAgent:e.parentAgent??void 0}:{}}}),a.push({id:`${l(`$start`)}->@entry`,source:l(`$start`),target:l(e.entryPoint),type:`animatedEdge`,data:{},animated:!1})}let g=new Set(i.map(e=>e.id)),_=new Map;for(let e of i)e.parentId&&_.set(e.id,e.parentId);let v=new Map;for(let t of e.routes){let e=_.get(l(t.from))??l(t.from),n=_.get(l(t.to))??l(t.to);if(!g.has(e)||!g.has(n)||e===n)continue;let r=`${e}->${n}`,i=v.get(r);if(i){i.when!==t.when&&(a[i.idx].data={when:void 0});continue}let o=a.length;v.set(r,{when:t.when,idx:o});let s=`${r}${t.when?`[${t.when}]`:``}`;a.push({id:s,source:e,target:n,type:`animatedEdge`,data:{when:t.when},animated:!1})}let{width:y,height:b}=u_(i,a,c_(i,a,l(`$start`)));for(let{containerId:e,sub:t}of u){for(let n of t.nodes)n.parentId||(n.parentId=e,n.extent=`parent`,n.position={x:n.position.x+Yg,y:n.position.y+Xg}),i.push(n);for(let e of t.edges)a.push(e)}for(let e of d)i.push(e);for(let e of f)a.push(e);return{nodes:i,edges:a,width:y,height:b}}function c_(e,t,n){let r=new Set(e.filter(e=>!e.parentId).map(e=>e.id)),i=new Map;for(let e of t)!r.has(e.source)||!r.has(e.target)||(i.has(e.source)||i.set(e.source,[]),i.get(e.source).push({target:e.target,edgeId:e.id}));for(let e of i.values())e.sort((e,t)=>e.targett.target));let a=new Set,o=new Set,s=new Set,c=e=>{s.add(e),o.add(e);for(let{target:t,edgeId:n}of i.get(e)??[])o.has(t)?a.add(n):s.has(t)||c(t);o.delete(e)};r.has(n)&&c(n);for(let e of[...i.keys()].sort())s.has(e)||c(e);return a}function l_(e){let t=e.style?.width,n=e.style?.height;return typeof t==`number`&&typeof n==`number`?{w:t,h:n}:{w:Ug,h:Wg}}function u_(e,t,n){let r=new Hg.default.graphlib.Graph;r.setDefaultEdgeLabel(()=>({})),r.setGraph({rankdir:`TB`,nodesep:50,ranksep:70,marginx:30,marginy:30});for(let t of e){if(t.parentId)continue;let{w:e,h:n}=l_(t);r.setNode(t.id,{width:e,height:n})}for(let e of t)!r.hasNode(e.source)||!r.hasNode(e.target)||(n.has(e.id)?r.setEdge(e.target,e.source):r.setEdge(e.source,e.target));Hg.default.layout(r);let i=1/0,a=1/0,o=-1/0,s=-1/0;for(let t of e){if(t.parentId)continue;let e=r.node(t.id);if(!e)continue;let{w:n,h:c}=l_(t),l=e.x-n/2,u=e.y-c/2;t.position={x:l,y:u},i=Math.min(i,l),a=Math.min(a,u),o=Math.max(o,l+n),s=Math.max(s,u+c)}if(!Number.isFinite(i))return{width:Ug,height:Wg};for(let t of e)t.parentId||(t.position={x:t.position.x-i,y:t.position.y-a});return{width:o-i,height:s-a}}var d_=400;function f_(){let e=new URLSearchParams(window.location.search);return{subworkflowPath:e.get(`subworkflow`),agent:e.get(`agent`)}}function p_(e,t){let n=[],r=e;for(let e of t){let t=-1;for(let n=r.length-1;n>=0;n--)if(r[n].slotKey===e){t=n;break}if(t===-1){for(let n=r.length-1;n>=0;n--)if(r[n].parentAgent===e){t=n;break}}if(t===-1)return{path:n,failedSegment:e};n.push(t),r=r[t].children}return{path:n,failedSegment:null}}function m_(e,t){let n=e,r=null;for(let e of t){if(r=n[e]??null,!r)return null;n=r.children}return r}function h_(e,t,n=[]){let r=[];for(let i=0;ie.name===t)&&r.push({path:o,ctx:a}),a.children.length>0&&r.push(...h_(a.children,t,o))}return r}function g_(e){return e.length===0?null:[...e].sort((e,t)=>{let n=+(e.ctx.status===`running`),r=+(t.ctx.status===`running`);if(n!==r)return r-n;if(e.path.length!==t.path.length)return t.path.length-e.path.length;for(let n=0;n{if(n.current||!s)return;let e=null,c=null,l=null,u=null,d=(e,t)=>{let n=B.getState(),r=n.subworkflowContexts;e.length>0&&!m_(r,e)&&console.warn(`[use-deep-link] reveal target path is not fully materialized; expanding only the resolved prefix`,e),n.expandContexts(r_(r,e)),B.setState({viewContextPath:[],selectedNode:t})},f=e=>{let t=0,n=()=>{l=null;let a=i(e)?.measured;a?.width&&a?.height?(Jh(d_),r({nodes:[{id:e}],padding:.5,duration:d_})):t++<40?l=requestAnimationFrame(n):(console.warn(`[use-deep-link] node "${e}" was not measured in time; fitting the whole graph instead`),Jh(d_),r({padding:.2,duration:d_}))};l=requestAnimationFrame(n)},p=()=>{if(n.current)return;n.current=!0,e&&clearTimeout(e),c&&clearTimeout(c),u&&u();let r=B.getState();if(r.agents.length===0){t({message:`Workflow state did not load.`});return}let i=[];if(a){let e=a.split(`/`).filter(Boolean),n=p_(r.subworkflowContexts,e);if(n.failedSegment){let r=e.slice(0,n.path.length).join(`/`);d(n.path,null),t({message:`Subworkflow "${n.failedSegment}" not found${r?` (resolved: ${r})`:``}. It may not have started yet.`});return}i=n.path}if(o){if((i.length===0?r.agents:m_(r.subworkflowContexts,i)?.agents??[]).some(e=>e.name===o)){let e=Ih(i,o);d(i,e),f(e);return}let e=h_(r.subworkflowContexts,o);if(e.length===0){let e=a||`root workflow`;d(i,null),t({message:`Agent "${o}" not found in ${e}.`});return}if(a){let n=e.slice(0,5).map(e=>__(r.subworkflowContexts,e.path)).join(`, `),s=e.length>5?`, and ${e.length-5} more`:``;d(i,null),t({message:`Agent "${o}" not found in ${a}. Found in: ${n}${s}`});return}let n=g_(e),s=Ih(n.path,o);d(n.path,s),f(s);return}if(d(i,null),i.length>0){let e=m_(r.subworkflowContexts,i);e&&f(Ih(i.slice(0,-1),e.slotKey))}},m=()=>{try{p()}catch(e){console.warn(`[use-deep-link] failed to apply deep-link target`,e),t({message:`Could not resolve the deep-link target.`})}},h=()=>{let e=B.getState();if(e.agents.length===0)return!1;if(e.workflowStatus!==`running`&&e.workflowStatus!==`pending`)return!0;if(a){let t=a.split(`/`).filter(Boolean),{failedSegment:n}=p_(e.subworkflowContexts,t);if(n)return!1}return!(o&&!a&&!e.agents.some(e=>e.name===o)&&h_(e.subworkflowContexts,o).length===0)},g=()=>{e&&clearTimeout(e),e=setTimeout(()=>{n.current||h()&&m()},200)};return u=B.subscribe(g),c=setTimeout(()=>{n.current||m()},5e3),g(),()=>{e&&clearTimeout(e),c&&clearTimeout(c),l!=null&&cancelAnimationFrame(l),u&&u()}},[s,a,o,r,i]),e}function y_(e){let t=new Map;for(let n of e)t.set(n.id,n);let n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,a=r,o={x:0,y:0};for(;a&&!i.has(a.id);){i.add(a.id),e.push(a);let r=a.parentId;if(r===void 0)break;let s=n.get(r);if(s){o=s;break}a=t.get(r)}for(let t=e.length-1;t>=0;t--){let r=e[t];o={x:o.x+r.position.x,y:o.y+r.position.y},n.set(r.id,o)}}return n}function b_(e,t){return e?.data?.childContextKey===t||e?.data?.groupExpansionKey===t}function x_(e,t=y_(e.prevNodes)){let{prevNodes:n,nextNodes:r,anchorKeyHint:i,viewport:a,paneSize:o}=e,s=new Map;for(let e of n)s.set(e.id,e);let c=r.filter(e=>s.has(e.id));if(c.length===0)return null;if(i!==null){let e=c.find(e=>b_(e,i)||b_(s.get(e.id),i));if(e)return e.id}if(o.width<=0||o.height<=0)return null;let l={x:(-a.x+o.width/2)/a.zoom,y:(-a.y+o.height/2)/a.zoom},u=null,d=1/0;for(let e of c){let n=t.get(e.id);if(!n)continue;let r=n.x-l.x,i=n.y-l.y,a=r*r+i*i;(a1||n===null)return{hint:null,stickyRebuilds:0};let s=r+1;return{hint:s>2?null:n,stickyRebuilds:s}}var X={pending:`#6b7280`,running:`#3b82f6`,completed:`#22c55e`,failed:`#ef4444`,paused:`#f59e0b`,idle:`#6b7280`,waiting:`#a855f7`};function w_({data:e,children:t}){let[n,r]=(0,v.useState)(!1),i=(0,v.useRef)(null),a=(0,v.useCallback)(()=>{i.current=setTimeout(()=>r(!0),200)},[]),o=(0,v.useCallback)(()=>{i.current&&clearTimeout(i.current),r(!1)},[]),s=X[e.status]||X.pending;return(0,H.jsxs)(`div`,{className:`relative`,onMouseEnter:a,onMouseLeave:o,children:[t,n&&(0,H.jsxs)(`div`,{className:U(`absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-2`,`bg-[var(--surface-raised)] border border-[var(--border)] shadow-lg`,`rounded-lg px-3 py-2 max-w-[260px] pointer-events-none`,`animate-[tooltip-in_150ms_ease-out]`),children:[(0,H.jsx)(`div`,{className:`absolute top-full left-1/2 -translate-x-1/2 w-0 h-0 border-x-[6px] border-x-transparent border-t-[6px] border-t-[var(--border)]`}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5 text-[11px]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`w-2 h-2 rounded-full flex-shrink-0`,style:{backgroundColor:s}}),(0,H.jsx)(`span`,{className:`font-medium text-[var(--text)] capitalize`,children:e.status}),e.iteration!=null&&e.iteration>1&&(0,H.jsxs)(`span`,{className:`text-[var(--text-muted)] ml-auto`,children:[`iter `,e.iteration]})]}),(0,H.jsx)(`div`,{className:`h-px bg-[var(--border)]`}),(0,H.jsxs)(`div`,{className:`grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5`,children:[e.elapsed!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Elapsed`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] font-mono`,children:W(e.elapsed)})]}),e.model&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Model`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] truncate`,children:e.model})]}),e.tokens!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Tokens`}),(0,H.jsxs)(`span`,{className:`text-[var(--text)] font-mono`,children:[_t(e.tokens),e.inputTokens!=null&&e.outputTokens!=null&&(0,H.jsxs)(`span`,{className:`text-[var(--text-muted)]`,children:[` `,`(`,_t(e.inputTokens),`↑ `,_t(e.outputTokens),`↓)`]})]})]}),e.costUsd!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Cost`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] font-mono`,children:vt(e.costUsd)})]}),e.exitCode!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Exit code`}),(0,H.jsx)(`span`,{className:U(`font-mono`,e.exitCode===0?`text-[var(--completed)]`:`text-[var(--failed)]`),children:e.exitCode})]}),e.selectedOption&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Selected`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] truncate`,children:e.selectedOption})]}),e.terminationStatus&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Termination`}),(0,H.jsx)(`span`,{className:U(`font-mono capitalize`,e.terminationStatus===`success`?`text-[var(--completed)]`:`text-[var(--failed)]`),children:e.terminationStatus})]})]}),e.reason&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`h-px bg-[var(--border)]`}),(0,H.jsxs)(`div`,{className:U(`leading-tight break-words`,e.terminationStatus===`failed`?`text-red-400`:`text-[var(--text)]`),children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] mr-1`,children:`Reason:`}),e.reason.slice(0,160),e.reason.length>160?`...`:``]})]}),e.errorMessage&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`h-px bg-[var(--border)]`}),(0,H.jsxs)(`div`,{className:`text-red-400 leading-tight`,children:[e.errorType&&(0,H.jsxs)(`span`,{className:`font-medium`,children:[e.errorType,`: `]}),(0,H.jsxs)(`span`,{className:`break-words`,children:[e.errorMessage.slice(0,120),e.errorMessage.length>120?`...`:``]})]})]})]})]})]})}var T_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.model,c=r?.tokens,l=r?.input_tokens,u=r?.output_tokens,d=r?.cost_usd,f=r?.iteration,p=r?.error_type,m=r?.error_message,h=r?.context_pct,g=r?.provider_tier,_=r?.provider_name,v=E_(r?.startedAt,i),y=D_(i),b=(()=>{if(i===`failed`&&m)return{text:m.length>40?m.slice(0,37)+`...`:m,className:`text-red-400`};if(i===`running`)return{text:v,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return o!=null&&e.push(W(o)),c!=null&&e.push(`${_t(c)} tok`),d!=null&&e.push(vt(d)),{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,elapsed:o,model:s,tokens:c,inputTokens:l,outputTokens:u,costUsd:d,iteration:f,errorType:p,errorMessage:m},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,y),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(A,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),f!=null&&f>1&&(0,H.jsxs)(`span`,{className:`flex-shrink-0 inline-flex items-center justify-center px-1.5 py-0.5 rounded-full text-[9px] font-bold leading-none`,style:{backgroundColor:`${a}25`,color:a},children:[`x`,f]}),g===`experimental`&&(0,H.jsx)(`span`,{className:`flex-shrink-0 inline-flex items-center justify-center px-1.5 py-0.5 rounded-full text-[9px] font-bold leading-none uppercase tracking-wide`,style:{backgroundColor:`rgba(245, 158, 11, 0.18)`,color:`#f59e0b`},title:`Experimental provider: ${_??`unknown`}`,children:`exp`})]}),b.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,b.className),children:b.text})]}),h!=null&&(0,H.jsx)(`div`,{className:`absolute bottom-0 left-0 right-0 h-[2px] rounded-b-lg overflow-hidden`,style:{backgroundColor:`rgba(255,255,255,0.06)`},children:(0,H.jsx)(`div`,{className:U(`h-full transition-all duration-500`,h>=90?`animate-[context-pulse_2s_ease-in-out_infinite]`:``),style:{width:`${Math.min(h,100)}%`,backgroundColor:h>=90?`#ef4444`:h>=70?`#f59e0b`:`#22c55e`}})})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function E_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(W((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(W((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function D_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var O_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.exit_code,c=r?.error_type,l=r?.error_message,u=k_(r?.startedAt,i),d=A_(i),f=(()=>{if(i===`failed`&&l)return{text:l.length>40?l.slice(0,37)+`...`:l,className:`text-red-400`};if(i===`running`)return{text:u,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return o!=null&&e.push(W(o)),s!=null&&e.push(`exit ${s}`),{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,elapsed:o,exitCode:s,errorType:c,errorMessage:l},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,d),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(De,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),f.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,f.className),children:f.text})]})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function k_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(W((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(W((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function A_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var j_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.set_output_keys,c=r?.set_value_repr,l=r?.error_type,u=r?.error_message,d=M_(r?.startedAt,i),f=N_(i),p=(()=>{if(i===`failed`&&u)return{text:u.length>40?u.slice(0,37)+`...`:u,className:`text-red-400`};if(i===`running`)return{text:d,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];if(o!=null&&e.push(W(o)),s&&s.length>0)e.push(`${s.length} key${s.length===1?``:`s`}`);else if(c){let t=c.length>24?c.slice(0,21)+`…`:c;e.push(t)}return{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,elapsed:o,errorType:l,errorMessage:u},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,f),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(ke,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),p.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,p.className),children:p.text})]})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function M_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(W((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(W((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function N_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var P_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.error_type,c=r?.error_message,l=r?.mcp_server,u=r?.mcp_tool,d=r?.mcp_result_bytes,f=r?.mcp_truncated,p=F_(r?.startedAt,i),m=I_(i),h=(()=>{if(i===`failed`&&c)return{text:c.length>40?c.slice(0,37)+`...`:c,className:`text-red-400`};if(i===`running`)return{text:p,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return o!=null&&e.push(W(o)),l&&u&&e.push(`${l}/${u}`),d!=null&&e.push(`${d}B${f?` (!)`:``}`),{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,elapsed:o,errorType:s,errorMessage:c},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,m),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(k,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),h.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,h.className),children:h.text})]})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function F_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(W((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(W((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function I_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var L_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.selected_option,s=R_(i);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,selectedOption:o},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 border-dashed bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`waiting`&&`shadow-[0_0_12px_var(--waiting-muted)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,s),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`waiting`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(Ce,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),i===`waiting`&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--waiting)] truncate leading-tight`,children:`Awaiting input...`}),i===`completed`&&o&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] truncate leading-tight`,children:o})]})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function R_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`||e===`waiting`?r(`node-activate`):(n===`running`||n===`waiting`)&&e===`completed`&&r(`node-complete`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var z_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=n.type===`for_each_group`?be:le,i=n.progress,a=Hh(n)?.status||n.status||`pending`,o=X[a]||X.pending,s=B_(a),c=B(e=>e.toggleContextExpanded),l=n.expanded===!0,u=n.canExpand===!0,d=n.groupExpansionKey,f=e=>{e.stopPropagation(),d!=null&&c(d)},p=i?`${i.completed+i.failed}/${i.total}${i.failed>0?` (${i.failed} failed)`:``}`:null,m=i&&i.total>0?(i.completed+i.failed)/i.total*100:0,h=i!=null&&i.failed>0;return l?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(`div`,{className:U(`w-full h-full rounded-xl border-2 border-dashed bg-[var(--surface)]/40 transition-all duration-300 animate-[subflow-expand-in_200ms_ease-out]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,a===`running`&&`shadow-[0_0_16px_var(--running-glow)]`,s),style:{borderColor:o,minHeight:`100%`},children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-2`,children:[(0,H.jsx)(`button`,{onClick:f,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Collapse for-each iterations`,children:(0,H.jsx)(M,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(r,{className:`w-3.5 h-3.5 flex-shrink-0`,style:{color:o}}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)] truncate`,children:n.label}),p&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] font-mono flex-shrink-0`,children:p})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsxs)(`div`,{className:U(`flex flex-col gap-1 px-4 py-3 rounded-xl border-2 border-dashed bg-[var(--surface)]/80 min-w-[180px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,a===`running`&&`shadow-[0_0_16px_var(--running-glow)]`,s),style:{borderColor:o,minHeight:`100%`},children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[u&&(0,H.jsx)(`button`,{onClick:f,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0 -ml-1`,title:`Expand for-each iterations inline`,children:(0,H.jsx)(N,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(r,{className:`w-3.5 h-3.5`,style:{color:o}}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text-secondary)]`,children:n.label})]}),p&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] font-mono`,children:p}),i&&i.total>0&&a===`running`&&(0,H.jsx)(`div`,{className:`w-full h-1 rounded-full bg-[var(--border)] overflow-hidden mt-0.5`,children:(0,H.jsx)(`div`,{className:`h-full rounded-full transition-all duration-500 ease-out`,style:{width:`${m}%`,backgroundColor:h?`var(--failed)`:`var(--completed)`}})})]}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function B_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var V_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.error_message,c=B(e=>e.toggleContextExpanded),l=n.expanded===!0,u=n.canExpand===!0,d=n.childContextKey,f=n.childName,p=e=>{e.stopPropagation(),d!=null&&c(d)};if(l)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(`div`,{className:U(`w-full h-full rounded-xl border-2 border-dashed bg-[var(--surface)]/40 transition-all duration-300 animate-[subflow-expand-in_200ms_ease-out]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_16px_var(--running-glow)]`),style:{borderColor:a,minHeight:`100%`},children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-2`,children:[(0,H.jsx)(`button`,{onClick:p,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Collapse subworkflow`,children:(0,H.jsx)(M,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(de,{className:`w-3.5 h-3.5 flex-shrink-0`,style:{color:a}}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)] truncate`,children:n.label}),f&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] truncate`,children:[`· `,f]})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]});let m=(()=>{if(i===`failed`&&s)return{text:s.length>35?s.slice(0,32)+`...`:s,className:`text-red-400`};if(i===`running`)return{text:f||`Running subworkflow…`,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return f&&e.push(f),o!=null&&e.push(`${o.toFixed(1)}s`),{text:e.join(` · `)||`Done`,className:`text-[var(--text-muted)]`}}return{text:f||null,className:`text-[var(--text-muted)]`}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,elapsed:o,errorType:void 0,errorMessage:s,iteration:void 0},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[240px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`),style:{borderColor:a,borderStyle:`dashed`},children:[u?(0,H.jsx)(`button`,{onClick:p,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Expand subworkflow inline (double-click to focus)`,children:(0,H.jsx)(N,{className:`w-3.5 h-3.5`})}):(0,H.jsx)(`div`,{className:`flex items-center justify-center w-5 h-5 flex-shrink-0 text-[var(--text-muted)] opacity-25`,title:`Subworkflow structure not yet known (will be expandable once it starts)`,"aria-hidden":`true`,children:(0,H.jsx)(N,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(de,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label})}),m.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,m.className),children:m.text})]})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})}),H_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.duration_seconds??r?.requested_seconds,s=r?.waited_seconds,c=r?.elapsed,l=r?.interrupted,u=r?.error_type,d=r?.error_message,f=U_(r?.startedAt,i),p=W_(i),m=(()=>{if(i===`failed`&&d)return{text:d.length>40?d.slice(0,37)+`...`:d,className:`text-red-400`};if(i===`running`)return{text:`${f}${typeof o==`number`?` / ${W(o)}`:``}`,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return s==null?c!=null&&e.push(W(c)):e.push(W(s)),l&&e.push(`interrupted`),{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return i===`pending`&&typeof o==`number`?{text:W(o),className:`text-[var(--text-muted)]`}:{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,elapsed:s??c,errorType:u,errorMessage:d},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,p),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(re,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),m.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,m.className),children:m.text})]})]})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function U_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(W((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(W((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function W_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var G_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Hh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.termination_reason,s=r?.termination_status,c=r?.error_message,l=r?.error_type,u=o||c,d=i===`failed`?`text-red-400`:i===`completed`?`text-green-400`:`text-[var(--text-muted)]`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(w_,{data:{status:i,reason:o,terminationStatus:s,errorType:l,errorMessage:c},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[260px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`completed`&&`shadow-[0_0_12px_var(--completed-muted)]`,i===`failed`&&`shadow-[0_0_12px_var(--failed-muted)]`),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,style:{backgroundColor:`${a}20`},children:(0,H.jsx)(_e,{className:`w-3.5 h-3.5`,style:{color:a},fill:i===`completed`||i===`failed`?a:`transparent`,fillOpacity:.2})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),(0,H.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-[var(--text-muted)] truncate leading-tight`,children:[`terminate`,s?` · ${s}`:``]}),u&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight mt-0.5`,d),title:u,children:u.length>50?u.slice(0,47)+`...`:u})]})]})})]})}),K_=(0,v.memo)(function({data:e,selected:t}){let n=e.status||`pending`,r=n===`completed`,i=n===`failed`,a=!r&&!i,o=r?X.completed:i?X.failed:X.pending;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 transition-all duration-300`,r?`bg-[var(--completed)] shadow-[0_0_16px_var(--completed-muted)]`:i?`bg-[var(--failed)] shadow-[0_0_16px_var(--failed-muted)]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`),style:{borderColor:o},children:r?(0,H.jsx)(j,{className:`w-5 h-5 text-white`,strokeWidth:3}):i?(0,H.jsx)(Ee,{className:`w-3.5 h-3.5 text-white`,fill:`white`}):(0,H.jsx)(j,{className:`w-5 h-5`,strokeWidth:2.5,style:{color:a?X.pending:o}})})]})}),q_=(0,v.memo)(function({data:e,selected:t}){let n=e.status||`pending`,r=X[n]||X.pending,i=n===`running`||n===`completed`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 transition-all duration-300`,i?`bg-[var(--completed)]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i&&`shadow-[0_0_12px_var(--completed-muted)]`),style:{borderColor:r},children:(0,H.jsx)(ye,{className:`w-4 h-4 ml-0.5`,style:{color:i?`white`:r}})}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})}),J_=`#a78bfa`,Y_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=n.status||`pending`,i=r===`running`||r===`completed`,a=i?J_:X[r]||J_,o=n.parentAgent,s=B(e=>e.navigateUp);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-1`,children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 border-dashed transition-all duration-300 cursor-pointer`,i?`bg-[#a78bfa]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i&&`shadow-[0_0_12px_rgba(167,139,250,0.4)]`),style:{borderColor:a},onDoubleClick:e=>{e.stopPropagation(),s()},children:(0,H.jsx)(E,{className:`w-4 h-4`,style:{color:i?`white`:a}})}),o&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] whitespace-nowrap`,children:[`from `,(0,H.jsx)(`span`,{className:`font-medium text-[var(--text)]`,children:o})]})]}),(0,H.jsx)(vp,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})}),X_=`#a78bfa`,Z_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=n.status||`pending`,i=r===`completed`,a=r===`failed`,o=i?X_:a?X.failed:X_,s=n.parentAgent,c=B(e=>e.navigateUp);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vp,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-1`,children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 border-dashed transition-all duration-300 cursor-pointer`,i?`bg-[#a78bfa] shadow-[0_0_12px_rgba(167,139,250,0.4)]`:a?`bg-[var(--failed)] shadow-[0_0_16px_var(--failed-muted)]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`),style:{borderColor:o},onDoubleClick:e=>{e.stopPropagation(),c()},children:(0,H.jsx)(D,{className:`w-4 h-4`,style:{color:i||a?`white`:o}})}),s&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] whitespace-nowrap`,children:[`return to `,(0,H.jsx)(`span`,{className:`font-medium text-[var(--text)]`,children:s})]})]})]})}),Q_=(0,v.memo)(function({id:e,sourceX:t,sourceY:n,targetX:r,targetY:i,sourcePosition:a,targetPosition:o,data:s}){let[c,l,u]=su({sourceX:t,sourceY:n,targetX:r,targetY:i,sourcePosition:a,targetPosition:o}),d=s?.when,f=s?.highlightState,p=!!d,m=f===`taken`,h=f===`highlighted`,g=f===`failed`,_=`var(--edge-color)`,v=2,y;return g?(_=`var(--failed)`,v=3):m?(_=`var(--edge-taken)`,v=3):h&&(_=`var(--edge-active)`,v=3),p&&!m&&!h&&!g&&(y=`6 3`),(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Qp,{id:e,path:c,style:{stroke:_,strokeWidth:v,strokeDasharray:y,transition:`stroke 0.3s ease, stroke-width 0.3s ease`},markerEnd:`url(#arrow-${g?`failed`:m?`taken`:h?`active`:`default`})`}),p&&(0,H.jsx)(Qm,{children:(0,H.jsx)(`div`,{className:`nodrag nopan`,style:{position:`absolute`,transform:`translate(-50%, -50%) translate(${l}px,${u}px)`,pointerEvents:`all`},children:(0,H.jsx)(`span`,{className:`inline-block px-1.5 py-0.5 rounded-full text-[9px] font-mono leading-tight max-w-[140px] truncate`,style:{backgroundColor:g?`var(--failed)`:m?`var(--edge-taken)`:`var(--surface)`,color:g||m?`var(--bg)`:`var(--text-muted)`,border:`1px solid ${g?`var(--failed)`:m?`var(--edge-taken)`:`var(--border)`}`},title:d,children:d})})}),m&&(0,H.jsx)(`circle`,{r:`3`,fill:`var(--edge-taken)`,children:(0,H.jsx)(`animateMotion`,{dur:`1s`,repeatCount:`indefinite`,path:c})}),g&&(0,H.jsx)(`circle`,{r:`3`,fill:`var(--failed)`,opacity:`0.8`,children:(0,H.jsx)(`animateMotion`,{dur:`1.5s`,repeatCount:`indefinite`,path:c})})]})});function $_(){let e=B(e=>e.workflowStatus),t=B(e=>e.workflowFailure),n=B(e=>e.workflowFailedAgent),r=B(e=>e.workflowTermination),i=B(e=>e.selectNode);if(e!==`failed`||!t)return null;if(t.stopped_by_user){let e=t.checkpoint_path?.split(`/`).pop();return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-slate-900/90 border border-slate-500/40 shadow-lg shadow-slate-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(Ee,{className:`w-4 h-4 text-slate-300 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-slate-200`,children:`Workflow Stopped`}),t.checkpoint_path?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`span`,{className:`text-[11px] text-slate-300/80 truncate`,title:t.checkpoint_path,children:[`Checkpoint saved: `,e]}),(0,H.jsx)(`span`,{className:`text-[10px] text-slate-400/70 truncate`,children:`Resume from the CLI with: conductor resume`})]}):t.checkpoint_unavailable_reason?(0,H.jsxs)(`span`,{className:`text-[11px] text-amber-300/80 truncate`,title:t.checkpoint_unavailable_reason,children:[`No checkpoint could be saved — `,t.checkpoint_unavailable_reason]}):(0,H.jsx)(`span`,{className:`text-[11px] text-slate-400/70 truncate`,children:`Saving checkpoint…`})]}),n&&(0,H.jsxs)(`button`,{onClick:()=>i(Ih([],n)),className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium text-slate-200 bg-slate-500/20 hover:bg-slate-500/30 transition-colors flex-shrink-0 ml-1`,children:[(0,H.jsx)(L,{className:`w-3 h-3`}),`View`]})]})})}let a=r?.is_explicit&&r.status===`failed`,o=a?r.termination_reason||t.message||`Workflow terminated`:t.message||t.error_type||`Unknown error`,s=a?`Workflow Terminated`:`Workflow Failed`,c=t.error_type===`TimeoutError`;return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-red-950/90 border border-red-500/40 shadow-lg shadow-red-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(Oe,{className:`w-4 h-4 text-red-400 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-red-300`,children:s}),(0,H.jsx)(`span`,{className:`text-[11px] text-red-400/80 truncate`,children:o}),a&&r?.terminated_by&&(0,H.jsxs)(`span`,{className:`text-[10px] text-red-400/60 truncate`,children:[`Terminated by: `,r.terminated_by]}),c&&t.current_agent&&(0,H.jsxs)(`span`,{className:`text-[10px] text-red-400/60 truncate`,children:[`Timed out on agent: `,t.current_agent]}),t.checkpoint_path&&(0,H.jsxs)(`span`,{className:`text-[10px] text-red-400/50 truncate`,title:t.checkpoint_path,children:[`Checkpoint: `,t.checkpoint_path.split(`/`).pop()]})]}),n&&(0,H.jsxs)(`button`,{onClick:()=>i(Ih([],n)),className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium text-red-300 bg-red-500/20 hover:bg-red-500/30 transition-colors flex-shrink-0 ml-1`,children:[(0,H.jsx)(L,{className:`w-3 h-3`}),`View`]})]})})}function ev(){let[e,t]=(0,v.useState)(!1),n=B(e=>e.workflowStatus),r=B(e=>e.workflowTermination),i=B(e=>e.totalCost),a=B(e=>e.totalTokens),o=B(e=>e.agentsCompleted),s=B(e=>e.agentsTotal),c=xt();if(n!==`completed`||e)return null;let l=r?.is_explicit&&r.status===`success`;return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-3 px-4 py-2 rounded-lg`,`bg-green-950/90 border border-green-500/40 shadow-lg shadow-green-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(F,{className:`w-4 h-4 text-green-400 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-green-300`,children:l?`Workflow Terminated`:`Completed`}),l&&r?.termination_reason&&(0,H.jsx)(`span`,{className:`text-[11px] text-green-400/80 truncate`,children:r.termination_reason}),l&&r?.terminated_by&&(0,H.jsxs)(`span`,{className:`text-[10px] text-green-400/60 truncate`,children:[`Terminated by: `,r.terminated_by]})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-[11px] text-green-400/80 font-mono flex-shrink-0 ml-auto`,children:[(0,H.jsx)(`span`,{children:c}),s>0&&(0,H.jsxs)(`span`,{children:[o,`/`,s,` agents`]}),a>0&&(0,H.jsxs)(`span`,{children:[_t(a),` tok`]}),i>0&&(0,H.jsx)(`span`,{children:vt(i)})]}),(0,H.jsx)(`button`,{onClick:()=>t(!0),className:`p-0.5 rounded text-green-500/60 hover:text-green-300 transition-colors flex-shrink-0 ml-1`,children:(0,H.jsx)(Me,{className:`w-3.5 h-3.5`})})]})})}var tv=6e4;function nv({wsStatus:e,wsDisconnectedSince:t,workflowStatus:n,replayMode:r,now:i=Date.now(),thresholdMs:a=tv}){return r||n!==`running`||e===`connected`||t==null?!1:i-t>=a}function rv(){let e=B(e=>e.wsStatus),t=B(e=>e.wsDisconnectedSince),n=B(e=>e.workflowStatus),r=B(e=>e.replayMode),[i,a]=(0,v.useState)(()=>Date.now());return(0,v.useEffect)(()=>{if(t==null||e===`connected`)return;let n=()=>a(Date.now());n();let r=setInterval(n,1e3);return()=>clearInterval(r)},[t,e]),{stuck:nv({wsStatus:e,wsDisconnectedSince:t,workflowStatus:n,replayMode:r,now:i}),elapsedMs:t==null?0:Math.max(0,i-t)}}function iv(){let{stuck:e,elapsedMs:t}=rv(),n=B(e=>e.bgStderrLog),r=B(e=>e.bgStdoutLog),i=B(e=>e.systemLogFile),a=B(e=>e.wsAuthFailed);if(!e)return null;let o=n?`Check the captured logs: ${n}${r?` (and ${r})`:``}`:i?`Check the event log: ${i}`:"Check the terminal where `conductor run` was launched, or re-run with --log-file to capture one.",s=a?`The dashboard may have been rejected by its own authentication check (an invalid or expired token, or a Host/Origin mismatch) -- try reloading the page. If that doesn’t help, the Conductor process may have crashed.`:`Reconnecting for `+W(t/1e3)+` with no success. The Conductor process may have crashed.`;return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-amber-950/90 border border-amber-500/40 shadow-lg shadow-amber-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(Oe,{className:`w-4 h-4 text-amber-400 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-amber-300`,children:`Connection lost — workflow may have stopped responding`}),(0,H.jsx)(`span`,{className:`text-[11px] text-amber-400/80 truncate`,children:s}),(0,H.jsx)(`span`,{className:`text-[10px] text-amber-400/60 truncate`,title:n??i??void 0,children:o})]})]})})}var av=5e3;function ov(){let e=B(e=>e.wsSendFailed),t=B(e=>e.setWsSendFailed),[n,r]=(0,v.useState)(!1);return(0,v.useEffect)(()=>{if(!e)return;r(!0);let n=setTimeout(()=>{r(!1),t(!1)},av);return()=>clearTimeout(n)},[e,t]),n?(0,H.jsx)(`div`,{className:`absolute top-14 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-red-950/90 border border-red-500/40 shadow-lg shadow-red-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(Oe,{className:`w-4 h-4 text-red-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-red-300`,children:`Not connected — your response was not sent. Reconnecting…`})]})}):null}var sv={agentNode:T_,scriptNode:O_,setNode:j_,mcpNode:P_,gateNode:L_,groupNode:z_,workflowNode:V_,waitNode:H_,terminateNode:G_,endNode:K_,startNode:q_,ingressNode:Y_,egressNode:Z_},cv={animatedEdge:Q_},lv={type:`animatedEdge`},uv=300,dv=50;function fv(e){Jh(uv),e({padding:.2,duration:uv})}function pv(){return(0,H.jsx)(`svg`,{style:{position:`absolute`,width:0,height:0},children:(0,H.jsxs)(`defs`,{children:[(0,H.jsx)(`marker`,{id:`arrow-default`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--edge-color)`})}),(0,H.jsx)(`marker`,{id:`arrow-active`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--edge-active)`})}),(0,H.jsx)(`marker`,{id:`arrow-taken`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--edge-taken)`})}),(0,H.jsx)(`marker`,{id:`arrow-failed`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--failed)`})})]})})}function mv(e,t){if(t.length===0)return null;let n=e[t[0]];for(let e=1;ee.viewContextPath),n=B(e=>e.selectNode),r=B(e=>e.selectedNode),i=B(e=>e.workflowStatus),a=B(e=>e.wsStatus),o=B(e=>e.workflowFailedAgent),s=B(e=>e.navigateIntoSubworkflow),{agents:c,routes:l,parallelGroups:u,forEachGroups:d,nodes:f,groupProgress:p,entryPoint:m,subworkflowContexts:h,parentAgent:g,basePath:_}=e,y=B(e=>e.expandedContexts),b=B(e=>e.nodes),x=B(e=>e.groupProgress),S=B(e=>e.subworkflowContexts),C=B(e=>e.highlightedEdges),[w,T,E]=$m([]),[D,O,k]=eh([]),A=(0,v.useRef)(``),{getViewport:j,setViewport:M}=Yf(),N=(0,v.useRef)(null),ee=(0,v.useRef)([]),te=(0,v.useRef)({hint:null,stickyRebuilds:0}),P=(0,v.useRef)(new Set),F=(0,v.useRef)(null),ne=JSON.stringify(t),re=(0,v.useMemo)(()=>{let e=[`${ne}#${c.map(e=>e.name).join(`,`)}`];for(let t of[...y].sort()){if(zh(t)){let{contextPath:n,name:r}=Lh(t),i=n.length===0?null:mv(S,n),a=(n.length===0?S:i?.children??[]).filter(e=>{let t=Bh(e.slotKey);return t!=null&&t.group===r}).map(e=>`${e.slotKey}:${e.entryPoint??``}:${e.agents.map(e=>e.name).join(`,`)}`);e.push(`${t}=>${a.join(`|`)}`);continue}let n=mv(S,t.split(`.`).filter(Boolean).map(Number));e.push(`${t}:${n?.entryPoint??``}:${n?.agents.map(e=>e.name).join(`,`)??``}`)}return e.join(`||`)},[ne,c,y,S]);(0,v.useEffect)(()=>{if(c.length===0){A.current!==re&&(A.current=re,ee.current=[],P.current=new Set(y),F.current=ne,te.current={hint:null,stickyRebuilds:0},T([]),O([]));return}if(A.current===re)return;A.current=re;let e=F.current!==ne;F.current=ne;let t=P.current;P.current=new Set(y),te.current=C_({previousKeys:t,currentKeys:y,currentHint:te.current.hint,stickyRebuilds:te.current.stickyRebuilds,contextSwitched:e});let{nodes:n,edges:r}=t_({agents:c,routes:l,parallelGroups:u,forEachGroups:d,nodes:f,groupProgress:p,entryPoint:m,parentAgent:g,children:h},_,y),i=ee.current;if(ee.current=n,T(n),O(r),e||i.length===0||Yh())return;let a=N.current?.getBoundingClientRect(),o=S_({prevNodes:i,nextNodes:n,anchorKeyHint:te.current.hint,viewport:j(),paneSize:{width:a?.width??0,height:a?.height??0}});o&&M(o)},[re,c,l,u,d,f,p,m,g,h,_,y,ne,j,M,T,O]),(0,v.useEffect)(()=>{T(e=>e.map(e=>{let t=e.data,n=t.iterationContextPath;if(n&&n.length>0){let r=mv(S,n)?.status;return!r||r===t.status?e:{...e,data:{...t,status:r}}}let r=t.contextPath??[],i=r.length===0?null:mv(S,r),a=r.length===0?b:i?.nodes,o=r.length===0?x:i?.groupProgress,s=t.name??e.id,c=a?a[s]:void 0;if(!c)return e;let l=t,u=!1,d=c.status||`pending`;if(d!==t.status&&(l={...l,status:d},u=!0),t.groupName&&o&&o[t.groupName]){let e=o[t.groupName],n=l.progress;e&&(!n||n.completed!==e.completed||n.failed!==e.failed)&&(l={...l,progress:e},u=!0)}return u?{...e,data:l}:e}))},[b,x,S,T]),(0,v.useEffect)(()=>{O(e=>e.map(e=>{let{contextPath:t,name:n}=Lh(e.source),r=Lh(e.target).name,i=t.length===0?null:mv(S,t),a=(t.length===0?C:i?.highlightedEdges??[]).find(e=>e.from===n&&e.to===r)?.state;return e.data?.highlightState===a?e:{...e,data:{...e.data,highlightState:a}}}))},[C,S,O]);let ie=(0,v.useCallback)((e,t)=>{t.type===`groupNode`&&t.data.type!==`for_each_group`||n(t.id)},[n]),ae=(0,v.useCallback)((e,n)=>{let r=n.data;if(r.type!==`workflow`||(r.contextPath??[]).join(`.`)!==t.join(`.`))return;let i=r.name;i&&h.some(e=>e.slotKey===i||e.parentAgent===i)&&s(i)},[h,s,t]),I=(0,v.useCallback)(()=>{n(null)},[n]),L=(0,v.useCallback)(e=>X[e.data?.status||`pending`]??X.pending??`#6b7280`,[]);(0,v.useEffect)(()=>{T(e=>e.map(e=>({...e,selected:e.id===r})))},[r,T]),(0,v.useEffect)(()=>{i===`failed`&&o&&n(Ih([],o))},[i,o,n]);let oe=i===`pending`&&c.length===0,se=(()=>{switch(a){case`connecting`:return`Connecting to workflow…`;case`reconnecting`:return`Reconnecting…`;case`disconnected`:return`Connection lost. Retrying…`;default:return`Waiting for workflow…`}})();return(0,H.jsxs)(`div`,{ref:N,className:`w-full h-full relative`,children:[(0,H.jsx)(pv,{}),(0,H.jsx)($_,{}),(0,H.jsx)(ev,{}),(0,H.jsx)(iv,{}),(0,H.jsx)(ov,{}),oe&&(0,H.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center pointer-events-none`,children:[(0,H.jsxs)(`div`,{className:`relative mb-3`,children:[(0,H.jsx)(Ne,{className:`w-8 h-8 text-[var(--accent)] opacity-20`}),(0,H.jsx)(pe,{className:`w-8 h-8 text-[var(--text-muted)] animate-spin absolute inset-0 opacity-40`})]}),(0,H.jsx)(`p`,{className:`text-sm text-[var(--text-muted)] animate-pulse`,children:se})]}),(0,H.jsxs)(Xm,{nodes:w,edges:D,onNodesChange:E,onEdgesChange:k,onNodeClick:ie,onNodeDoubleClick:ae,onPaneClick:I,nodeTypes:sv,edgeTypes:cv,defaultEdgeOptions:lv,fitView:!0,fitViewOptions:{padding:.2},minZoom:.2,maxZoom:2,proOptions:{hideAttribution:!0},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,children:[(0,H.jsx)(sh,{variant:rh.Dots,gap:20,size:1,color:`var(--border-subtle)`}),(0,H.jsx)(jh,{nodeColor:L,maskColor:`var(--minimap-mask)`,style:{background:`var(--minimap-bg)`},pannable:!0,zoomable:!0}),(0,H.jsxs)(gh,{showInteractive:!1,children:[(0,H.jsx)(vv,{}),(0,H.jsx)(_v,{})]}),(0,H.jsx)(yv,{}),(0,H.jsx)(bv,{viewPathKey:ne}),(0,H.jsx)(xv,{})]})]})}function _v(){let{fitView:e}=Yf();return(0,H.jsx)(`button`,{onClick:(0,v.useCallback)(()=>{fv(e)},[e]),className:`react-flow__controls-button`,title:`Fit view (F)`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,H.jsx)(me,{className:`w-3.5 h-3.5`})})}function vv(){let{agents:e,subworkflowContexts:t,basePath:n}=Kh(),r=B(e=>e.expandedContexts),i=B(e=>e.expandContexts),a=B(e=>e.collapseContexts),o=(0,v.useMemo)(()=>n_(e,t,n),[e,t,n]),s=(0,v.useMemo)(()=>o.some(e=>r.has(e)),[o,r]),c=(0,v.useCallback)(()=>{o.length!==0&&(s?a(o):i(o))},[o,s,a,i]);if((0,v.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.key===`e`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&c()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]),o.length===0)return null;let l=s?`Collapse all subworkflows`:`Expand all subworkflows`;return(0,H.jsx)(`button`,{onClick:c,className:`react-flow__controls-button`,title:`${l} (E)`,"aria-label":l,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:s?(0,H.jsx)(te,{className:`w-3.5 h-3.5`}):(0,H.jsx)(P,{className:`w-3.5 h-3.5`})})}function yv(){let{fitView:e}=Yf();return(0,v.useEffect)(()=>{let t=t=>{let n=t.target?.tagName;n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.key===`f`&&!t.ctrlKey&&!t.metaKey&&!t.altKey&&fv(e)};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]),null}function bv({viewPathKey:e}){let{fitView:t}=Yf(),n=(0,v.useRef)(e);return(0,v.useEffect)(()=>{n.current!==e&&(n.current=e,Jh(350),setTimeout(()=>fv(t),dv))},[e,t]),null}function xv(){let e=v_();return e?(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2 rounded-lg bg-amber-950/90 border border-amber-500/40 shadow-lg shadow-amber-500/10 backdrop-blur-sm max-w-[560px]`,children:[(0,H.jsx)(`span`,{className:`text-xs text-amber-300`,children:`⚠`}),(0,H.jsx)(`span`,{className:`text-[11px] text-amber-400/80`,children:e.message}),(0,H.jsx)(`a`,{href:window.location.pathname,className:`px-2 py-0.5 rounded text-[10px] font-medium text-amber-300 bg-amber-500/20 hover:bg-amber-500/30 transition-colors flex-shrink-0 ml-1`,children:`Root`})]})}):null}function Sv({items:e}){let t=e.filter(e=>e.value!=null&&e.value!==``);return t.length===0?null:(0,H.jsx)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 text-xs`,children:t.map(({label:e,value:t})=>(0,H.jsxs)(`div`,{className:`contents`,children:[(0,H.jsx)(`dt`,{className:`text-[var(--text-muted)] whitespace-nowrap`,children:e}),(0,H.jsx)(`dd`,{className:`text-[var(--text)] break-words`,children:typeof t==`object`?JSON.stringify(t):String(t)})]},e))})}function Cv(e){let t=[];return e.elapsed!=null&&t.push({label:`Elapsed`,value:W(e.elapsed)}),e.model&&t.push({label:`Model`,value:e.model}),e.reasoning_effort&&t.push({label:`Reasoning`,value:e.reasoning_effort}),e.tokens!=null&&t.push({label:`Tokens`,value:_t(e.tokens)}),e.input_tokens!=null&&e.output_tokens!=null&&t.push({label:`In / Out`,value:`${_t(e.input_tokens)} / ${_t(e.output_tokens)}`}),e.cost_usd!=null&&t.push({label:`Cost`,value:vt(e.cost_usd)}),e.context_window_used!=null&&e.context_window_max!=null&&t.push({label:`Context`,value:bt(e.context_window_used,e.context_window_max)}),e.iteration!=null&&t.push({label:`Iteration`,value:e.iteration}),e.error_type&&t.push({label:`Error`,value:e.error_type}),e.error_message&&t.push({label:`Message`,value:e.error_message}),t}function wv({output:e,title:t=`Output`,defaultExpanded:n=!0,maxHeight:r=`300px`}){let[i,a]=(0,v.useState)(n),[o,s]=(0,v.useState)(!1),c=yt(e);if(!c)return null;let l=typeof e==`object`&&!!e;return(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsxs)(`button`,{onClick:()=>a(!i),className:`flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--text-muted)] hover:text-[var(--text)] transition-colors font-semibold`,children:[i?(0,H.jsx)(M,{className:`w-3 h-3`}):(0,H.jsx)(N,{className:`w-3 h-3`}),t]}),i&&(0,H.jsx)(`button`,{onClick:async()=>{await navigator.clipboard.writeText(c),s(!0),setTimeout(()=>s(!1),2e3)},className:`flex items-center gap-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,title:`Copy to clipboard`,children:o?(0,H.jsx)(j,{className:`w-3 h-3 text-[var(--completed)]`}):(0,H.jsx)(ae,{className:`w-3 h-3`})})]}),i&&(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md p-3 font-mono text-[11px] leading-relaxed text-[var(--text)] overflow-auto whitespace-pre-wrap break-words`,style:{maxHeight:r},children:l?(0,H.jsx)(Tv,{text:c}):c})]})}function Tv({text:e}){let t=e.split(/("(?:[^"\\]|\\.)*")/g);return(0,H.jsx)(H.Fragment,{children:t.map((e,n)=>{if(n%2==1){let r=t.slice(n+1).join(``);return(0,H.jsx)(`span`,{className:/^\s*:/.test(r)?`text-blue-400`:`text-green-400`,children:e},n)}return(0,H.jsx)(`span`,{dangerouslySetInnerHTML:{__html:e.replace(/\b(true|false|null)\b|(-?\d+\.?\d*(?:e[+-]?\d+)?)/gi,(e,t,n)=>t?`${e}`:n?`${e}`:e)}},n)})})}function Ev({activity:e,defaultExpanded:t=!0}){let[n,r]=(0,v.useState)(t),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{i.current&&n&&(i.current.scrollTop=i.current.scrollHeight)},[e.length,n]),e.length===0?null:(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsxs)(`button`,{onClick:()=>r(!n),className:`flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--text-muted)] hover:text-[var(--text)] transition-colors font-semibold`,children:[n?(0,H.jsx)(M,{className:`w-3 h-3`}):(0,H.jsx)(N,{className:`w-3 h-3`}),`Activity (`,e.length,`)`]}),n&&(0,H.jsx)(`div`,{ref:i,className:`max-h-[400px] overflow-y-auto space-y-0.5`,children:e.map((e,t)=>(0,H.jsx)(Dv,{entry:e},t))})]})}function Dv({entry:e}){return(0,H.jsxs)(`div`,{className:U(`py-1.5 px-2 rounded text-[11px] leading-relaxed border-b border-[var(--border-subtle)] last:border-b-0`),children:[(0,H.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,H.jsx)(`span`,{className:`w-4 text-center flex-shrink-0`,children:e.icon}),(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] uppercase text-[9px] font-semibold tracking-wider w-12 flex-shrink-0 pt-px`,children:e.label}),(0,H.jsx)(`span`,{className:U(`break-words`,{reasoning:`text-indigo-400/70`,"tool-start":`text-blue-400`,"tool-complete":`text-green-400`,turn:`text-amber-400`,message:`text-[var(--text)]`,"parse-recovery":`text-yellow-400`,"compaction-error":`text-yellow-400`}[e.type]||`text-[var(--text)]`),children:typeof e.text==`object`?JSON.stringify(e.text):e.text})]}),e.detail&&(0,H.jsx)(`div`,{className:`mt-1 ml-[4.25rem] px-2 py-1 bg-[var(--bg)] rounded text-[10px] font-mono text-[var(--text-muted)] whitespace-pre-wrap break-words max-h-24 overflow-y-auto`,children:typeof e.detail==`object`?JSON.stringify(e.detail,null,2):e.detail})]})}var Ov={running:{label:`Validating…`,color:`#3b82f6`},passed:{label:`Passed`,color:`#22c55e`},failed:{label:`Failed`,color:`#f59e0b`},error:{label:`Validator error (treated as pass)`,color:`#f59e0b`}};function kv({node:e}){let t=e.validator_state;if(!t)return null;let n=Ov[t]??{label:`Validating…`,color:`#3b82f6`},r=e.validator_issues??[],i=(t===`failed`||t===`error`)&&r.length>0;return(0,H.jsxs)(`div`,{className:`border border-[var(--border)] rounded-lg overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-[var(--bg)]`,children:[(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)]`,children:`Validation`}),(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ml-auto`,style:{backgroundColor:`${n.color}20`,color:n.color},children:n.label})]}),(0,H.jsxs)(`div`,{className:`px-3 py-3 space-y-2 border-t border-[var(--border)]`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-[var(--text-muted)]`,children:[e.validator_model&&(0,H.jsxs)(`span`,{children:[`model: `,e.validator_model]}),e.validator_cost_usd!=null&&(0,H.jsxs)(`span`,{children:[`cost: $`,e.validator_cost_usd.toFixed(4)]}),e.validator_attempts!=null&&e.validator_attempts>1&&(0,H.jsxs)(`span`,{children:[`runs: `,e.validator_attempts]})]}),i&&(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]`,children:`Issues`}),(0,H.jsx)(`ul`,{className:`space-y-1`,children:r.map((e,t)=>(0,H.jsxs)(`li`,{className:`text-xs text-[var(--text)] flex gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] flex-shrink-0`,children:`•`}),(0,H.jsx)(`span`,{children:e})]},t))})]}),e.validator_will_retry&&(0,H.jsx)(`div`,{className:`text-[10px] text-[var(--text-muted)] italic`,children:`Primary agent re-run once with this feedback appended.`})]})]})}function Av({node:e}){let t=e.status,n=X[t]||X.pending,r=e.iterationHistory&&e.iterationHistory.length>0;return(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Agent`})]}),(0,H.jsx)(kv,{node:e}),r?(0,H.jsx)(jv,{label:`Iteration ${e.iteration??`?`} (current)`,defaultExpanded:!0,status:t,snapshot:{iteration:e.iteration??0,prompt:e.prompt,output:e.output,elapsed:e.elapsed,model:e.model,reasoning_effort:e.reasoning_effort,tokens:e.tokens,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cost_usd:e.cost_usd,activity:e.activity,error_type:e.error_type,error_message:e.error_message}}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Sv,{items:Cv(e)}),e.prompt&&(0,H.jsx)(wv,{output:e.prompt,title:`Input / Prompt`,defaultExpanded:!0}),(0,H.jsx)(Ev,{activity:e.activity,defaultExpanded:t!==`completed`}),e.output!=null&&(0,H.jsx)(wv,{output:e.output,title:`Output`})]}),r&&[...e.iterationHistory].reverse().map(e=>(0,H.jsx)(jv,{label:`Iteration ${e.iteration}`,defaultExpanded:!1,status:t,snapshot:e},e.iteration))]})}function jv({label:e,defaultExpanded:t,snapshot:n,status:r}){let[i,a]=(0,v.useState)(t);return(0,H.jsxs)(`div`,{className:`border border-[var(--border)] rounded-lg overflow-hidden`,children:[(0,H.jsxs)(`button`,{onClick:()=>a(!i),className:`flex items-center gap-2 w-full px-3 py-2 bg-[var(--bg)] hover:bg-[var(--node-bg)] transition-colors text-left`,children:[i?(0,H.jsx)(M,{className:`w-3.5 h-3.5 text-[var(--text-muted)] flex-shrink-0`}):(0,H.jsx)(N,{className:`w-3.5 h-3.5 text-[var(--text-muted)] flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)]`,children:e}),n.elapsed!=null&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] ml-auto`,children:Mv(n.elapsed)})]}),i&&(0,H.jsxs)(`div`,{className:`px-3 py-3 space-y-3 border-t border-[var(--border)]`,children:[(0,H.jsx)(Sv,{items:Cv(n)}),n.prompt&&(0,H.jsx)(wv,{output:n.prompt,title:`Input / Prompt`,defaultExpanded:!1}),(0,H.jsx)(Ev,{activity:n.activity,defaultExpanded:t&&r!==`completed`}),n.output!=null&&(0,H.jsx)(wv,{output:n.output,title:`Output`,defaultExpanded:!0}),n.error_type&&(0,H.jsxs)(`div`,{className:`text-xs text-red-400`,children:[(0,H.jsx)(`span`,{className:`font-semibold`,children:n.error_type}),n.error_message&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`— `,n.error_message]})]})]})]})}function Mv(e){return e<1?`${(e*1e3).toFixed(0)}ms`:e<60?`${e.toFixed(1)}s`:`${Math.floor(e/60)}m ${(e%60).toFixed(0)}s`}function Nv({node:e}){let t=e.status,n=X[t]||X.pending,r=[];e.elapsed!=null&&r.push({label:`Elapsed`,value:W(e.elapsed)}),e.exit_code!=null&&r.push({label:`Exit Code`,value:e.exit_code}),e.error_type&&r.push({label:`Error`,value:e.error_type}),e.error_message&&r.push({label:`Message`,value:e.error_message});let i=``;return e.stdout&&(i+=e.stdout),e.stderr&&(i+=(i?` + +--- stderr --- +`:``)+e.stderr),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Script`})]}),(0,H.jsx)(Sv,{items:r}),i&&(0,H.jsx)(wv,{output:i,title:`Output`})]})}function Pv({node:e}){let t=e.status,n=X[t]||X.pending,r=e.set_output_type,i=e.set_output_keys,a=e.set_value_repr,o=i?.length??0,s=[];return e.elapsed!=null&&s.push({label:`Elapsed`,value:W(e.elapsed)}),r&&s.push({label:`Output Type`,value:r}),o>0?s.push({label:`Bindings`,value:i.join(`, `)}):t===`completed`&&s.push({label:`Bindings`,value:`scalar`}),e.error_type&&s.push({label:`Error`,value:e.error_type}),e.error_message&&s.push({label:`Message`,value:e.error_message}),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Set`})]}),(0,H.jsx)(Sv,{items:s}),a&&(0,H.jsx)(wv,{output:a,title:`Value preview`})]})}function Fv({node:e}){let t=e.status,n=X[t]||X.pending,r=[];return e.elapsed!=null&&r.push({label:`Elapsed`,value:W(e.elapsed)}),e.mcp_server&&r.push({label:`Server`,value:e.mcp_server}),e.mcp_tool&&r.push({label:`Tool`,value:e.mcp_tool}),e.mcp_is_error!==void 0&&r.push({label:`Is Error`,value:String(e.mcp_is_error)}),e.mcp_result_bytes!=null&&r.push({label:`Result Bytes`,value:`${e.mcp_result_bytes}${e.mcp_truncated?` (truncated)`:``}`}),e.mcp_spill_path&&r.push({label:`Spill Path`,value:e.mcp_spill_path}),e.error_type&&r.push({label:`Error`,value:e.error_type}),e.error_message&&r.push({label:`Message`,value:e.error_message}),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`MCP`})]}),(0,H.jsx)(Sv,{items:r})]})}function Iv(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Lv=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Rv=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,zv={};function Bv(e,t){return((t||zv).jsx?Rv:Lv).test(e)}var Vv=/[ \t\n\f\r]/g;function Hv(e){return typeof e==`object`?e.type===`text`?Uv(e.value):!1:Uv(e)}function Uv(e){return e.replace(Vv,``)===``}var Wv=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Wv.prototype.normal={},Wv.prototype.property={},Wv.prototype.space=void 0;function Gv(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Wv(n,r,t)}function Kv(e){return e.toLowerCase()}var qv=class{constructor(e,t){this.attribute=t,this.property=e}};qv.prototype.attribute=``,qv.prototype.booleanish=!1,qv.prototype.boolean=!1,qv.prototype.commaOrSpaceSeparated=!1,qv.prototype.commaSeparated=!1,qv.prototype.defined=!1,qv.prototype.mustUseProperty=!1,qv.prototype.number=!1,qv.prototype.overloadedBoolean=!1,qv.prototype.property=``,qv.prototype.spaceSeparated=!1,qv.prototype.space=void 0;var Jv=s({boolean:()=>Z,booleanish:()=>Xv,commaOrSpaceSeparated:()=>ey,commaSeparated:()=>$v,number:()=>Q,overloadedBoolean:()=>Zv,spaceSeparated:()=>Qv}),Yv=0,Z=ty(),Xv=ty(),Zv=ty(),Q=ty(),Qv=ty(),$v=ty(),ey=ty();function ty(){return 2**++Yv}var ny=Object.keys(Jv),ry=class extends qv{constructor(e,t,n,r){let i=-1;if(super(e,t),iy(this,`space`,r),typeof n==`number`)for(;++i4&&n.slice(0,4)===`data`&&_y.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(gy,by);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!gy.test(e)){let n=e.replace(hy,yy);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=ry}return new i(r,t)}function yy(e){return`-`+e.toLowerCase()}function by(e){return e.charAt(1).toUpperCase()}var xy=Gv([oy,ly,dy,fy,py],`html`),Sy=Gv([oy,uy,dy,fy,py],`svg`);function Cy(e){return e.join(` `).trim()}var wy=o(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g,u=` +`,d=`/`,f=`*`,p=``,m=`comment`,h=`declaration`;function g(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,g=1;function v(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(u);g=~n?e.length-n:g+e.length}function y(){var e={line:l,column:g};return function(t){return t.position=new b(e),C(),t}}function b(e){this.start=e,this.end={line:l,column:g},this.source=t.source}b.prototype.content=e;function x(n){var r=Error(t.source+`:`+l+`:`+g+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=g,r.source=e,!t.silent)throw r}function S(t){var n=t.exec(e);if(n){var r=n[0];return v(r),e=e.slice(r.length),n}}function C(){S(i)}function w(e){var t;for(e||=[];t=T();)t!==!1&&e.push(t);return e}function T(){var t=y();if(!(d!=e.charAt(0)||f!=e.charAt(1))){for(var n=2;p!=e.charAt(n)&&(f!=e.charAt(n)||d!=e.charAt(n+1));)++n;if(n+=2,p===e.charAt(n-1))return x(`End of comment missing`);var r=e.slice(2,n-2);return g+=2,v(r),e=e.slice(n),g+=2,t({type:m,comment:r})}}function E(){var e=y(),t=S(a);if(t){if(T(),!S(o))return x(`property missing ':'`);var r=S(s),i=e({type:h,property:_(t[0].replace(n,p)),value:r?_(r[0].replace(n,p)):p});return S(c),i}}function D(){var e=[];w(e);for(var t;t=E();)t!==!1&&(e.push(t),w(e));return e}return C(),D()}function _(e){return e?e.replace(l,p):p}t.exports=g})),Ty=o((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var n=t(wy());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),Ey=o((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),Dy=o(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(Ty()),r=Ey();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),Oy=Ay(`end`),ky=Ay(`start`);function Ay(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function jy(e){let t=ky(e),n=Oy(e);if(t&&n)return{start:t,end:n}}function My(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?Py(e.position):`start`in e||`end`in e?Py(e):`line`in e||`column`in e?Ny(e):``}function Ny(e){return Fy(e&&e.line)+`:`+Fy(e&&e.column)}function Py(e){return Ny(e&&e.start)+`-`+Ny(e&&e.end)}function Fy(e){return e&&typeof e==`number`?e:1}var Iy=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=My(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};Iy.prototype.file=``,Iy.prototype.name=``,Iy.prototype.reason=``,Iy.prototype.message=``,Iy.prototype.stack=``,Iy.prototype.column=void 0,Iy.prototype.line=void 0,Iy.prototype.ancestors=void 0,Iy.prototype.cause=void 0,Iy.prototype.fatal=void 0,Iy.prototype.place=void 0,Iy.prototype.ruleId=void 0,Iy.prototype.source=void 0;var Ly=l(Dy(),1),Ry={}.hasOwnProperty,zy=new Map,By=/[A-Z]/g,Vy=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),Hy=new Set([`td`,`th`]);function Uy(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=eb(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=$y(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?Sy:xy,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=Wy(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function Wy(e,t,n){if(t.type===`element`)return Gy(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return Ky(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return Jy(e,t,n);if(t.type===`mdxjsEsm`)return qy(e,t);if(t.type===`root`)return Yy(e,t,n);if(t.type===`text`)return Xy(e,t)}function Gy(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=Sy,e.schema=i),e.ancestors.push(t);let a=ob(e,t.tagName,!1),o=tb(e,t),s=rb(e,t);return Vy.has(t.tagName)&&(s=s.filter(function(e){return typeof e==`string`?!Hv(e):!0})),Zy(e,o,a,t),Qy(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Ky(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}sb(e,t.position)}function qy(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);sb(e,t.position)}function Jy(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=Sy,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:ob(e,t.name,!0),o=nb(e,t),s=rb(e,t);return Zy(e,o,a,t),Qy(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Yy(e,t,n){let r={};return Qy(r,rb(e,t)),e.create(t,e.Fragment,r,n)}function Xy(e,t){return t.value}function Zy(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Qy(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function $y(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function eb(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=ky(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function tb(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&Ry.call(t.properties,i)){let a=ib(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&Hy.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function nb(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`)if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else sb(e,t.position);else{let i=r.name,a;if(r.value&&typeof r.value==`object`)if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else sb(e,t.position);else a=r.value===null?!0:r.value;n[i]=a}return n}function rb(e,t){let n=[],r=-1,i=e.passKeys?new Map:zy;for(;++ri?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a0?(yb(e,e.length,0,t),e):t}var xb={}.hasOwnProperty;function Sb(e){let t={},n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function Eb(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var Db=Rb(/[A-Za-z]/),Ob=Rb(/[\dA-Za-z]/),kb=Rb(/[#-'*+\--9=?A-Z^-~]/);function Ab(e){return e!==null&&(e<32||e===127)}var jb=Rb(/\d/),Mb=Rb(/[\dA-Fa-f]/),Nb=Rb(/[!-/:-@[-`{-~]/);function $(e){return e!==null&&e<-2}function Pb(e){return e!==null&&(e<0||e===32)}function Fb(e){return e===-2||e===-1||e===32}var Ib=Rb(/\p{P}|\p{S}/u),Lb=Rb(/\s/);function Rb(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function zb(e){let t=[],n=-1,r=0,i=0;for(;++n55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function Bb(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return Fb(r)?(e.enter(n),s(r)):t(r)}function s(r){return Fb(r)&&a++o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;er;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function Kb(e,t,n){return Bb(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function qb(e){if(e===null||Pb(e)||Lb(e))return 1;if(Ib(e))return 2}function Jb(e,t,n){let r=[],i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};Qb(d,-c),Qb(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=bb(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=bb(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=bb(l,Jb(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=bb(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=bb(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,yb(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n0&&Fb(t)?Bb(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||$(t)?e.check(dx,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||$(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),Fb(t)?Bb(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),Fb(t)?Bb(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||$(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function mx(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var hx={name:`codeIndented`,tokenize:_x},gx={partial:!0,tokenize:vx};function _x(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),Bb(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):$(t)?e.attempt(gx,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||$(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function vx(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):Bb(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):$(e)?i(e):n(e)}}var yx={name:`codeText`,previous:xx,resolve:bx,tokenize:Sx};function bx(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&wx(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),wx(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),wx(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function Mx(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||Ab(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||$(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||Pb(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):$(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||$(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!Fb(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function Px(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),Bb(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||$(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function Fx(e,t){let n;return r;function r(i){return $(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):Fb(i)?Bb(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var Ix={name:`definition`,tokenize:Rx},Lx={partial:!0,tokenize:zx};function Rx(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return Nx.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=Eb(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return Pb(t)?Fx(e,l)(t):l(t)}function l(t){return Mx(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(Lx,d,d)(t)}function d(t){return Fb(t)?Bb(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||$(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function zx(e,t,n){return r;function r(t){return Pb(t)?Fx(e,i)(t):n(t)}function i(t){return Px(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return Fb(t)?Bb(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||$(e)?t(e):n(e)}}var Bx={name:`hardBreakEscape`,tokenize:Vx};function Vx(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return $(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var Hx={name:`headingAtx`,resolve:Ux,tokenize:Wx};function Ux(e,t){let n=e.length-2,r=3,i,a;return e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},yb(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function Wx(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||Pb(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||$(n)?(e.exit(`atxHeading`),t(n)):Fb(n)?Bb(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||Pb(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var Gx=`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`.split(`.`),Kx=[`pre`,`script`,`style`,`textarea`],qx={concrete:!0,name:`htmlFlow`,resolveTo:Xx,tokenize:Zx},Jx={partial:!0,tokenize:$x},Yx={partial:!0,tokenize:Qx};function Xx(e){let t=e.length;for(;t--&&!(e[t][0]===`enter`&&e[t][1].type===`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Zx(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:P):Db(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):Db(a)?(e.consume(a),i=4,r.interrupt?t:P):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:P):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return Db(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||Pb(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&Kx.includes(l)?(i=1,r.interrupt?t(s):O(s)):Gx.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||Ob(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return Fb(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||Db(t)?(e.consume(t),b):Fb(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||Ob(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):Fb(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):Fb(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||$(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||Pb(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||Fb(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||$(t)?O(t):Fb(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),M):t===60&&i===1?(e.consume(t),N):t===62&&i===4?(e.consume(t),F):t===63&&i===3?(e.consume(t),P):t===93&&i===5?(e.consume(t),te):$(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(Jx,ne,k)(t)):t===null||$(t)?(e.exit(`htmlFlowData`),k(t)):(e.consume(t),O)}function k(t){return e.check(Yx,A,ne)(t)}function A(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),j}function j(t){return t===null||$(t)?k(t):(e.enter(`htmlFlowData`),O(t))}function M(t){return t===45?(e.consume(t),P):O(t)}function N(t){return t===47?(e.consume(t),o=``,ee):O(t)}function ee(t){if(t===62){let n=o.toLowerCase();return Kx.includes(n)?(e.consume(t),F):O(t)}return Db(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),ee):O(t)}function te(t){return t===93?(e.consume(t),P):O(t)}function P(t){return t===62?(e.consume(t),F):t===45&&i===2?(e.consume(t),P):O(t)}function F(t){return t===null||$(t)?(e.exit(`htmlFlowData`),ne(t)):(e.consume(t),F)}function ne(n){return e.exit(`htmlFlow`),t(n)}}function Qx(e,t,n){let r=this;return i;function i(t){return $(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function $x(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(tx,t,n)}}var eS={name:`htmlText`,tokenize:tS};function tS(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):Db(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):Db(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):$(t)?(o=d,N(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?M(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):$(t)?(o=h,N(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?M(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?M(t):$(t)?(o=v,N(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):$(t)?(o=y,N(t)):(e.consume(t),y)}function b(e){return e===62?M(e):y(e)}function x(t){return Db(t)?(e.consume(t),S):n(t)}function S(t){return t===45||Ob(t)?(e.consume(t),S):C(t)}function C(t){return $(t)?(o=C,N(t)):Fb(t)?(e.consume(t),C):M(t)}function w(t){return t===45||Ob(t)?(e.consume(t),w):t===47||t===62||Pb(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),M):t===58||t===95||Db(t)?(e.consume(t),E):$(t)?(o=T,N(t)):Fb(t)?(e.consume(t),T):M(t)}function E(t){return t===45||t===46||t===58||t===95||Ob(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):$(t)?(o=D,N(t)):Fb(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,k):$(t)?(o=O,N(t)):Fb(t)?(e.consume(t),O):(e.consume(t),A)}function k(t){return t===i?(e.consume(t),i=void 0,j):t===null?n(t):$(t)?(o=k,N(t)):(e.consume(t),k)}function A(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||Pb(t)?T(t):(e.consume(t),A)}function j(e){return e===47||e===62||Pb(e)?T(e):n(e)}function M(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function N(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),ee}function ee(t){return Fb(t)?Bb(e,te,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):te(t)}function te(t){return e.enter(`htmlTextData`),o(t)}}var nS={name:`labelEnd`,resolveAll:oS,resolveTo:sS,tokenize:cS},rS={tokenize:lS},iS={tokenize:uS},aS={tokenize:dS};function oS(e){let t=-1,n=[];for(;++t=3&&(a===null||$(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),Fb(t)?Bb(e,s,`whitespace`)(t):s(t))}}var bS={continuation:{tokenize:wS},exit:ES,name:`list`,tokenize:CS},xS={partial:!0,tokenize:DS},SS={partial:!0,tokenize:TS};function CS(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:jb(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(vS,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return jb(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(tx,r.interrupt?n:u,e.attempt(xS,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return Fb(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function wS(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(tx,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Bb(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!Fb(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(SS,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,Bb(e,e.attempt(bS,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function TS(e,t,n){let r=this;return Bb(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function ES(e){e.exit(this.containerState.type)}function DS(e,t,n){let r=this;return Bb(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!Fb(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var OS={name:`setextUnderline`,resolveTo:kS,tokenize:AS};function kS(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function AS(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),Fb(t)?Bb(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||$(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var jS={tokenize:MS};function MS(e){let t=this,n=e.attempt(tx,r,e.attempt(this.parser.constructs.flowInitial,i,Bb(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Dx,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var NS={resolveAll:LS()},PS=IS(`string`),FS=IS(`text`);function IS(e){return{resolveAll:LS(e===`text`?RS:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++iqS,contentInitial:()=>VS,disable:()=>JS,document:()=>BS,flow:()=>US,flowInitial:()=>HS,insideSpan:()=>KS,string:()=>WS,text:()=>GS}),BS={42:bS,43:bS,45:bS,48:bS,49:bS,50:bS,51:bS,52:bS,53:bS,54:bS,55:bS,56:bS,57:bS,62:rx},VS={91:Ix},HS={[-2]:hx,[-1]:hx,32:hx},US={35:Hx,42:vS,45:[OS,vS],60:qx,61:OS,95:vS,96:fx,126:fx},WS={38:lx,92:sx},GS={[-5]:gS,[-4]:gS,[-3]:gS,33:fS,38:lx,42:Yb,60:[$b,eS],91:mS,92:[Bx,sx],93:nS,95:Yb,96:yx},KS={null:[Yb,NS]},qS={null:[42,95]},JS={null:[]};function YS(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=bb(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=Jb(a,l.events,l),l.events):[]}function f(e,t){return ZS(p(e),t)}function p(e){return XS(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function ZS(e,t){let n=-1,r=[],i;for(;++n0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||dC).call(a,void 0,e[0])}for(r.position={start:cC(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:cC(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d0&&(r.className=[`language-`+i[0]]);let a={type:`element`,tagName:`code`,properties:r,children:[{type:`text`,value:n}]};return t.meta&&(a.data={meta:t.meta}),e.patch(t,a),a=e.applyData(t,a),a={type:`element`,tagName:`pre`,properties:{},children:[a]},e.patch(t,a),a}function gC(e,t){let n={type:`element`,tagName:`del`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function _C(e,t){let n={type:`element`,tagName:`em`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function vC(e,t){let n=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,r=String(t.identifier).toUpperCase(),i=zb(r.toLowerCase()),a=e.footnoteOrder.indexOf(r),o,s=e.footnoteCounts.get(r);s===void 0?(s=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=a+1,s+=1,e.footnoteCounts.set(r,s);let c={type:`element`,tagName:`a`,properties:{href:`#`+n+`fn-`+i,id:n+`fnref-`+i+(s>1?`-`+s:``),dataFootnoteRef:!0,ariaDescribedBy:[`footnote-label`]},children:[{type:`text`,value:String(o)}]};e.patch(t,c);let l={type:`element`,tagName:`sup`,properties:{},children:[c]};return e.patch(t,l),e.applyData(t,l)}function yC(e,t){let n={type:`element`,tagName:`h`+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function bC(e,t){if(e.options.allowDangerousHtml){let n={type:`raw`,value:t.value};return e.patch(t,n),e.applyData(t,n)}}function xC(e,t){let n=t.referenceType,r=`]`;if(n===`collapsed`?r+=`[]`:n===`full`&&(r+=`[`+(t.label||t.identifier)+`]`),t.type===`imageReference`)return[{type:`text`,value:`![`+t.alt+r}];let i=e.all(t),a=i[0];a&&a.type===`text`?a.value=`[`+a.value:i.unshift({type:`text`,value:`[`});let o=i[i.length-1];return o&&o.type===`text`?o.value+=r:i.push({type:`text`,value:r}),i}function SC(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return xC(e,t);let i={src:zb(r.url||``),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`img`,properties:i,children:[]};return e.patch(t,a),e.applyData(t,a)}function CC(e,t){let n={src:zb(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`img`,properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function wC(e,t){let n={type:`text`,value:t.value.replace(/\r?\n|\r/g,` `)};e.patch(t,n);let r={type:`element`,tagName:`code`,properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function TC(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return xC(e,t);let i={href:zb(r.url||``)};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`a`,properties:i,children:e.all(t)};return e.patch(t,a),e.applyData(t,a)}function EC(e,t){let n={href:zb(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`a`,properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function DC(e,t,n){let r=e.all(t),i=n?OC(n):kC(t),a={},o=[];if(typeof t.checked==`boolean`){let e=r[0],n;e&&e.type===`element`&&e.tagName===`p`?n=e:(n={type:`element`,tagName:`p`,properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:`text`,value:` `}),n.children.unshift({type:`element`,tagName:`input`,properties:{type:`checkbox`,checked:t.checked,disabled:!0},children:[]}),a.className=[`task-list-item`]}let s=-1;for(;++s1}function AC(e,t){let n={},r=e.all(t),i=-1;for(typeof t.start==`number`&&t.start!==1&&(n.start=t.start);++i0){let r={type:`element`,tagName:`tbody`,properties:{},children:e.wrap(n,!0)},a=ky(t.children[1]),o=Oy(t.children[t.children.length-1]);a&&o&&(r.position={start:a,end:o}),i.push(r)}let a={type:`element`,tagName:`table`,properties:{},children:e.wrap(i,!0)};return e.patch(t,a),e.applyData(t,a)}function FC(e,t,n){let r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?`th`:`td`,a=n&&n.type===`table`?n.align:void 0,o=a?a.length:t.children.length,s=-1,c=[];for(;++s0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return a.push(BC(t.slice(i),i>0,!1)),a.join(``)}function BC(e,t,n){let r=0,i=e.length;if(t){let t=e.codePointAt(r);for(;t===LC||t===RC;)r++,t=e.codePointAt(r)}if(n){let t=e.codePointAt(i-1);for(;t===LC||t===RC;)i--,t=e.codePointAt(i-1)}return i>r?e.slice(r,i):``}function VC(e,t){let n={type:`text`,value:zC(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function HC(e,t){let n={type:`element`,tagName:`hr`,properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}var UC={blockquote:pC,break:mC,code:hC,delete:gC,emphasis:_C,footnoteReference:vC,heading:yC,html:bC,imageReference:SC,image:CC,inlineCode:wC,linkReference:TC,link:EC,listItem:DC,list:AC,paragraph:jC,root:MC,strong:NC,table:PC,tableCell:IC,tableRow:FC,text:VC,thematicBreak:HC,toml:WC,yaml:WC,definition:WC,footnoteDefinition:WC};function WC(){}var GC=typeof self==`object`?self:globalThis,KC=(e,t)=>{let n=(t,n)=>(e.set(n,t),t),r=i=>{if(e.has(i))return e.get(i);let[a,o]=t[i];switch(a){case 0:case-1:return n(o,i);case 1:{let e=n([],i);for(let t of o)e.push(r(t));return e}case 2:{let e=n({},i);for(let[t,n]of o)e[r(t)]=r(n);return e}case 3:return n(new Date(o),i);case 4:{let{source:e,flags:t}=o;return n(new RegExp(e,t),i)}case 5:{let e=n(new Map,i);for(let[t,n]of o)e.set(r(t),r(n));return e}case 6:{let e=n(new Set,i);for(let t of o)e.add(r(t));return e}case 7:{let{name:e,message:t}=o;return n(new GC[e](t),i)}case 8:return n(BigInt(o),i);case`BigInt`:return n(Object(BigInt(o)),i);case`ArrayBuffer`:return n(new Uint8Array(o).buffer,o);case`DataView`:{let{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}}return n(new GC[a](o),i)};return r},qC=e=>KC(new Map,e)(0),JC=``,{toString:YC}={},{keys:XC}=Object,ZC=e=>{let t=typeof e;if(t!==`object`||!e)return[0,t];let n=YC.call(e).slice(8,-1);switch(n){case`Array`:return[1,JC];case`Object`:return[2,JC];case`Date`:return[3,JC];case`RegExp`:return[4,JC];case`Map`:return[5,JC];case`Set`:return[6,JC];case`DataView`:return[1,n]}return n.includes(`Array`)?[1,n]:n.includes(`Error`)?[7,n]:[2,n]},QC=([e,t])=>e===0&&(t===`function`||t===`symbol`),$C=(e,t,n,r)=>{let i=(e,t)=>{let i=r.push(e)-1;return n.set(t,i),i},a=r=>{if(n.has(r))return n.get(r);let[o,s]=ZC(r);switch(o){case 0:{let t=r;switch(s){case`bigint`:o=8,t=r.toString();break;case`function`:case`symbol`:if(e)throw TypeError(`unable to serialize `+s);t=null;break;case`undefined`:return i([-1],r)}return i([o,t],r)}case 1:{if(s){let e=r;return s===`DataView`?e=new Uint8Array(r.buffer):s===`ArrayBuffer`&&(e=new Uint8Array(r)),i([s,[...e]],r)}let e=[],t=i([o,e],r);for(let t of r)e.push(a(t));return t}case 2:{if(s)switch(s){case`BigInt`:return i([s,r.toString()],r);case`Boolean`:case`Number`:case`String`:return i([s,r.valueOf()],r)}if(t&&`toJSON`in r)return a(r.toJSON());let n=[],c=i([o,n],r);for(let t of XC(r))(e||!QC(ZC(r[t])))&&n.push([a(t),a(r[t])]);return c}case 3:return i([o,r.toISOString()],r);case 4:{let{source:e,flags:t}=r;return i([o,{source:e,flags:t}],r)}case 5:{let t=[],n=i([o,t],r);for(let[n,i]of r)(e||!(QC(ZC(n))||QC(ZC(i))))&&t.push([a(n),a(i)]);return n}case 6:{let t=[],n=i([o,t],r);for(let n of r)(e||!QC(ZC(n)))&&t.push(a(n));return n}}let{message:c}=r;return i([o,{name:s,message:c}],r)};return a},ew=(e,{json:t,lossy:n}={})=>{let r=[];return $C(!(t||n),!!t,new Map,r)(e),r},tw=typeof structuredClone==`function`?(e,t)=>t&&(`json`in t||`lossy`in t)?qC(ew(e,t)):structuredClone(e):(e,t)=>qC(ew(e,t));function nw(e,t){let n=[{type:`text`,value:`↩`}];return t>1&&n.push({type:`element`,tagName:`sup`,properties:{},children:[{type:`text`,value:String(t)}]}),n}function rw(e,t){return`Back to reference `+(e+1)+(t>1?`-`+t:``)}function iw(e){let t=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,n=e.options.footnoteBackContent||nw,r=e.options.footnoteBackLabel||rw,i=e.options.footnoteLabel||`Footnotes`,a=e.options.footnoteLabelTagName||`h2`,o=e.options.footnoteLabelProperties||{className:[`sr-only`]},s=[],c=-1;for(;++c0&&d.push({type:`text`,value:` `});let e=typeof n==`string`?n:n(c,u);typeof e==`string`&&(e={type:`text`,value:e}),d.push({type:`element`,tagName:`a`,properties:{href:`#`+t+`fnref-`+l+(u>1?`-`+u:``),dataFootnoteBackref:``,ariaLabel:typeof r==`string`?r:r(c,u),className:[`data-footnote-backref`]},children:Array.isArray(e)?e:[e]})}let p=a[a.length-1];if(p&&p.type===`element`&&p.tagName===`p`){let e=p.children[p.children.length-1];e&&e.type===`text`?e.value+=` `:p.children.push({type:`text`,value:` `}),p.children.push(...d)}else a.push(...d);let m={type:`element`,tagName:`li`,properties:{id:t+`fn-`+l},children:e.wrap(a,!0)};e.patch(i,m),s.push(m)}if(s.length!==0)return{type:`element`,tagName:`section`,properties:{dataFootnotes:!0,className:[`footnotes`]},children:[{type:`element`,tagName:a,properties:{...tw(o),id:`footnote-label`},children:[{type:`text`,value:i}]},{type:`text`,value:` +`},{type:`element`,tagName:`ol`,properties:{},children:e.wrap(s,!0)},{type:`text`,value:` +`}]}}var aw=(function(e){if(e==null)return uw;if(typeof e==`function`)return lw(e);if(typeof e==`object`)return Array.isArray(e)?ow(e):sw(e);if(typeof e==`string`)return cw(e);throw Error(`Expected function, string, or object as test`)});function ow(e){let t=[],n=-1;for(;++n`:``))+`)`})}return u;function u(){let l=pw,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=hw(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d0&&n.push({type:`text`,value:` +`}),n}function ww(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Tw(e,t){let n=yw(e,t),r=n.one(e,void 0),i=iw(n),a=Array.isArray(r)?{type:`root`,children:r}:r||{type:`root`,children:[]};return i&&(`children`in a,a.children.push({type:`text`,value:` +`},i)),a}function Ew(e,t){return e&&`run`in e?async function(n,r){let i=Tw(n,{file:r,...t});await e.run(i,r)}:function(n,r){return Tw(n,{file:r,...e||t})}}function Dw(e){if(e)throw e}var Ow=o(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});ft.length,o;r&&t.push(i);try{o=e.apply(this,t)}catch(e){let t=e;if(r&&n)throw t;return i(t)}r||(o&&o.then&&typeof o.then==`function`?o.then(a,i):o instanceof Error?i(o):a(o))}function i(e,...r){n||(n=!0,t(e,...r))}function a(e){i(null,e)}}var Mw={basename:Nw,dirname:Pw,extname:Fw,join:Iw,sep:`/`};function Nw(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);zw(e);let n=0,r=-1,i=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else r<0&&(a=!0,r=i+1);return r<0?``:e.slice(n,r)}if(t===e)return``;let o=-1,s=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else o<0&&(a=!0,o=i+1),s>-1&&(e.codePointAt(i)===t.codePointAt(s--)?s<0&&(r=i):(s=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Pw(e){if(zw(e),e.length===0)return`.`;let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||=!0;return t<0?e.codePointAt(0)===47?`/`:`.`:t===1&&e.codePointAt(0)===47?`//`:e.slice(0,t)}function Fw(e){zw(e);let t=e.length,n=-1,r=0,i=-1,a=0,o;for(;t--;){let s=e.codePointAt(t);if(s===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),s===46?i<0?i=t:a!==1&&(a=1):i>-1&&(a=-1)}return i<0||n<0||a===0||a===1&&i===n-1&&i===r+1?``:e.slice(i,n)}function Iw(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+=`/`),t?`/`+n:n}function Rw(e,t){let n=``,r=0,i=-1,a=0,o=-1,s,c;for(;++o<=e.length;){if(o2){if(c=n.lastIndexOf(`/`),c!==n.length-1){c<0?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=o,a=0;continue}}else if(n.length>0){n=``,r=0,i=o,a=0;continue}}t&&(n=n.length>0?n+`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1;i=o,a=0}else s===46&&a>-1?a++:a=-1}return n}function zw(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}var Bw={cwd:Vw};function Vw(){return`/`}function Hw(e){return!!(typeof e==`object`&&e&&`href`in e&&e.href&&`protocol`in e&&e.protocol&&e.auth===void 0)}function Uw(e){if(typeof e==`string`)e=new URL(e);else if(!Hw(e)){let t=TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code=`ERR_INVALID_ARG_TYPE`,t}if(e.protocol!==`file:`){let e=TypeError(`The URL must be of scheme file`);throw e.code=`ERR_INVALID_URL_SCHEME`,e}return Ww(e)}function Ww(e){if(e.hostname!==``){let e=TypeError(`File URL host must be "localhost" or empty on darwin`);throw e.code=`ERR_INVALID_FILE_URL_HOST`,e}let t=e.pathname,n=-1;for(;++n0){let[r,...a]=t,o=n[i][1];kw(o)&&kw(r)&&(r=(0,Qw.default)(!0,o,r)),n[i]=[e,r,...a]}}}}().freeze();function tT(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `parser`")}function nT(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `compiler`")}function rT(e,t){if(t)throw Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function iT(e){if(!kw(e)||typeof e.type!=`string`)throw TypeError("Expected node, got `"+e+"`")}function aT(e,t,n){if(!n)throw Error("`"+e+"` finished async. Use `"+t+"` instead")}function oT(e){return sT(e)?e:new Kw(e)}function sT(e){return!!(e&&typeof e==`object`&&`message`in e&&`messages`in e)}function cT(e){return typeof e==`string`||lT(e)}function lT(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var uT=[],dT={allowDangerousHtml:!0},fT=/^(https?|ircs?|mailto|xmpp)$/i,pT=[{from:`astPlugins`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowDangerousHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowNode`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowElement`},{from:`allowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowedElements`},{from:`className`,id:`remove-classname`},{from:`disallowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`disallowedElements`},{from:`escapeHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`includeElementIndex`,id:`#remove-includeelementindex`},{from:`includeNodeIndex`,id:`change-includenodeindex-to-includeelementindex`},{from:`linkTarget`,id:`remove-linktarget`},{from:`plugins`,id:`change-plugins-to-remarkplugins`,to:`remarkPlugins`},{from:`rawSourcePos`,id:`#remove-rawsourcepos`},{from:`renderers`,id:`change-renderers-to-components`,to:`components`},{from:`source`,id:`change-source-to-children`,to:`children`},{from:`sourcePos`,id:`#remove-sourcepos`},{from:`transformImageUri`,id:`#add-urltransform`,to:`urlTransform`},{from:`transformLinkUri`,id:`#add-urltransform`,to:`urlTransform`}];function mT(e){let t=hT(e),n=gT(e);return _T(t.runSync(t.parse(n),n),e)}function hT(e){let t=e.rehypePlugins||uT,n=e.remarkPlugins||uT,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...dT}:dT;return eT().use(fC).use(n).use(Ew,r).use(t)}function gT(e){let t=e.children||``,n=new Kw;return typeof t==`string`?n.value=t:``+t,n}function _T(e,t){let n=t.allowedElements,r=t.allowElement,i=t.components,a=t.disallowedElements,o=t.skipHtml,s=t.unwrapDisallowed,c=t.urlTransform||vT;for(let e of pT)Object.hasOwn(t,e.from)&&``+e.from+(e.to?"use `"+e.to+"` instead":`remove it`)+e.id;return gw(e,l),Uy(e,{Fragment:H.Fragment,components:i,ignoreInvalidStyle:!0,jsx:H.jsx,jsxs:H.jsxs,passKeys:!0,passNode:!0});function l(e,t,i){if(e.type===`raw`&&i&&typeof t==`number`)return o?i.children.splice(t,1):i.children[t]={type:`text`,value:e.value},t;if(e.type===`element`){let t;for(t in db)if(Object.hasOwn(db,t)&&Object.hasOwn(e.properties,t)){let n=e.properties[t],r=db[t];(r===null||r.includes(e.tagName))&&(e.properties[t]=c(String(n||``),t,e))}}if(e.type===`element`){let o=n?!n.includes(e.tagName):a?a.includes(e.tagName):!1;if(!o&&r&&typeof t==`number`&&(o=!r(e,t,i)),o&&i&&typeof t==`number`)return s&&e.children?i.children.splice(t,1,...e.children):i.children.splice(t,1),t}}}function vT(e){let t=e.indexOf(`:`),n=e.indexOf(`?`),r=e.indexOf(`#`),i=e.indexOf(`/`);return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||fT.test(e.slice(0,t))?e:``}function yT(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function bT(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function xT(e,t,n){let r=aw((n||{}).ignore||[]),i=ST(t),a=-1;for(;++a0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=yT(e,`(`),a=yT(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function BT(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||Lb(n)||Ib(n))&&(!t||n!==47)}XT.peek=YT;function VT(){this.buffer()}function HT(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function UT(){this.buffer()}function WT(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function GT(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Eb(this.sliceSerialize(e)).toLowerCase(),n.label=t}function KT(e){this.exit(e)}function qT(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Eb(this.sliceSerialize(e)).toLowerCase(),n.label=t}function JT(e){this.exit(e)}function YT(){return`[`}function XT(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function ZT(){return{enter:{gfmFootnoteCallString:VT,gfmFootnoteCall:HT,gfmFootnoteDefinitionLabelString:UT,gfmFootnoteDefinition:WT},exit:{gfmFootnoteCallString:GT,gfmFootnoteCall:KT,gfmFootnoteDefinitionLabelString:qT,gfmFootnoteDefinition:JT}}}function QT(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:XT},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?` +`:` `)+r.indentLines(r.containerFlow(e,a.current()),t?eE:$T))),s(),o}}function $T(e,t,n){return t===0?e:eE(e,t,n)}function eE(e,t,n){return(n?``:` `)+e}var tE=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];oE.peek=sE;function nE(){return{canContainEols:[`delete`],enter:{strikethrough:iE},exit:{strikethrough:aE}}}function rE(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:tE}],handlers:{delete:oE}}}function iE(e){this.enter({type:`delete`,children:[]},e)}function aE(e){this.exit(e)}function oE(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function sE(){return`~`}function cE(e){return e.length}function lE(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||cE,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++ul&&(l=e[u].length);++ac[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++dc[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u `),a.shift(2);let o=n.indentLines(n.containerFlow(e,a.current()),pE);return i(),o}function pE(e,t,n){return`>`+(n?``:` `)+e}function mE(e,t){return hE(e,t.inConstruct,!0)&&!hE(e,t.notInConstruct,!1)}function hE(e,t,n){if(typeof t==`string`&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++ro&&(o=a):a=1,i=r+t.length,r=n.indexOf(t,i);return o}function vE(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function yE(e){let t=e.options.fence||"`";if(t!=="`"&&t!==`~`)throw Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function bE(e,t,n,r){let i=yE(n),a=e.value||``,o=i==="`"?`GraveAccent`:`Tilde`;if(vE(e,n)){let e=n.enter(`codeIndented`),t=n.indentLines(a,xE);return e(),t}let s=n.createTracker(r),c=i.repeat(Math.max(_E(a,i)+1,3)),l=n.enter(`codeFenced`),u=s.move(c);if(e.lang){let t=n.enter(`codeFencedLang${o}`);u+=s.move(n.safe(e.lang,{before:u,after:` `,encode:["`"],...s.current()})),t()}if(e.lang&&e.meta){let t=n.enter(`codeFencedMeta${o}`);u+=s.move(` `),u+=s.move(n.safe(e.meta,{before:u,after:` +`,encode:["`"],...s.current()})),t()}return u+=s.move(` +`),a&&(u+=s.move(a+` +`)),u+=s.move(c),l(),u}function xE(e,t,n){return(n?``:` `)+e}function SE(e){let t=e.options.quote||`"`;if(t!==`"`&&t!==`'`)throw Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function CE(e,t,n,r){let i=SE(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`definition`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`[`);return l+=c.move(n.safe(n.associationId(e),{before:l,after:`]`,...c.current()})),l+=c.move(`]: `),s(),!e.url||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:` +`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),o(),l}function wE(e){let t=e.options.emphasis||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function TE(e){return`&#x`+e.toString(16).toUpperCase()+`;`}function EE(e,t,n){let r=qb(e),i=qb(t);return r===void 0?i===void 0?n===`_`?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}DE.peek=OE;function DE(e,t,n,r){let i=wE(n),a=n.enter(`emphasis`),o=n.createTracker(r),s=o.move(i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=EE(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=TE(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=EE(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+TE(d));let p=o.move(i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function OE(e,t,n){return n.options.emphasis||`*`}function kE(e,t){let n=!1;return gw(e,function(e){if(`value`in e&&/\r?\n|\r/.test(e.value)||e.type===`break`)return n=!0,!1}),!!((!e.depth||e.depth<3)&&pb(e)&&(t.options.setext||n))}function AE(e,t,n,r){let i=Math.max(Math.min(6,e.depth||1),1),a=n.createTracker(r);if(kE(e,n)){let t=n.enter(`headingSetext`),r=n.enter(`phrasing`),o=n.containerPhrasing(e,{...a.current(),before:` +`,after:` +`});return r(),t(),o+` +`+(i===1?`=`:`-`).repeat(o.length-(Math.max(o.lastIndexOf(`\r`),o.lastIndexOf(` +`))+1))}let o=`#`.repeat(i),s=n.enter(`headingAtx`),c=n.enter(`phrasing`);a.move(o+` `);let l=n.containerPhrasing(e,{before:`# `,after:` +`,...a.current()});return/^[\t ]/.test(l)&&(l=TE(l.charCodeAt(0))+l.slice(1)),l=l?o+` `+l:o,n.options.closeAtx&&(l+=` `+o),c(),s(),l}jE.peek=ME;function jE(e){return e.value||``}function ME(){return`<`}NE.peek=PE;function NE(e,t,n,r){let i=SE(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`image`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`![`);return l+=c.move(n.safe(e.alt,{before:l,after:`]`,...c.current()})),l+=c.move(`](`),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),l+=c.move(`)`),o(),l}function PE(){return`!`}FE.peek=IE;function FE(e,t,n,r){let i=e.referenceType,a=n.enter(`imageReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`![`),l=n.safe(e.alt,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function IE(){return`!`}LE.peek=RE;function LE(e,t,n){let r=e.value||``,i="`",a=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=` `+r+` `);++a\u007F]/.test(e.url))}BE.peek=VE;function BE(e,t,n,r){let i=SE(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.createTracker(r),s,c;if(zE(e,n)){let t=n.stack;n.stack=[],s=n.enter(`autolink`);let r=o.move(`<`);return r+=o.move(n.containerPhrasing(e,{before:r,after:`>`,...o.current()})),r+=o.move(`>`),s(),n.stack=t,r}s=n.enter(`link`),c=n.enter(`label`);let l=o.move(`[`);return l+=o.move(n.containerPhrasing(e,{before:l,after:`](`,...o.current()})),l+=o.move(`](`),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter(`destinationLiteral`),l+=o.move(`<`),l+=o.move(n.safe(e.url,{before:l,after:`>`,...o.current()})),l+=o.move(`>`)):(c=n.enter(`destinationRaw`),l+=o.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...o.current()}))),c(),e.title&&(c=n.enter(`title${a}`),l+=o.move(` `+i),l+=o.move(n.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(`)`),s(),l}function VE(e,t,n){return zE(e,n)?`<`:`[`}HE.peek=UE;function HE(e,t,n,r){let i=e.referenceType,a=n.enter(`linkReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`[`),l=n.containerPhrasing(e,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function UE(){return`[`}function WE(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function GE(e){let t=WE(e),n=e.options.bulletOther;if(!n)return t===`*`?`-`:`*`;if(n!==`*`&&n!==`+`&&n!==`-`)throw Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function KE(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function qE(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function JE(e,t,n,r){let i=n.enter(`list`),a=n.bulletCurrent,o=e.ordered?KE(n):WE(n),s=e.ordered?o===`.`?`)`:`.`:GE(n),c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((o===`*`||o===`-`)&&t&&(!t.children||!t.children[0])&&n.stack[n.stack.length-1]===`list`&&n.stack[n.stack.length-2]===`listItem`&&n.stack[n.stack.length-3]===`list`&&n.stack[n.stack.length-4]===`listItem`&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),qE(n)===o&&t){let t=-1;for(;++t-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+a);let o=a.length+1;(i===`tab`||i===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let s=n.createTracker(r);s.move(a+` `.repeat(o-a.length)),s.shift(o);let c=n.enter(`listItem`),l=n.indentLines(n.containerFlow(e,s.current()),u);return c(),l;function u(e,t,n){return t?(n?``:` `.repeat(o))+e:(n?a:a+` `.repeat(o-a.length))+e}}function ZE(e,t,n,r){let i=n.enter(`paragraph`),a=n.enter(`phrasing`),o=n.containerPhrasing(e,r);return a(),i(),o}var QE=aw([`break`,`delete`,`emphasis`,`footnote`,`footnoteReference`,`image`,`imageReference`,`inlineCode`,`inlineMath`,`link`,`linkReference`,`mdxJsxTextElement`,`mdxTextExpression`,`strong`,`text`,`textDirective`]);function $E(e,t,n,r){return(e.children.some(function(e){return QE(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function eD(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}tD.peek=nD;function tD(e,t,n,r){let i=eD(n),a=n.enter(`strong`),o=n.createTracker(r),s=o.move(i+i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=EE(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=TE(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=EE(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+TE(d));let p=o.move(i+i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function nD(e,t,n){return n.options.strong||`*`}function rD(e,t,n,r){return n.safe(e.value,r)}function iD(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function aD(e,t,n){let r=(qE(n)+(n.options.ruleSpaces?` `:``)).repeat(iD(n));return n.options.ruleSpaces?r.slice(0,-1):r}var oD={blockquote:fE,break:gE,code:bE,definition:CE,emphasis:DE,hardBreak:gE,heading:AE,html:jE,image:NE,imageReference:FE,inlineCode:LE,link:BE,linkReference:HE,list:JE,listItem:XE,paragraph:ZE,root:$E,strong:tD,text:rD,thematicBreak:aD};function sD(){return{enter:{table:cD,tableData:fD,tableHeader:fD,tableRow:uD},exit:{codeText:pD,table:lD,tableData:dD,tableHeader:dD,tableRow:dD}}}function cD(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function lD(e){this.exit(e),this.data.inTable=void 0}function uD(e){this.enter({type:`tableRow`,children:[]},e)}function dD(e){this.exit(e)}function fD(e){this.enter({type:`tableCell`,children:[]},e)}function pD(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,mD));let n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function mD(e,t){return t===`|`?t:e}function hD(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,a=n?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:` +`,inConstruct:`tableCell`},{atBreak:!0,character:`|`,after:`[ :-]`},{character:`|`,inConstruct:`tableCell`},{atBreak:!0,character:`:`,after:`-`},{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:s}};function o(e,t,n,r){return l(u(e,n,r),e.align)}function s(e,t,n,r){let i=l([d(e,n,r)]);return i.slice(0,i.indexOf(` +`))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return lE(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var qD={tokenize:tO,partial:!0};function JD(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:QD,continuation:{tokenize:$D},exit:eO}},text:{91:{name:`gfmFootnoteCall`,tokenize:ZD},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:YD,resolveTo:XD}}}}function YD(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=Eb(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function XD(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function ZD(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||Pb(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(Eb(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return Pb(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function QD(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||Pb(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=Eb(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return Pb(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),Bb(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function $D(e,t,n){return e.check(tx,t,e.attempt(qD,t,n))}function eO(e){e.exit(`gfmFootnoteDefinition`)}function tO(e,t,n){let r=this;return Bb(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function nO(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=qb(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var rO=class{constructor(){this.map=[]}add(e,t,n){iO(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}};function iO(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i-1;){let e=r.events[t][1].type;if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):$(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):Fb(t)?Bb(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||Pb(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,Fb(t)?Bb(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return Fb(t)?Bb(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||$(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return Fb(t)?Bb(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||$(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||$(n)?(e.exit(`tableRow`),t(n)):Fb(n)?Bb(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||Pb(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function cO(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new rO;for(;++nn[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},dO(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function uO(e,t,n,r,i){let a=[],o=dO(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function dO(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var fO={name:`tasklistCheck`,tokenize:mO};function pO(){return{text:{91:fO}}}function mO(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return Pb(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return $(r)?t(r):Fb(r)?e.check({tokenize:hO},t,n)(r):n(r)}}function hO(e,t,n){return Bb(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function gO(e){return Sb([MD(),JD(),nO(e),oO(),pO()])}var _O={};function vO(e){let t=this,n=e||_O,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(gO(n)),a.push(xD()),o.push(SD(n))}var yO=new Set([`.md`,`.markdown`,`.mdx`]);function bO({filePath:e,onClose:t}){let[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(!0),c=(0,v.useCallback)(async()=>{s(!0),a(null);try{let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`),n=await fetch(`/api/files/${t}`);if(!n.ok){a((await n.json().catch(()=>({}))).error||`HTTP ${n.status}`);return}r(await n.json())}catch(e){a(e instanceof Error?e.message:`Failed to load file`)}finally{s(!1)}},[e]);(0,v.useEffect)(()=>{c()},[c]),(0,v.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let l=n?yO.has(n.extension):!1;return(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`relative flex flex-col w-[90vw] max-w-3xl max-h-[80vh] rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-2xl overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2.5 border-b border-[var(--border)] bg-[var(--surface-raised)] flex-shrink-0`,children:[(0,H.jsx)(ce,{className:`w-4 h-4 text-[var(--text-muted)] flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate flex-1`,title:e,children:e}),n&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] flex-shrink-0 tabular-nums`,children:SO(n.size)}),(0,H.jsx)(`button`,{onClick:t,className:`p-1 rounded-md text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--surface-hover)] transition-colors flex-shrink-0`,title:`Close (Esc)`,children:(0,H.jsx)(Me,{className:`w-4 h-4`})})]}),(0,H.jsxs)(`div`,{className:`flex-1 overflow-auto px-5 py-4 min-h-0`,children:[o&&(0,H.jsx)(`div`,{className:`flex items-center justify-center py-12`,children:(0,H.jsx)(pe,{className:`w-5 h-5 text-[var(--text-muted)] animate-spin`})}),i&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30`,children:[(0,H.jsx)(Oe,{className:`w-4 h-4 text-red-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs text-red-300`,children:i})]}),n&&!i&&(l?(0,H.jsx)(`div`,{className:`file-viewer-markdown text-xs leading-relaxed text-[var(--text)]`,children:(0,H.jsx)(xO,{content:n.content})}):(0,H.jsx)(`pre`,{className:`font-mono text-[11px] leading-[1.6] text-[var(--text)] whitespace-pre-wrap break-words`,children:n.content}))]})]})})}function xO({content:e}){return(0,H.jsx)(mT,{remarkPlugins:[vO],components:{h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-base font-bold mb-3 mt-2 text-[var(--text)]`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-sm font-bold mb-2 mt-3 text-[var(--text)]`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xs font-bold mb-1.5 mt-2 text-[var(--text)]`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`mb-2 last:mb-0`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside mb-2 space-y-1 ml-2`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside mb-2 space-y-1 ml-2`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{children:e}),code:({children:e,className:t})=>t?.includes(`language-`)?(0,H.jsx)(`code`,{className:`block bg-[var(--bg)] border border-[var(--border)] rounded px-3 py-2 font-mono text-[11px] my-2 overflow-x-auto whitespace-pre`,children:e}):(0,H.jsx)(`code`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded px-1 py-0.5 font-mono text-[11px]`,children:e}),pre:({children:e})=>(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md px-3 py-2.5 font-mono text-[11px] my-2 overflow-x-auto`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic`,children:e}),a:({href:e,children:t})=>(0,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-400 hover:text-blue-300 underline underline-offset-2`,children:t}),blockquote:({children:e})=>(0,H.jsx)(`blockquote`,{className:`border-l-2 border-[var(--border)] pl-3 my-2 opacity-80`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`border-[var(--border)] my-3`}),table:({children:e})=>(0,H.jsx)(`div`,{className:`overflow-x-auto my-2`,children:(0,H.jsx)(`table`,{className:`text-[11px] border-collapse w-full`,children:e})}),th:({children:e})=>(0,H.jsx)(`th`,{className:`border border-[var(--border)] px-2 py-1 text-left bg-[var(--bg)] font-semibold`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`border border-[var(--border)] px-2 py-1`,children:e})},children:e})}function SO(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function CO({node:e}){let t=B(e=>e.sendGateResponse),n=B(e=>e.wsStatus),[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(!1),[d,f]=(0,v.useState)(!1),[p,m]=(0,v.useState)(null),h=e.status===`waiting`,g=e.status===`completed`;(0,v.useEffect)(()=>{h&&(i(null),o(``),c(null),u(!1),f(!1))},[h,e.gate_prompt_id]);let _=h&&n===`connected`&&r===null,y=(n,r,a)=>{if(_){if(r){i(n),c(r),u(!!a);return}i(n),f(!0),t(e.name,n,void 0,e.gate_prompt_id)}},b=()=>{if(r===null||s===null)return;let n={[s]:a};f(!0),t(e.name,r,n,e.gate_prompt_id),c(null),u(!1)},x=e.option_details,S=x?.find(t=>t.value===e.selected_option)?.label||e.selected_option;return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[h&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30`,children:[(0,H.jsxs)(`span`,{className:`relative flex h-2.5 w-2.5 flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75`}),(0,H.jsx)(`span`,{className:`relative inline-flex rounded-full h-2.5 w-2.5 bg-amber-500`})]}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-amber-400 tracking-wide`,children:`Decision Required`})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-amber-500/50 pl-3 py-0.5`,children:(0,H.jsx)(TO,{text:e.prompt,muted:!1,onFileClick:m})}),x&&x.length>0&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:x.map(e=>{let t=r===e.value,n=r!==null&&!t;return(0,H.jsx)(`button`,{disabled:!_&&!t,onClick:()=>y(e.value,e.prompt_for,e.multiline),className:`w-full text-left px-3 py-2.5 rounded-lg border transition-all duration-150 ${t?`border-green-500/60 bg-green-500/10`:n?`border-[var(--border)] opacity-40 cursor-default`:`border-[var(--border)] bg-[var(--surface)] hover:border-amber-400/60 hover:bg-amber-500/5 cursor-pointer group`}`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0`,children:t?(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full bg-green-500 flex items-center justify-center`,children:(0,H.jsx)(j,{className:`w-2.5 h-2.5 text-white`,strokeWidth:3})}):(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full border-2 transition-colors ${n?`border-[var(--border)]`:`border-[var(--border)] group-hover:border-amber-400`}`})}),(0,H.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,H.jsx)(`span`,{className:`text-xs font-medium ${t?`text-green-400`:`text-[var(--text)]`}`,children:e.label})}),e.route?(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] flex-shrink-0`,children:[`→ `,e.route]}):null]})},e.value)})}),d&&!s&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-1`,children:[(0,H.jsx)(pe,{className:`w-3 h-3 text-green-400 animate-spin`}),(0,H.jsx)(`span`,{className:`text-[10px] text-green-400`,children:`Sending...`})]}),_&&(0,H.jsx)(`p`,{className:`text-[10px] text-[var(--text-muted)] px-1`,children:`Select an option to continue the workflow`})]}),!x&&e.options&&e.options.length>0&&(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(`h4`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Options`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.options.map(e=>(0,H.jsx)(`span`,{className:`text-[11px] px-2 py-0.5 rounded border border-[var(--border)] text-[var(--text-muted)]`,children:e},e))})]}),s&&(0,H.jsxs)(`div`,{className:`rounded-lg border border-[var(--border)] bg-[var(--bg)] overflow-hidden`,children:[(0,H.jsx)(`div`,{className:`px-3 py-2 border-b border-[var(--border)] bg-[var(--surface)]`,children:(0,H.jsx)(`h4`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:s})}),(0,H.jsxs)(`div`,{className:`p-3 space-y-2`,children:[l?(0,H.jsx)(`textarea`,{value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())},rows:6,placeholder:`Enter ${s}...`,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-amber-400 transition-colors resize-y font-mono leading-relaxed`,autoFocus:!0}):(0,H.jsx)(`input`,{type:`text`,value:a,onChange:e=>o(e.target.value),onKeyDown:e=>e.key===`Enter`&&b(),placeholder:`Enter ${s}...`,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-amber-400 transition-colors`,autoFocus:!0}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)]`,children:l?`Enter inserts a newline — press Ctrl/Cmd+Enter or click Submit`:`Press Enter or click Submit`}),(0,H.jsxs)(`button`,{onClick:b,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg bg-amber-500 text-white hover:bg-amber-600 transition-colors font-medium`,children:[(0,H.jsx)(Se,{className:`w-3 h-3`}),`Submit`]})]})]})]})]}),g&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-green-500/10 border border-green-500/30`,children:[(0,H.jsx)(j,{className:`w-3.5 h-3.5 text-green-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-green-400 tracking-wide`,children:`Decision Completed`})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-[var(--border)] pl-3 py-0.5`,children:(0,H.jsx)(TO,{text:e.prompt,muted:!0,onFileClick:m})}),S&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2.5 rounded-lg border border-green-500/30 bg-green-500/5`,children:[(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full bg-green-500 flex items-center justify-center flex-shrink-0`,children:(0,H.jsx)(j,{className:`w-2.5 h-2.5 text-white`,strokeWidth:3})}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)]`,children:S}),e.route&&(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[`→ `,e.route]})]}),x&&x.length>1&&(0,H.jsx)(`div`,{className:`space-y-1`,children:x.filter(t=>t.value!==e.selected_option).map(e=>(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg opacity-35`,children:[(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full border-2 border-[var(--border)] flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:e.label}),e.route&&(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[`→ `,e.route]})]},e.value))}),!x&&e.options&&e.options.length>0&&(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.options.map(t=>(0,H.jsxs)(`span`,{className:`text-[11px] px-2.5 py-1 rounded-lg border ${t===e.selected_option?`border-green-500/30 text-green-400 bg-green-500/5`:`border-[var(--border)] text-[var(--text-muted)] opacity-40`}`,children:[t===e.selected_option&&`✓ `,t]},t))}),(0,H.jsx)(EO,{node:e})]}),!h&&!g&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Human Gate`}),(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] capitalize`,children:[`(`,e.status,`)`]})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-[var(--border)] pl-3 py-0.5`,children:(0,H.jsx)(TO,{text:e.prompt,muted:!0,onFileClick:m})})]}),p&&(0,H.jsx)(bO,{filePath:p,onClose:()=>m(null)})]})}function wO(e){return!(!e||/^[a-z][a-z0-9+.-]*:/i.test(e)||e.startsWith(`//`)||e.startsWith(`#`)||e.startsWith(`/`)||e.startsWith(`\\`))}function TO({text:e,muted:t,onFileClick:n}){return(0,H.jsx)(`div`,{className:`gate-markdown text-xs leading-relaxed ${t?`text-[var(--text-muted)]`:`text-[var(--text)]`}`,children:(0,H.jsx)(mT,{remarkPlugins:[vO],components:{h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-sm font-bold mb-2 mt-1`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-xs font-bold mb-1.5 mt-1`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xs font-semibold mb-1 mt-1`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`mb-1.5 last:mb-0`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside mb-1.5 space-y-0.5`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside mb-1.5 space-y-0.5`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{children:e}),code:({children:e,className:t})=>t?.includes(`language-`)?(0,H.jsx)(`code`,{className:`block bg-[var(--bg)] border border-[var(--border)] rounded px-2 py-1.5 font-mono text-[11px] my-1 overflow-x-auto whitespace-pre`,children:e}):(0,H.jsx)(`code`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded px-1 py-0.5 font-mono text-[11px]`,children:e}),pre:({children:e})=>(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md px-2.5 py-2 font-mono text-[11px] my-1.5 overflow-x-auto`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic`,children:e}),a:({href:e,children:t})=>n&&wO(e)?(0,H.jsxs)(`button`,{onClick:t=>{t.preventDefault(),n(e)},className:`inline-flex items-center gap-0.5 text-blue-400 hover:text-blue-300 underline underline-offset-2 cursor-pointer`,title:`Open ${e}`,children:[(0,H.jsx)(ce,{className:`w-3 h-3 inline flex-shrink-0`}),t]}):(0,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-400 hover:text-blue-300 underline underline-offset-2`,children:t}),blockquote:({children:e})=>(0,H.jsx)(`blockquote`,{className:`border-l-2 border-[var(--border)] pl-2.5 my-1.5 opacity-80`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`border-[var(--border)] my-2`}),table:({children:e})=>(0,H.jsx)(`div`,{className:`overflow-x-auto my-2`,children:(0,H.jsx)(`table`,{className:`text-[11px] border-collapse w-full`,children:e})}),th:({children:e})=>(0,H.jsx)(`th`,{className:`border border-[var(--border)] px-2 py-1 text-left bg-[var(--bg)] font-semibold`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`border border-[var(--border)] px-2 py-1`,children:e})},children:e})})}function EO({node:e}){let t=[];if(e.route&&t.push({label:`Route`,value:`→ ${e.route}`}),e.additional_input){let n=typeof e.additional_input==`object`?JSON.stringify(e.additional_input):e.additional_input;t.push({label:`Additional Input`,value:n})}return t.length===0?null:(0,H.jsx)(Sv,{items:t})}function DO({node:e}){let[t,n]=(0,v.useState)(null),r=e.status===`waiting`,i=e.status===`completed`;if(r)return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsx)(OO,{node:e}),e.questions_reject_reason&&(0,H.jsx)(`div`,{className:`px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30 text-[11px] text-red-400`,children:e.questions_reject_reason}),(0,H.jsx)(CO,{node:e})]});if(!i)return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Questions`}),(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] capitalize`,children:[`(`,e.status,`)`]})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-[var(--border)] pl-3 py-0.5`,children:(0,H.jsx)(TO,{text:e.prompt,muted:!0,onFileClick:n})}),t&&(0,H.jsx)(bO,{filePath:t,onClose:()=>n(null)})]});let a=e.questions_answered_count??0,o=e.questions_skipped_count??0,s=e.questions_outcome??`completed`,c=s===`aborted`;return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg border ${c?`bg-amber-500/10 border-amber-500/30`:`bg-green-500/10 border-green-500/30`}`,children:[c?(0,H.jsx)(O,{className:`w-3.5 h-3.5 text-amber-400 flex-shrink-0`}):(0,H.jsx)(j,{className:`w-3.5 h-3.5 text-green-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold tracking-wide ${c?`text-amber-400`:`text-green-400`}`,children:c?`Questions Aborted`:s===`skipped_remaining`?`Remaining Questions Skipped`:`Questions Completed`})]}),(0,H.jsx)(Sv,{items:[{label:`Answered`,value:a},{label:`Skipped`,value:o},{label:`Outcome`,value:s}]})]})}function OO({node:e}){let t=e.questions_total??0,n=e.questions_answered_count??0,r=e.questions_skipped_count??0,i=n+r,a=t>0?Math.round(i/t*100):0;return(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-[var(--text-muted)]`,children:[(0,H.jsx)(fe,{className:`w-3 h-3 flex-shrink-0`}),(0,H.jsxs)(`span`,{children:[i,` of `,t,` answered`]}),r>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(we,{className:`w-3 h-3`}),r,` skipped`]})]}),(0,H.jsx)(`div`,{className:`h-1 rounded-full bg-[var(--border)] overflow-hidden`,children:(0,H.jsx)(`div`,{className:`h-full bg-amber-500 transition-all duration-300`,style:{width:`${a}%`}})})]})}function kO({node:e}){let t=e.status,n=X[t]||X.pending,r=Wh()[e.name],i=e.type===`for_each_group`,[a,o]=(0,v.useState)(!0),s=[];e.elapsed!=null&&s.push({label:`Elapsed`,value:W(e.elapsed)}),r&&(s.push({label:`Total`,value:r.total}),s.push({label:`Completed`,value:r.completed}),r.failed>0&&s.push({label:`Failed`,value:r.failed})),e.success_count!=null&&s.push({label:`Success`,value:e.success_count}),e.failure_count!=null&&s.push({label:`Failures`,value:e.failure_count});let c=e.for_each_items;return(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:i?`For-Each Group`:`Parallel Group`})]}),r&&r.total>0&&(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsxs)(`div`,{className:`flex justify-between text-[10px] text-[var(--text-muted)]`,children:[(0,H.jsx)(`span`,{children:`Progress`}),(0,H.jsxs)(`span`,{children:[r.completed+r.failed,`/`,r.total]})]}),(0,H.jsx)(`div`,{className:`h-1.5 bg-[var(--bg)] rounded-full overflow-hidden`,children:(0,H.jsx)(`div`,{className:`h-full rounded-full transition-all duration-500`,style:{width:`${(r.completed+r.failed)/r.total*100}%`,background:r.failed>0?`linear-gradient(90deg, var(--completed) ${r.completed/(r.completed+r.failed)*100}%, var(--failed) 0%)`:`var(--completed)`}})})]}),(0,H.jsx)(Sv,{items:s}),i&&c&&c.length>0&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`button`,{onClick:()=>o(!a),className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold hover:text-[var(--text)] transition-colors`,children:[a?(0,H.jsx)(M,{className:`w-3 h-3`}):(0,H.jsx)(N,{className:`w-3 h-3`}),`Items (`,c.length,`)`]}),a&&(0,H.jsx)(`div`,{className:`space-y-1`,children:c.map(t=>(0,H.jsx)(jO,{groupName:e.name,item:t},`${t.key}-${t.index}`))})]})]})}var AO={running:X.running,completed:X.completed,failed:X.failed};function jO({groupName:e,item:t}){let[n,r]=(0,v.useState)(t.status===`running`),i=AO[t.status],a=Gh(),o=B(e=>e.navigateIntoSubworkflow),s=`${e}[${t.key}]`,c=a.find(e=>e.slotKey===s),l=!!c,u=!!(t.prompt||t.output!=null||t.activity&&t.activity.length>0||t.error_type||t.mcp_server!=null),d=[];return t.elapsed!=null&&d.push({label:`Elapsed`,value:W(t.elapsed)}),t.tokens!=null&&d.push({label:`Tokens`,value:_t(t.tokens)}),t.cost_usd!=null&&d.push({label:`Cost`,value:vt(t.cost_usd)}),t.mcp_server&&d.push({label:`Server`,value:t.mcp_server}),t.mcp_tool&&d.push({label:`Tool`,value:t.mcp_tool}),t.mcp_result_bytes!=null&&d.push({label:`Result Bytes`,value:`${t.mcp_result_bytes}${t.mcp_truncated?` (truncated)`:``}`}),t.mcp_spill_path&&d.push({label:`Spill Path`,value:t.mcp_spill_path}),(0,H.jsxs)(`div`,{className:`rounded-lg border border-[var(--border)] bg-[var(--surface)] overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center`,children:[(0,H.jsxs)(`button`,{onClick:()=>u&&r(!n),className:`flex items-center gap-2 flex-1 min-w-0 px-3 py-2 text-left hover:bg-[var(--node-bg)] transition-colors`,disabled:!u,children:[u?n?(0,H.jsx)(M,{className:`w-3 h-3 text-[var(--text-muted)] flex-shrink-0`}):(0,H.jsx)(N,{className:`w-3 h-3 text-[var(--text-muted)] flex-shrink-0`}):t.status===`running`?(0,H.jsx)(pe,{className:`w-3 h-3 animate-spin flex-shrink-0`,style:{color:i}}):(0,H.jsx)(`span`,{className:`w-2 h-2 rounded-full flex-shrink-0 ml-0.5 mr-0.5`,style:{backgroundColor:i}}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate flex-1 min-w-0`,children:t.key}),!n&&(t.elapsed!=null||t.tokens!=null||t.cost_usd!=null)&&(0,H.jsxs)(`span`,{className:`flex items-center gap-2 text-[10px] text-[var(--text-muted)] flex-shrink-0`,children:[t.elapsed!=null&&(0,H.jsx)(`span`,{children:W(t.elapsed)}),t.tokens!=null&&(0,H.jsx)(`span`,{children:_t(t.tokens)}),t.cost_usd!=null&&(0,H.jsx)(`span`,{children:vt(t.cost_usd)})]}),(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider flex-shrink-0 px-1.5 py-0.5 rounded`,style:{backgroundColor:`${i}20`,color:i},children:t.status})]}),l&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>o(s),title:`Dive into ${c?.workflowName??s}`,className:`flex-shrink-0 mr-2 p-1 rounded hover:bg-[var(--accent)]/20 hover:text-[var(--accent)] transition-colors text-[var(--text-muted)] cursor-pointer`,children:(0,H.jsx)(de,{className:`w-3 h-3`})})]}),n&&u&&(0,H.jsxs)(`div`,{className:`px-3 py-3 space-y-3 border-t border-[var(--border)]`,children:[d.length>0&&(0,H.jsx)(Sv,{items:d}),t.mcp_is_error===!0&&(0,H.jsx)(`div`,{className:`text-xs text-amber-500 font-semibold px-1`,children:`Tool reported an error (is_error)`}),t.prompt&&(0,H.jsx)(wv,{output:t.prompt,title:`Input / Prompt`,defaultExpanded:!1}),t.activity&&t.activity.length>0&&(0,H.jsx)(Ev,{activity:t.activity,defaultExpanded:t.status!==`completed`}),t.output!=null&&(0,H.jsx)(wv,{output:t.output,title:`Output`,defaultExpanded:!0}),t.status===`failed`&&(t.error_type||t.error_message)&&(0,H.jsxs)(`div`,{className:`text-xs text-red-400`,children:[t.error_type&&(0,H.jsx)(`span`,{className:`font-semibold`,children:t.error_type}),t.error_message&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`— `,t.error_message]})]})]})]})}function MO({node:e}){let t=B(e=>e.engageDialog),n=B(e=>e.sendDialogDecline),r=B(e=>e.wsStatus),i=e.dialog_id||``,a=e.dialog_messages||[],o=r===`connected`,s=a.find(e=>e.role===`agent`);return(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-fuchsia-500/10 border border-fuchsia-500/30`,children:[(0,H.jsxs)(`span`,{className:`relative flex h-2.5 w-2.5 flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`animate-ping absolute inline-flex h-full w-full rounded-full bg-fuchsia-400 opacity-75`}),(0,H.jsx)(`span`,{className:`relative inline-flex rounded-full h-2.5 w-2.5 bg-fuchsia-500`})]}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-fuchsia-400 tracking-wide`,children:`Dialog Requested`})]}),s&&(0,H.jsxs)(`div`,{className:`rounded-lg px-3 py-2 bg-amber-500/10 border border-amber-500/30`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold mb-1 text-[var(--text-muted)]`,children:e.name}),(0,H.jsx)(`div`,{className:`dialog-markdown text-xs leading-relaxed text-[var(--text)]`,children:(0,H.jsx)(mT,{remarkPlugins:[vO],children:s.content})})]}),(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`div`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`How would you like to proceed?`}),(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsxs)(`button`,{onClick:t,disabled:!o,className:`flex-1 flex items-center justify-center gap-1.5 text-xs px-3 py-2 rounded-lg border border-fuchsia-500/40 bg-fuchsia-500/10 text-fuchsia-300 hover:bg-fuchsia-500/20 transition-colors font-medium disabled:opacity-40 disabled:cursor-not-allowed`,children:[(0,H.jsx)(he,{className:`w-3 h-3`}),`💬 Discuss`]}),(0,H.jsxs)(`button`,{onClick:()=>{o&&n(e.name,i)},disabled:!o,className:`flex-1 flex items-center justify-center gap-1.5 text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] text-[var(--text-muted)] hover:bg-[var(--surface-hover)] transition-colors font-medium disabled:opacity-40 disabled:cursor-not-allowed`,children:[(0,H.jsx)(Me,{className:`w-3 h-3`}),`✕ Skip & continue`]})]})]})]})}function NO({node:e}){let t=e.status,n=X[t]||X.pending,r=B(e=>e.navigateToContext),i=B(e=>e.viewContextPath),a=Gh().map((e,t)=>({ctx:e,index:t})).filter(({ctx:t})=>t.parentAgent===e.name),o=new Map;for(let{ctx:e}of a)o.set(e.slotKey,(o.get(e.slotKey)??0)+1);let s=[];return e.elapsed!=null&&s.push({label:`Elapsed`,value:W(e.elapsed)}),e.cost_usd!=null&&s.push({label:`Cost`,value:vt(e.cost_usd)}),e.tokens!=null&&s.push({label:`Tokens`,value:_t(e.tokens)}),e.iteration!=null&&e.iteration>1&&s.push({label:`Iteration`,value:e.iteration}),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Subworkflow Agent`})]}),(0,H.jsx)(Sv,{items:s}),a.length>0&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:[`Subworkflow Runs (`,a.length,`)`]}),(0,H.jsx)(`div`,{className:`space-y-1`,children:a.map(({ctx:e,index:t})=>(0,H.jsx)(PO,{ctx:e,showIteration:(o.get(e.slotKey)??0)>1,onClick:()=>r([...i,t])},`${e.slotKey}-${e.iteration}-${t}`))})]}),t===`failed`&&(e.error_type||e.error_message)&&(0,H.jsxs)(`div`,{className:`text-xs text-red-400`,children:[e.error_type&&(0,H.jsx)(`span`,{className:`font-semibold`,children:e.error_type}),e.error_message&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`— `,e.error_message]})]}),a.length===0&&t===`pending`&&(0,H.jsx)(`div`,{className:`text-xs text-[var(--text-muted)] italic`,children:`Subworkflow has not started yet.`})]})}function PO({ctx:e,showIteration:t,onClick:n}){let r=X[e.status]||X.pending;return(0,H.jsxs)(`button`,{onClick:n,className:`flex items-center gap-2 w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] hover:bg-[var(--node-bg)] transition-colors text-left`,children:[(0,H.jsx)(de,{className:`w-3.5 h-3.5 flex-shrink-0`,style:{color:r}}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsxs)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:[e.workflowName||e.workflowFile||`Subworkflow`,t&&(0,H.jsxs)(`span`,{className:`ml-1.5 text-[var(--text-muted)] font-normal`,children:[`· Iteration `,e.iteration]})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-[var(--text-muted)]`,children:[e.agentsTotal>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,H.jsx)(ue,{className:`w-2.5 h-2.5`}),e.agentsCompleted,`/`,e.agentsTotal,` agents`]}),e.totalCost>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,H.jsx)(ie,{className:`w-2.5 h-2.5`}),vt(e.totalCost)]})]})]}),(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider flex-shrink-0 px-1.5 py-0.5 rounded`,style:{backgroundColor:`${r}20`,color:r},children:e.status}),(0,H.jsx)(N,{className:`w-3.5 h-3.5 flex-shrink-0 text-[var(--text-muted)]`})]})}function FO({node:e}){let t=e.status,n=X[t]||X.pending,r=[],i=e.requested_seconds??e.duration_seconds;return i!=null&&r.push({label:`Requested`,value:W(i)}),e.waited_seconds==null?e.elapsed!=null&&r.push({label:`Elapsed`,value:W(e.elapsed)}):r.push({label:`Waited`,value:W(e.waited_seconds)}),e.interrupted&&r.push({label:`Interrupted`,value:`yes`}),e.reason&&r.push({label:`Reason`,value:e.reason}),e.error_type&&r.push({label:`Error`,value:e.error_type}),e.error_message&&r.push({label:`Message`,value:e.error_message}),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Wait`})]}),(0,H.jsx)(Sv,{items:r})]})}function IO(){let e=B(e=>e.selectedNode),t=Uh(),n=B(e=>e.selectNode),r=B(e=>e.dialogEngaged),[i,a]=(0,v.useState)(!1);(0,v.useEffect)(()=>(requestAnimationFrame(()=>a(!0)),()=>a(!1)),[e]);let o=e?t??null:null;if(!e||!o)return(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-[var(--surface)]`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between px-4 py-3 border-b border-[var(--border)]`,children:(0,H.jsx)(`h2`,{className:`text-sm font-semibold text-[var(--text)]`,children:`Detail`})}),(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Click a node to view details`})})]});let s=(()=>{if(o.dialog_active&&!r)return MO;if(o.dialog_active&&r)return Av;switch(o.type){case`script`:return Nv;case`wait`:return FO;case`set`:return Pv;case`mcp`:return Fv;case`human_gate`:return CO;case`questions`:return DO;case`parallel_group`:case`for_each_group`:return kO;case`workflow`:return NO;default:return Av}})();return(0,H.jsxs)(`div`,{className:U(`h-full flex flex-col bg-[var(--surface)] transition-all duration-150 ease-out`,i?`translate-x-0 opacity-100`:`translate-x-4 opacity-0`),children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-3 border-b border-[var(--border)] flex-shrink-0`,children:[(0,H.jsx)(`h2`,{className:`text-sm font-semibold text-[var(--text)] truncate`,children:e?Lh(e).name:``}),(0,H.jsx)(`button`,{onClick:()=>n(null),className:`p-1 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,title:`Close panel`,children:(0,H.jsx)(Me,{className:`w-4 h-4`})})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3`,children:(0,H.jsx)(s,{node:o})})]})}function LO(e){if(e==null)return``;if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function RO(){let e=B(e=>e.eventLog),t=B(e=>e.activityLog),n=B(e=>e.workflowOutput),r=B(e=>e.workflowStatus),[i,a]=(0,v.useState)(`log`),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0),[u,d]=(0,v.useState)(0),f=(0,v.useCallback)(n=>{a(n),n===`log`&&l(e.length),n===`activity`&&d(t.length)},[e.length,t.length]);(0,v.useEffect)(()=>{i===`log`&&l(e.length)},[i,e.length]),(0,v.useEffect)(()=>{i===`activity`&&d(t.length)},[i,t.length]),(0,v.useEffect)(()=>{r===`completed`&&n!=null&&a(`output`)},[r,n]);let p=n!=null,m=i===`log`?0:Math.max(0,e.length-c),h=i===`activity`?0:Math.max(0,t.length-u);return o?(0,H.jsx)(`div`,{className:`flex items-center bg-[var(--surface)] border-t border-[var(--border)] px-3 py-1`,children:(0,H.jsxs)(`button`,{onClick:()=>s(!1),className:`flex items-center gap-1.5 text-xs text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,children:[(0,H.jsx)(ee,{className:`w-3 h-3`}),(0,H.jsx)(Te,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Output`}),t.length>0&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)]`,children:[`(`,t.length,`)`]})]})}):(0,H.jsxs)(`div`,{className:`flex flex-col h-full bg-[var(--surface)] border-t border-[var(--border)]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-2 flex-shrink-0 border-b border-[var(--border)]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,H.jsx)(zO,{active:i===`log`,onClick:()=>f(`log`),icon:(0,H.jsx)(Te,{className:`w-3 h-3`}),label:`Log`,count:e.length,unread:m}),(0,H.jsx)(zO,{active:i===`activity`,onClick:()=>f(`activity`),icon:(0,H.jsx)(T,{className:`w-3 h-3`}),label:`Activity`,count:t.length,unread:h}),(0,H.jsx)(zO,{active:i===`output`,onClick:()=>f(`output`),icon:(0,H.jsx)(se,{className:`w-3 h-3`}),label:`Output`,badge:p?r===`failed`?`error`:`success`:void 0})]}),(0,H.jsx)(`button`,{onClick:()=>s(!0),className:`p-1 rounded text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--surface-hover)] transition-colors`,title:`Collapse panel`,children:(0,H.jsx)(M,{className:`w-3.5 h-3.5`})})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:i===`activity`?(0,H.jsx)(VO,{entries:t}):i===`log`?(0,H.jsx)(UO,{entries:e}):(0,H.jsx)(GO,{output:n,status:r})})]})}function zO({active:e,onClick:t,icon:n,label:r,count:i,badge:a,unread:o}){return(0,H.jsxs)(`button`,{onClick:t,className:U(`relative flex items-center gap-1.5 px-3 py-1.5 text-xs transition-colors border-b-2 -mb-px`,e?`text-[var(--text)] border-[var(--accent)]`:`text-[var(--text-muted)] border-transparent hover:text-[var(--text-secondary)]`),children:[n,(0,H.jsx)(`span`,{children:r}),i!=null&&i>0&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] tabular-nums`,children:i}),a&&(0,H.jsx)(`span`,{className:U(`w-1.5 h-1.5 rounded-full`,a===`success`?`bg-[var(--completed)]`:`bg-[var(--failed)]`)}),!e&&o!=null&&o>0&&(0,H.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 flex h-3.5 min-w-[14px] items-center justify-center rounded-full bg-[var(--accent)] px-1`,children:(0,H.jsx)(`span`,{className:`text-[8px] font-bold text-white leading-none tabular-nums`,children:o>99?`99+`:o})})]})}var BO={reasoning:{color:`text-indigo-400/70`,label:`THINK`,labelColor:`text-indigo-500`},"tool-start":{color:`text-blue-400`,label:`TOOL →`,labelColor:`text-blue-500`},"tool-complete":{color:`text-green-400`,label:`TOOL ←`,labelColor:`text-green-600`},turn:{color:`text-amber-400`,label:`STEP`,labelColor:`text-amber-500`},message:{color:`text-[var(--text)]`,label:`MSG`,labelColor:`text-[var(--text-muted)]`},prompt:{color:`text-cyan-400/70`,label:`PROMPT`,labelColor:`text-cyan-600`},"parse-recovery":{color:`text-yellow-400`,label:`RETRY`,labelColor:`text-yellow-600`},"compaction-config":{color:`text-[var(--text-muted)]`,label:`COMPACT`,labelColor:`text-[var(--text-muted)]`},"compaction-start":{color:`text-[var(--text-muted)]`,label:`COMPACT`,labelColor:`text-[var(--text-muted)]`},"compaction-complete":{color:`text-[var(--text-muted)]`,label:`COMPACT`,labelColor:`text-[var(--text-muted)]`},"compaction-error":{color:`text-yellow-400`,label:`COMPACT`,labelColor:`text-yellow-600`}};function VO({entries:e}){let t=(0,v.useRef)(null),n=(0,v.useRef)(!0),r=B(e=>e.selectNode),[i,a]=(0,v.useState)(``),o=(0,v.useCallback)(()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<30)},[]),s=(0,v.useMemo)(()=>{if(!i)return e;let t=i.toLowerCase();return e.filter(e=>e.source.toLowerCase().includes(t)||LO(e.message).toLowerCase().includes(t))},[e,i]);return(0,v.useEffect)(()=>{t.current&&n.current&&(t.current.scrollTop=t.current.scrollHeight)},[s.length]),e.length===0?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Waiting for agent activity…`})}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-1.5 border-b border-[var(--border-subtle)] flex-shrink-0`,children:[(0,H.jsx)(xe,{className:`w-3 h-3 text-[var(--text-muted)] flex-shrink-0`}),(0,H.jsx)(`input`,{type:`text`,value:i,onChange:e=>a(e.target.value),placeholder:`Filter by agent or message…`,className:`flex-1 bg-transparent text-[11px] text-[var(--text)] placeholder:text-[var(--text-muted)] outline-none min-w-0`}),i&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] tabular-nums flex-shrink-0`,children:[s.length,` of `,e.length]}),(0,H.jsx)(`button`,{onClick:()=>a(``),className:`text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Clear filter`,children:(0,H.jsx)(Me,{className:`w-3 h-3`})})]})]}),(0,H.jsxs)(`div`,{ref:t,onScroll:o,className:`flex-1 overflow-y-auto font-mono text-[11px] leading-[1.6] px-3 py-2`,children:[s.map((e,t)=>{let n=BO[e.type]||BO.message;return(0,H.jsxs)(`div`,{className:`group`,children:[(0,H.jsxs)(`div`,{className:`flex gap-1.5 hover:bg-[var(--surface-hover)] rounded px-1 -mx-1`,children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] flex-shrink-0 select-none tabular-nums`,children:WO(e.timestamp)}),(0,H.jsx)(`span`,{className:U(`flex-shrink-0 w-[5ch] text-[10px] font-semibold tabular-nums select-none`,n.labelColor),children:n.label}),(0,H.jsx)(`button`,{onClick:()=>r(Ih([],e.source)),className:`text-[var(--text-secondary)] flex-shrink-0 min-w-[8ch] max-w-[16ch] truncate hover:text-[var(--accent)] hover:underline transition-colors text-left`,title:`Select ${e.source}`,children:e.source}),(0,H.jsx)(`span`,{className:U(`break-words min-w-0`,n.color,e.type===`reasoning`&&`italic`),children:LO(e.message)})]}),e.detail&&(0,H.jsx)(`div`,{className:`ml-[calc(7ch+5ch+8ch+1rem)] px-2 py-1 my-0.5 bg-[var(--bg)] rounded text-[10px] text-[var(--text-muted)] whitespace-pre-wrap break-words max-h-24 overflow-y-auto border-l-2 border-[var(--border)]`,children:LO(e.detail)})]},t)}),i&&s.length===0&&(0,H.jsx)(`div`,{className:`flex items-center justify-center py-4`,children:(0,H.jsxs)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:[`No matches for "`,i,`"`]})})]})]})}var HO={info:{color:`text-blue-400`,icon:`›`},success:{color:`text-green-400`,icon:`✓`},error:{color:`text-red-400`,icon:`✗`},warning:{color:`text-amber-400`,icon:`⚠`},debug:{color:`text-[var(--text-muted)]`,icon:`·`}};function UO({entries:e}){let t=(0,v.useRef)(null),n=(0,v.useRef)(!0),r=B(e=>e.selectNode),i=(0,v.useCallback)(()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<30)},[]);return(0,v.useEffect)(()=>{t.current&&n.current&&(t.current.scrollTop=t.current.scrollHeight)},[e.length]),e.length===0?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Waiting for events…`})}):(0,H.jsx)(`div`,{ref:t,onScroll:i,className:`h-full overflow-y-auto font-mono text-[11px] leading-[1.6] px-3 py-2`,children:e.map((e,t)=>{let n=HO[e.level]||HO.info;return(0,H.jsxs)(`div`,{className:`flex gap-2 hover:bg-[var(--surface-hover)] rounded px-1 -mx-1`,children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] flex-shrink-0 select-none tabular-nums`,children:WO(e.timestamp)}),(0,H.jsx)(`span`,{className:U(`flex-shrink-0 w-3 text-center select-none`,n.color),children:n.icon}),(0,H.jsx)(`button`,{onClick:()=>r(Ih([],e.source)),className:`text-[var(--text-secondary)] flex-shrink-0 min-w-[8ch] max-w-[16ch] truncate hover:text-[var(--accent)] hover:underline transition-colors text-left`,title:`Select ${e.source}`,children:e.source}),(0,H.jsx)(`span`,{className:U(`break-words`,e.level===`error`?`text-red-400`:e.level===`success`?`text-green-400`:`text-[var(--text)]`),children:LO(e.message)})]},t)})})}function WO(e){let t=new Date(e*1e3);return`${t.getHours().toString().padStart(2,`0`)}:${t.getMinutes().toString().padStart(2,`0`)}:${t.getSeconds().toString().padStart(2,`0`)}`}function GO({output:e,status:t}){let[n,r]=(0,v.useState)(!1),i=yt(e);return e==null?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:t===`running`?`Workflow running — output will appear when complete…`:t===`failed`?`Workflow failed — no output produced`:`No output yet`})}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-1 border-b border-[var(--border-subtle)] flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] uppercase tracking-wider font-semibold`,children:`Workflow Result`}),(0,H.jsx)(`button`,{onClick:async()=>{i&&(await navigator.clipboard.writeText(i),r(!0),setTimeout(()=>r(!1),2e3))},className:`flex items-center gap-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors px-1.5 py-0.5 rounded hover:bg-[var(--surface-hover)]`,title:`Copy to clipboard`,children:n?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(j,{className:`w-3 h-3 text-[var(--completed)]`}),(0,H.jsx)(`span`,{className:`text-[var(--completed)]`,children:`Copied`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(ae,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Copy`})]})})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-auto px-3 py-2`,children:(0,H.jsx)(`pre`,{className:`font-mono text-[11px] leading-relaxed text-[var(--text)] whitespace-pre-wrap break-words`,children:typeof e==`object`?(0,H.jsx)(KO,{text:i}):i})})]})}function KO({text:e}){let t=e.split(/("(?:[^"\\]|\\.)*")/g);return(0,H.jsx)(H.Fragment,{children:t.map((e,n)=>{if(n%2==1){let r=t.slice(n+1).join(``);return(0,H.jsx)(`span`,{className:/^\s*:/.test(r)?`text-blue-400`:`text-green-400`,children:e},n)}return(0,H.jsx)(`span`,{dangerouslySetInnerHTML:{__html:e.replace(/\b(true|false|null)\b|(-?\d+\.?\d*(?:e[+-]?\d+)?)/gi,(e,t,n)=>t?`${e}`:n?`${e}`:e)}},n)})})}function qO({text:e}){return(0,H.jsx)(`div`,{className:`dialog-markdown text-xs leading-relaxed text-[var(--text)]`,children:(0,H.jsx)(mT,{remarkPlugins:[vO],components:{h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-sm font-bold mb-2 mt-1`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-xs font-bold mb-1.5 mt-1`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xs font-semibold mb-1 mt-1`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`mb-1.5 last:mb-0`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside mb-1.5 space-y-0.5`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside mb-1.5 space-y-0.5`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{children:e}),code:({children:e,className:t})=>t?.includes(`language-`)?(0,H.jsx)(`code`,{className:`block bg-[var(--bg)] border border-[var(--border)] rounded px-2 py-1.5 font-mono text-[11px] my-1 overflow-x-auto whitespace-pre`,children:e}):(0,H.jsx)(`code`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded px-1 py-0.5 font-mono text-[11px]`,children:e}),pre:({children:e})=>(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md px-2.5 py-2 font-mono text-[11px] my-1.5 overflow-x-auto`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic`,children:e}),a:({href:e,children:t})=>(0,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-400 hover:text-blue-300 underline underline-offset-2`,children:t}),blockquote:({children:e})=>(0,H.jsx)(`blockquote`,{className:`border-l-2 border-[var(--border)] pl-2.5 my-1.5 opacity-80`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`border-[var(--border)] my-2`}),table:({children:e})=>(0,H.jsx)(`div`,{className:`overflow-x-auto my-2`,children:(0,H.jsx)(`table`,{className:`text-[11px] border-collapse w-full`,children:e})}),th:({children:e})=>(0,H.jsx)(`th`,{className:`border border-[var(--border)] px-2 py-1 text-left bg-[var(--bg)] font-semibold`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`border border-[var(--border)] px-2 py-1`,children:e})},children:e})})}function JO({node:e}){let t=B(e=>e.sendDialogMessage),n=B(e=>e.wsStatus),[r,i]=(0,v.useState)(``),a=(0,v.useRef)(null),o=e.dialog_active===!0,s=e.dialog_id||``,c=e.dialog_messages||[],l=o&&n===`connected`;(0,v.useEffect)(()=>{a.current?.scrollIntoView({behavior:`smooth`})},[c.length,e.dialog_awaiting_response]);let u=()=>{!r.trim()||!l||(t(e.name,s,r.trim()),i(``))};return(0,H.jsxs)(`div`,{className:`flex flex-col h-full`,children:[o?(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-fuchsia-500/10 border border-fuchsia-500/30 mb-3 flex-shrink-0`,children:[(0,H.jsxs)(`span`,{className:`relative flex h-2.5 w-2.5 flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`animate-ping absolute inline-flex h-full w-full rounded-full bg-fuchsia-400 opacity-75`}),(0,H.jsx)(`span`,{className:`relative inline-flex rounded-full h-2.5 w-2.5 bg-fuchsia-500`})]}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-fuchsia-400 tracking-wide`,children:`Dialog Mode`}),(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[c.length,` message`,c.length===1?``:`s`]})]}):(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-[var(--surface)] border border-[var(--border)] mb-3 flex-shrink-0`,children:[(0,H.jsx)(he,{className:`w-3.5 h-3.5 text-[var(--text-muted)]`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text-muted)] tracking-wide`,children:`Dialog Completed`}),(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[c.length,` message`,c.length===1?``:`s`]})]}),(0,H.jsxs)(`div`,{className:`flex-1 overflow-y-auto space-y-3 min-h-0 mb-3`,children:[c.map((t,n)=>(0,H.jsx)(`div`,{className:`flex ${t.role===`user`?`justify-end`:`justify-start`}`,children:(0,H.jsxs)(`div`,{className:`max-w-[85%] rounded-lg px-3 py-2 ${t.role===`agent`?`bg-amber-500/10 border border-amber-500/30`:`bg-blue-500/10 border border-blue-500/30`}`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold mb-1 text-[var(--text-muted)]`,children:t.role===`agent`?e.name:`You`}),(0,H.jsx)(qO,{text:t.content})]})},n)),e.dialog_awaiting_response&&(0,H.jsx)(`div`,{className:`flex justify-start`,children:(0,H.jsxs)(`div`,{className:`max-w-[85%] rounded-lg px-3 py-2 bg-amber-500/10 border border-amber-500/30`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold mb-1 text-[var(--text-muted)]`,children:e.name}),(0,H.jsxs)(`div`,{className:`flex gap-1 items-center h-4`,children:[(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-amber-400/60 animate-bounce [animation-delay:0ms]`}),(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-amber-400/60 animate-bounce [animation-delay:150ms]`}),(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-amber-400/60 animate-bounce [animation-delay:300ms]`})]})]})}),(0,H.jsx)(`div`,{ref:a})]}),o&&(0,H.jsxs)(`div`,{className:`flex-shrink-0 border-t border-[var(--border)] pt-3`,children:[(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),u())},placeholder:`Type your message...`,className:`flex-1 text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-fuchsia-400 transition-colors`,disabled:!l,autoFocus:!0}),(0,H.jsxs)(`button`,{onClick:u,disabled:!l||!r.trim(),className:`flex items-center justify-center gap-1.5 text-xs px-8 py-2 rounded-lg bg-fuchsia-500 text-white hover:bg-fuchsia-600 transition-colors font-medium disabled:opacity-40 disabled:cursor-not-allowed`,children:[(0,H.jsx)(Se,{className:`w-3 h-3`}),`Send`]})]}),(0,H.jsx)(`p`,{className:`text-[10px] text-[var(--text-muted)] mt-1.5 px-1`,children:`Press Enter to send · Type "done" to end dialog`})]})]})}function YO(){let e=B(e=>e.activeDialog),t=B(e=>e.nodes);if(!e)return null;let n=t[e.agentName];return n?(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-[var(--bg)] overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-5 py-3 border-b border-[var(--border)] bg-[var(--surface)] flex-shrink-0`,children:[(0,H.jsx)(he,{className:`w-4 h-4 text-fuchsia-400`}),(0,H.jsxs)(`h2`,{className:`text-sm font-semibold text-[var(--text)]`,children:[`Dialog with `,e.agentName]})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-hidden px-5 py-4`,children:(0,H.jsx)(JO,{node:n})})]}):null}function XO(){let e=B(e=>e.selectedNode),t=B(e=>e.activeDialog),n=B(e=>e.dialogEngaged);return(0,H.jsxs)(cr,{direction:`vertical`,className:`flex-1 overflow-hidden`,children:[(0,H.jsx)(Ft,{defaultSize:70,minSize:30,children:(0,H.jsxs)(cr,{direction:`horizontal`,className:`h-full`,children:[(0,H.jsx)(Ft,{defaultSize:e?65:100,minSize:40,children:t&&n?(0,H.jsx)(YO,{}):(0,H.jsx)(hv,{})}),e&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(fr,{className:`w-[3px] bg-[var(--border)] hover:bg-[var(--text-muted)] transition-colors cursor-col-resize`}),(0,H.jsx)(Ft,{defaultSize:35,minSize:20,maxSize:60,children:(0,H.jsx)(IO,{})})]})]})}),(0,H.jsx)(fr,{className:`h-[3px] bg-[var(--border)] hover:bg-[var(--text-muted)] transition-colors cursor-row-resize`}),(0,H.jsx)(Ft,{defaultSize:30,minSize:5,maxSize:70,collapsible:!0,children:(0,H.jsx)(RO,{})})]})}var ZO=10;function QO(){let e=B(e=>e.iterationLimitGate),t=B(e=>e.wsStatus),n=B(e=>e.sendIterationLimitResponse),[r,i]=(0,v.useState)(String(ZO)),[a,o]=(0,v.useState)(!1);(0,v.useEffect)(()=>{e?.gate_id&&(i(String(ZO)),o(!1))},[e?.gate_id]);let s=(0,v.useMemo)(()=>{let e=Number(r);return!Number.isFinite(e)||e<0?null:Math.floor(e)},[r]);if(!e||e.skip_gates)return null;let c=e.agent_name??e.group_name??`workflow`,l=t===`connected`&&!a,u=!l||s==null||s<=0,d=()=>e.agent_name===void 0?{group_name:e.group_name}:{agent_name:e.agent_name},f=()=>{u||s==null||(o(!0),n(d(),e.gate_id,s))};return(0,H.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`iteration-limit-title`,"data-testid":`iteration-limit-modal`,className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`relative flex flex-col w-[90vw] max-w-md rounded-xl border border-amber-500/40 bg-[var(--surface)] shadow-2xl overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-4 py-3 border-b border-[var(--border)] bg-amber-500/10`,children:[(0,H.jsx)(Oe,{className:`w-4 h-4 text-amber-400 flex-shrink-0`}),(0,H.jsx)(`h2`,{id:`iteration-limit-title`,className:`text-sm font-semibold text-[var(--text)]`,children:`Max iterations reached`})]}),(0,H.jsxs)(`div`,{className:`px-4 py-4 space-y-3`,children:[(0,H.jsxs)(`p`,{className:`text-xs text-[var(--text)]`,children:[(0,H.jsx)(`span`,{className:`font-semibold`,children:c}),` reached`,` `,(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[e.current_iteration,`/`,e.max_iterations]}),` `,`iterations.`]}),e.possible_loop&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/5 border border-amber-500/30`,children:[(0,H.jsx)(Oe,{className:`w-3.5 h-3.5 text-amber-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-[11px] text-amber-300`,children:`The same agent has run repeatedly — this may indicate a loop.`})]}),e.agent_history.length>0&&(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`h3`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Recent agents`}),(0,H.jsx)(`ol`,{className:`text-[11px] text-[var(--text-muted)] list-decimal list-inside space-y-0.5`,children:e.agent_history.map((e,t)=>(0,H.jsx)(`li`,{children:e},`${t}-${e}`))})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`iteration-limit-additional`,className:`block text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Additional iterations`}),(0,H.jsx)(`input`,{id:`iteration-limit-additional`,"data-testid":`iteration-limit-input`,type:`number`,min:0,step:1,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),f())},disabled:!l,autoFocus:!0,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-amber-400 transition-colors disabled:opacity-50`}),(0,H.jsx)(`p`,{className:`text-[10px] text-[var(--text-muted)]`,children:`Enter a positive number to continue, or press Stop to end the workflow.`})]}),t!==`connected`&&(0,H.jsx)(`div`,{className:`text-[11px] text-red-300`,children:`Disconnected from server — reconnect to resolve this gate.`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-2 px-4 py-3 border-t border-[var(--border)] bg-[var(--surface-raised)]`,children:[(0,H.jsxs)(`button`,{type:`button`,"data-testid":`iteration-limit-stop`,onClick:()=>{l&&(o(!0),n(d(),e.gate_id,0))},disabled:!l,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg border border-[var(--border)] text-[var(--text)] hover:bg-[var(--surface-hover)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,children:[(0,H.jsx)(ne,{className:`w-3.5 h-3.5`}),`Stop`]}),(0,H.jsxs)(`button`,{type:`button`,"data-testid":`iteration-limit-continue`,onClick:f,disabled:u,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg bg-amber-500 text-white hover:bg-amber-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium`,children:[(0,H.jsx)(ye,{className:`w-3.5 h-3.5`}),`Continue`]})]})]})})}var $O=3e4;function ek(){let e=B(e=>e.processEvent),t=B(e=>e.replayState),n=B(e=>e.setWsStatus),r=B(e=>e.setWsSend),i=B(e=>e.setWsAuthFailed),a=(0,v.useRef)(null),o=(0,v.useRef)(1e3),s=(0,v.useRef)(null),c=(0,v.useRef)(null),l=(0,v.useRef)(()=>{}),u=(0,v.useCallback)(()=>{n(`reconnecting`),s.current=setTimeout(()=>{o.current=Math.min(o.current*2,$O),l.current()},o.current)},[n]),d=(0,v.useCallback)(()=>{n(`connecting`),c.current&&c.current.abort();let s=new AbortController;c.current=s,fetch(`/api/state`,{signal:s.signal}).then(e=>{if(!e.ok)throw Error(`GET /api/state -> ${e.status}`);return e.json()}).then(s=>{s&&s.length>0&&t(s);let c=Ue(`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}/ws`);try{let t=new WebSocket(c);a.current=t;let s=!1;t.onopen=()=>{s=!0,o.current=1e3,n(`connected`),i(!1),r(e=>{t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))})},t.onmessage=t=>{try{e(JSON.parse(t.data))}catch(e){console.error(`Failed to parse WebSocket message:`,e)}},t.onclose=()=>{n(`disconnected`),r(null),a.current=null,s||(i(!0),o.current=$O),u()},t.onerror=()=>{}}catch{u()}}).catch(e=>{s.signal.aborted||(console.error(`Failed to fetch state:`,e),u())})},[e,t,n,r,i,u]);l.current=d,(0,v.useEffect)(()=>(d(),()=>{c.current&&c.current.abort(),s.current&&clearTimeout(s.current),a.current&&a.current.close(),r(null)}),[d,r])}function tk(){let e=B(e=>e.setReplayMode),t=B(e=>e.markReplayMode),n=B(e=>e.setWsStatus),r=B(e=>e.replayPlaying),i=B(e=>e.replayPosition),a=B(e=>e.replayTotalEvents),o=B(e=>e.replaySpeed),s=B(e=>e.replayEvents),c=B(e=>e.setReplayPosition);(0,v.useEffect)(()=>{t(),n(`connecting`),fetch(`/api/state`).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status} from /api/state`);return e.json()}).then(t=>{e(t),n(`connected`)}).catch(e=>{console.error(`Failed to load replay events:`,e),n(`disconnected`)})},[e,t,n]);let l=(0,v.useRef)(null);(0,v.useEffect)(()=>{if(!r||i>=a){l.current&&clearTimeout(l.current),r&&i>=a&&B.getState().setReplayPlaying(!1);return}let e=s[i-1],t=s[i],n=100;if(e&&t){let r=(t.timestamp-e.timestamp)*1e3;n=Math.max(16,Math.min(r/o,2e3))}return l.current=setTimeout(()=>{c(i+1)},n),()=>{l.current&&clearTimeout(l.current)}},[r,i,a,o,s,c])}function nk(){return ek(),null}function rk(){return tk(),null}function ik(){let[e,t]=(0,v.useState)(null),n=B(e=>e.replayMode),r=B(e=>e.selectNode),i=B(e=>e.workflowName);return(0,v.useEffect)(()=>{fetch(`/api/replay/info`).then(e=>{e.ok?t(!0):t(!1)}).catch(()=>t(!1))},[]),(0,v.useEffect)(()=>{document.title=i?`Conductor — ${i}`:`Conductor Dashboard`},[i]),(0,v.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r(null)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]),e===null?null:(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-[var(--bg)]`,children:[e?(0,H.jsx)(rk,{}):(0,H.jsx)(nk,{}),(0,H.jsx)(ht,{}),(0,H.jsx)(gt,{}),(0,H.jsx)(XO,{}),n?(0,H.jsx)(Tt,{}):(0,H.jsx)(St,{}),!n&&(0,H.jsx)(QO,{})]})}(0,y.createRoot)(document.getElementById(`root`)).render((0,H.jsx)(v.StrictMode,{children:(0,H.jsx)(ik,{})})); \ No newline at end of file diff --git a/src/conductor/web/static/assets/index-DDhFijLw.js b/src/conductor/web/static/assets/index-DDhFijLw.js deleted file mode 100644 index 09118e7c..00000000 --- a/src/conductor/web/static/assets/index-DDhFijLw.js +++ /dev/null @@ -1,91 +0,0 @@ -var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var u=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=u()})),f=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),p=o(((e,t)=>{t.exports=f()})),m=o((e=>{var t=d();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=m()})),g=o((e=>{var t=p(),n=d(),r=h();function i(e){var t=`https://react.dev/errors/`+e;if(1re||(e.current=ne[re],ne[re]=null,re--)}function ae(e,t){re++,ne[re]=e.current,e.current=t}var oe=ie(null),se=ie(null),ce=ie(null),le=ie(null);function ue(e,t){switch(ae(ce,t),ae(se,e),ae(oe,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Gd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Gd(t),e=Kd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}L(oe),ae(oe,e)}function de(){L(oe),L(se),L(ce)}function fe(e){e.memoizedState!==null&&ae(le,e);var t=oe.current,n=Kd(t,e.type);t!==n&&(ae(se,e),ae(oe,n))}function pe(e){se.current===e&&(L(oe),L(se)),le.current===e&&(L(le),np._currentValue=te)}var me,he;function ge(e){if(me===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);me=t&&t[1]||``,he=-1)`:-1i||c[r]!==l[i]){var u=` -`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{_e=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?ge(n):``}function ye(e,t){switch(e.tag){case 26:case 27:case 5:return ge(e.type);case 16:return ge(`Lazy`);case 13:return e.child!==t&&t!==null?ge(`Suspense Fallback`):ge(`Suspense`);case 19:return ge(`SuspenseList`);case 0:case 15:return ve(e.type,!1);case 11:return ve(e.type.render,!1);case 1:return ve(e.type,!0);case 31:return ge(`Activity`);default:return``}}function be(e){try{var t=``,n=null;do t+=ye(e,n),n=e,e=e.return;while(e);return t}catch(e){return` -Error generating stack: `+e.message+` -`+e.stack}}var xe=Object.prototype.hasOwnProperty,Se=t.unstable_scheduleCallback,Ce=t.unstable_cancelCallback,we=t.unstable_shouldYield,Te=t.unstable_requestPaint,Ee=t.unstable_now,De=t.unstable_getCurrentPriorityLevel,Oe=t.unstable_ImmediatePriority,ke=t.unstable_UserBlockingPriority,Ae=t.unstable_NormalPriority,je=t.unstable_LowPriority,Me=t.unstable_IdlePriority,Ne=t.log,Pe=t.unstable_setDisableYieldValue,Fe=null,Ie=null;function Le(e){if(typeof Ne==`function`&&Pe(e),Ie&&typeof Ie.setStrictMode==`function`)try{Ie.setStrictMode(Fe,e)}catch{}}var Re=Math.clz32?Math.clz32:Ve,ze=Math.log,Be=Math.LN2;function Ve(e){return e>>>=0,e===0?32:31-(ze(e)/Be|0)|0}var He=256,R=262144,Ue=4194304;function z(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function We(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=z(n))):i=z(o):i=z(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=z(n))):i=z(o)):i=z(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Ge(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ke(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function qe(){var e=Ue;return Ue<<=1,!(Ue&62914560)&&(Ue=4194304),e}function Je(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ye(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Xe(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),an=!1;if(rn)try{var on={};Object.defineProperty(on,"passive",{get:function(){an=!0}}),window.addEventListener(`test`,on,on),window.removeEventListener(`test`,on,on)}catch{an=!1}var sn=null,cn=null,ln=null;function un(){if(ln)return ln;var e,t=cn,n=t.length,r,i=`value`in sn?sn.value:sn.textContent,a=i.length;for(e=0;e=Vn),Wn=` `,Gn=!1;function Kn(e,t){switch(e){case`keyup`:return zn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function qn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Jn=!1;function Yn(e,t){switch(e){case`compositionend`:return qn(t);case`keypress`:return t.which===32?(Gn=!0,Wn):null;case`textInput`:return e=t.data,e===Wn&&Gn?null:e;default:return null}}function Xn(e,t){if(Jn)return e===`compositionend`||!Bn&&Kn(e,t)?(e=un(),ln=cn=sn=null,Jn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=vr(n)}}function br(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?br(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=jt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=jt(e.document)}return t}function Sr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Cr=rn&&`documentMode`in document&&11>=document.documentMode,wr=null,Tr=null,Er=null,Dr=!1;function Or(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Dr||wr==null||wr!==jt(r)||(r=wr,`selectionStart`in r&&Sr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Er&&_r(Er,r)||(Er=r,r=kd(Tr,`onSelect`),0>=o,i-=o,bi=1<<32-Re(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),G&&Si(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),G&&Si(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return G&&Si(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),G&&Si(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&Sa(l)===r.type){n(e,r.sibling),c=a(r,o.props),ka(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===y?(c=si(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=oi(o.type,o.key,o.props,null,e.mode,c),ka(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=ui(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=Sa(o),b(e,r,o,c)}if(ee(o))return h(e,r,o,c);if(M(o)){if(l=M(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Oa(o),c);if(o.$$typeof===C)return b(e,r,Xi(e,o),c);Aa(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=ci(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Da=0;var i=b(e,t,n,r);return Ea=null,i}catch(t){if(t===ga||t===va)throw t;var a=ni(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ma=ja(!0),Na=ja(!1),Pa=!1;function Fa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ia(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function La(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ra(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ll&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=$r(e),Qr(e,null,n),t}return Yr(e,r,t,n),$r(e)}function za(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}function Ba(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Va=!1;function Ha(){if(Va){var e=sa;if(e!==null)throw e}}function Ua(e,t,n,r){Va=!1;var i=e.updateQueue;Pa=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(zl&f)===f:(r&f)===f){f!==0&&f===oa&&(Va=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=m({},d,f);break a;case 2:Pa=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),ql|=o,e.lanes=o,e.memoizedState=d}}function Wa(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Ga(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=F.T,s={};F.T=s,js(e,!1,t,n);try{var c=i(),l=F.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?As(e,t,ua(c,r),hu(e)):As(e,t,r,hu(e))}catch(n){As(e,t,{then:function(){},status:`rejected`,reason:n},hu())}finally{I.p=a,o!==null&&s.types!==null&&(o.types=s.types),F.T=o}}function bs(){}function xs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ss(e).queue;ys(e,a,t,te,n===null?bs:function(){return Cs(e),n(r)})}function Ss(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:te,baseState:te,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mo,lastRenderedState:te},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Cs(e){var t=Ss(e);t.next===null&&(t=e.alternate.memoizedState),As(e,t.next.queue,{},hu())}function ws(){return Yi(np)}function Ts(){return Do().memoizedState}function Es(){return Do().memoizedState}function Ds(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=hu();e=La(n);var r=Ra(t,e,n);r!==null&&(_u(r,t,n),za(r,t,n)),t={cache:na()},e.payload=t;return}t=t.return}}function Os(e,t,n){var r=hu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ms(e)?Ns(t,n):(n=Xr(e,t,n,r),n!==null&&(_u(n,e,r),Ps(n,t,r)))}function ks(e,t,n){As(e,t,n,hu())}function As(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ms(e))Ns(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,gr(s,o))return Yr(e,t,i,0),Rl===null&&Jr(),!1}catch{}if(n=Xr(e,t,i,r),n!==null)return _u(n,e,r),Ps(n,t,r),!0}return!1}function js(e,t,n,r){if(r={lane:2,revertLane:md(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ms(e)){if(t)throw Error(i(479))}else t=Xr(e,n,r,2),t!==null&&_u(t,e,2)}function Ms(e){var t=e.alternate;return e===K||t!==null&&t===K}function Ns(e,t){uo=lo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ps(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}var Fs={readContext:Yi,use:Ao,useCallback:_o,useContext:_o,useEffect:_o,useImperativeHandle:_o,useLayoutEffect:_o,useInsertionEffect:_o,useMemo:_o,useReducer:_o,useRef:_o,useState:_o,useDebugValue:_o,useDeferredValue:_o,useTransition:_o,useSyncExternalStore:_o,useId:_o,useHostTransitionStatus:_o,useFormState:_o,useActionState:_o,useOptimistic:_o,useMemoCache:_o,useCacheRefresh:_o};Fs.useEffectEvent=_o;var Is={readContext:Yi,use:Ao,useCallback:function(e,t){return Eo().memoizedState=[e,t===void 0?null:t],e},useContext:Yi,useEffect:os,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),is(4194308,4,fs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return is(4194308,4,e,t)},useInsertionEffect:function(e,t){is(4,2,e,t)},useMemo:function(e,t){var n=Eo();t=t===void 0?null:t;var r=e();if(fo){Le(!0);try{e()}finally{Le(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Eo();if(n!==void 0){var i=n(t);if(fo){Le(!0);try{n(t)}finally{Le(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Os.bind(null,K,e),[r.memoizedState,e]},useRef:function(e){var t=Eo();return e={current:e},t.memoizedState=e},useState:function(e){e=Ho(e);var t=e.queue,n=ks.bind(null,K,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ms,useDeferredValue:function(e,t){return _s(Eo(),e,t)},useTransition:function(){var e=Ho(!1);return e=ys.bind(null,K,e.queue,!0,!1),Eo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=K,a=Eo();if(G){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Rl===null)throw Error(i(349));zl&127||Lo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,os(zo.bind(null,r,o,e),[e]),r.flags|=2048,ns(9,{destroy:void 0},Ro.bind(null,r,o,n,t),null),n},useId:function(){var e=Eo(),t=Rl.identifierPrefix;if(G){var n=xi,r=bi;n=(r&~(1<<32-Re(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=po++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[rt]=t,o[it]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Rd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Ac(t)}}return Fc(t),jc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Ac(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ce.current,Fi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Di,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[rt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Fd(e.nodeValue,n)),e||Mi(t,!0)}else e=Wd(e).createTextNode(r),e[rt]=t,t.stateNode=e}return Fc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Fi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[rt]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),e=!1}else n=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ro(t),t):(ro(t),null);if(t.flags&128)throw Error(i(558))}return Fc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Fi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[rt]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),a=!1}else a=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(ro(t),t):(ro(t),null)}return ro(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Nc(t,t.updateQueue),Fc(t),null);case 4:return de(),e===null&&Td(t.stateNode.containerInfo),Fc(t),null;case 10:return Ui(t.type),Fc(t),null;case 19:if(L(io),r=t.memoizedState,r===null)return Fc(t),null;if(a=(t.flags&128)!=0,o=r.rendering,o===null)if(a)Pc(r,!1);else{if(Kl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=ao(e),o!==null){for(t.flags|=128,Pc(r,!1),e=o.updateQueue,t.updateQueue=e,Nc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)ai(n,e),n=n.sibling;return ae(io,io.current&1|2),G&&Si(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ee()>ru&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304)}else{if(!a)if(e=ao(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Nc(t,e),Pc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!G)return Fc(t),null}else 2*Ee()-r.renderingStartTime>ru&&n!==536870912&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Fc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ee(),e.sibling=null,n=io.current,ae(io,a?n&1|2:n&1),G&&Si(t,r.treeForkCount),e);case 22:case 23:return ro(t),Xa(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Fc(t),t.subtreeFlags&6&&(t.flags|=8192)):Fc(t),n=t.updateQueue,n!==null&&Nc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&L(fa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ui(ta),Fc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Lc(e,t){switch(Ti(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ui(ta),de(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return pe(t),null;case 31:if(t.memoizedState!==null){if(ro(t),t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ro(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return L(io),null;case 4:return de(),null;case 10:return Ui(t.type),null;case 22:case 23:return ro(t),Xa(),e!==null&&L(fa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ui(ta),null;case 25:return null;default:return null}}function Rc(e,t){switch(Ti(t),t.tag){case 3:Ui(ta),de();break;case 26:case 27:case 5:pe(t);break;case 4:de();break;case 31:t.memoizedState!==null&&ro(t);break;case 13:ro(t);break;case 19:L(io);break;case 10:Ui(t.type);break;case 22:case 23:ro(t),Xa(),e!==null&&L(fa);break;case 24:Ui(ta)}}function zc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){qu(t,t.return,e)}}function Bc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){qu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){qu(t,t.return,e)}}function Vc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ga(t,n)}catch(t){qu(e,e.return,t)}}}function Hc(e,t,n){n.props=Us(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){qu(e,t,n)}}function Uc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){qu(e,t,n)}}function Wc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){qu(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){qu(e,t,n)}else n.current=null}function Gc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){qu(e,e.return,t)}}function Kc(e,t,n){try{var r=e.stateNode;zd(r,e.type,n,t),r[it]=t}catch(t){qu(e,e.return,t)}}function qc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&tf(e.type)||e.tag===4}function Jc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||qc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&tf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Yc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Jt));else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Yc(e,t,n),e=e.sibling;e!==null;)Yc(e,t,n),e=e.sibling}function Xc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Xc(e,t,n),e=e.sibling;e!==null;)Xc(e,t,n),e=e.sibling}function Zc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Rd(t,r,n),t[rt]=e,t[it]=n}catch(t){qu(e,e.return,t)}}var Qc=!1,$c=!1,el=!1,tl=typeof WeakSet==`function`?WeakSet:Set,nl=null;function rl(e,t){if(e=e.containerInfo,Hd=dp,e=xr(e),Sr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Ud={focusedElem:e,selectionRange:n},dp=!1,nl=t;nl!==null;)if(t=nl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,nl=e;else for(;nl!==null;){switch(t=nl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Rd(o,r,n),o[rt]=e,ht(o),r=o;break a;case`link`:var s=Gf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=yr(s,h),v=yr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,F.T=null,n=du,du=null;var o=su,s=lu;if(ou=0,cu=su=null,lu=0,Ll&6)throw Error(i(331));var c=Ll;if(Ll|=4,Ml(o.current),wl(o,o.current,s,n),Ll=c,sd(0,!1),Ie&&typeof Ie.onPostCommitFiberRoot==`function`)try{Ie.onPostCommitFiberRoot(Fe,o)}catch{}return!0}finally{I.p=a,F.T=r,Uu(e,t)}}function Ku(e,t,n){t=fi(n,t),t=Ys(e.stateNode,t,2),e=Ra(e,t,2),e!==null&&(Ye(e,2),od(e))}function qu(e,t,n){if(e.tag===3)Ku(e,e,n);else for(;t!==null;){if(t.tag===3){Ku(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(au===null||!au.has(r))){e=fi(n,e),n=Xs(2),r=Ra(t,n,2),r!==null&&(Zs(n,r,t,e),Ye(r,2),od(r));break}}t=t.return}}function Ju(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Il;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Wl=!0,i.add(n),e=Yu.bind(null,e,t,n),t.then(e,e))}function Yu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Rl===e&&(zl&n)===n&&(Kl===4||Kl===3&&(zl&62914560)===zl&&300>Ee()-tu?!(Ll&2)&&wu(e,0):Yl|=n,Zl===zl&&(Zl=0)),od(e)}function Xu(e,t){t===0&&(t=qe()),e=Zr(e,t),e!==null&&(Ye(e,t),od(e))}function Zu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Xu(e,n)}function Qu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Xu(e,n)}function $u(e,t){return Se(e,t)}var ed=null,td=null,nd=!1,rd=!1,id=!1,ad=0;function od(e){e!==td&&e.next===null&&(td===null?ed=td=e:td=td.next=e),rd=!0,nd||(nd=!0,pd())}function sd(e,t){if(!id&&rd){id=!0;do for(var n=!1,r=ed;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Re(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,fd(r,a))}else a=zl,a=We(r,r===Rl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ge(r,a)||(n=!0,fd(r,a));r=r.next}while(n);id=!1}}function cd(){ld()}function ld(){rd=nd=!1;var e=0;ad!==0&&Yd()&&(e=ad);for(var t=Ee(),n=null,r=ed;r!==null;){var i=r.next,a=ud(r,t);a===0?(r.next=null,n===null?ed=i:n.next=i,i===null&&(td=n)):(n=r,(e!==0||a&3)&&(rd=!0)),r=i}ou!==0&&ou!==5||sd(e,!1),ad!==0&&(ad=0)}function ud(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Bd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Tf(e,t,n){var r=wf;if(r&&typeof t==`string`&&t){var i=Nt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),yf.has(i)||(yf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Rd(t,`link`,e),ht(t),r.head.appendChild(t)))}}function Ef(e){xf.D(e),Tf(`dns-prefetch`,e,null)}function Df(e,t){xf.C(e,t),Tf(`preconnect`,e,t)}function Of(e,t,n){xf.L(e,t,n);var r=wf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Nt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Nt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Nt(n.imageSizes)+`"]`)):i+=`[href="`+Nt(e)+`"]`;var a=i;switch(t){case`style`:a=Pf(e);break;case`script`:a=Rf(e)}vf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Ff(a))||t===`script`&&r.querySelector(zf(a))||(t=r.createElement(`link`),Rd(t,`link`,e),ht(t),r.head.appendChild(t)))}}function kf(e,t){xf.m(e,t);var n=wf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Nt(r)+`"][href="`+Nt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rf(e)}if(!vf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),vf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zf(a)))return}r=n.createElement(`link`),Rd(r,`link`,e),ht(r),n.head.appendChild(r)}}}function Af(e,t,n){xf.S(e,t,n);var r=wf;if(r&&e){var i=mt(r).hoistableStyles,a=Pf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Ff(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vf.get(a))&&Hf(e,n);var c=o=r.createElement(`link`);ht(c),Rd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jf(e,t){xf.X(e,t);var n=wf;if(n&&e){var r=mt(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=m({src:e,async:!0},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),ht(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t){xf.M(e,t);var n=wf;if(n&&e){var r=mt(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),ht(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nf(e,t,n,r){var a=(a=ce.current)?bf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Pf(n.href),n=mt(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pf(n.href);var o=mt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Ff(e)))&&!o._p&&(s.instance=o,s.state.loading=5),vf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vf.set(e,n),o||Lf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Rf(n),n=mt(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Pf(e){return`href="`+Nt(e)+`"`}function Ff(e){return`link[rel="stylesheet"][`+e+`]`}function If(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Lf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Rd(t,`link`,n),ht(t),e.head.appendChild(t))}function Rf(e){return`[src="`+Nt(e)+`"]`}function zf(e){return`script[async]`+e}function Bf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Nt(n.href)+`"]`);if(r)return t.instance=r,ht(r),r;var a=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),ht(r),Rd(r,`style`,a),Vf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Pf(n.href);var o=e.querySelector(Ff(a));if(o)return t.state.loading|=4,t.instance=o,ht(o),o;r=If(n),(a=vf.get(a))&&Hf(r,a),o=(e.ownerDocument||e).createElement(`link`),ht(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Rd(o,`link`,r),t.state.loading|=4,Vf(o,n.precedence,e),t.instance=o;case`script`:return o=Rf(n.src),(a=e.querySelector(zf(o)))?(t.instance=a,ht(a),a):(r=n,(a=vf.get(o))&&(r=m({},n),Uf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),ht(a),Rd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vf(r,n.precedence,e));return t.instance}function Vf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Yf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pf(r.href),a=t.querySelector(Ff(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Qf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,ht(a);return}a=t.ownerDocument||t,r=If(r),(i=vf.get(i))&&Hf(r,i),a=a.createElement(`link`),ht(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Rd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Qf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Xf=0;function Zf(e,t){return e.stylesheets&&e.count===0&&ep(e,e.stylesheets),0Xf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Qf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ep(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var $f=null;function ep(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,$f=new Map,t.forEach(tp,e),$f=null,Qf.call(e))}function tp(e,t){if(!(t.state.loading&4)){var n=$f.get(e);if(n)var r=n.get(null);else{n=new Map,$f.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=g()})),v=l(d()),y=_(),b=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),x=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),S={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},C=(0,v.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,v.createElement)(`svg`,{ref:c,...S,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:x(`lucide`,i),...s},[...o.map(([e,t])=>(0,v.createElement)(e,t)),...Array.isArray(a)?a:[a]])),w=(e,t)=>{let n=(0,v.forwardRef)(({className:n,...r},i)=>(0,v.createElement)(C,{ref:i,iconNode:t,className:x(`lucide-${b(e)}`,n),...r}));return n.displayName=`${e}`,n},T=w(`Activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),E=w(`ArrowDownToLine`,[[`path`,{d:`M12 17V3`,key:`1cwfxf`}],[`path`,{d:`m6 11 6 6 6-6`,key:`12ii2o`}],[`path`,{d:`M19 21H5`,key:`150jfl`}]]),D=w(`ArrowUpFromLine`,[[`path`,{d:`m18 9-6-6-6 6`,key:`kcunyi`}],[`path`,{d:`M12 3v14`,key:`7cf3v8`}],[`path`,{d:`M5 21h14`,key:`11awu3`}]]),O=w(`Ban`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m4.9 4.9 14.2 14.2`,key:`1m5liu`}]]),k=w(`Bot`,[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]),A=w(`Check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),j=w(`ChevronDown`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),M=w(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),N=w(`ChevronUp`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),P=w(`ChevronsDownUp`,[[`path`,{d:`m7 20 5-5 5 5`,key:`13a0gw`}],[`path`,{d:`m7 4 5 5 5-5`,key:`1kwcof`}]]),ee=w(`ChevronsUpDown`,[[`path`,{d:`m7 15 5 5 5-5`,key:`1hf1tw`}],[`path`,{d:`m7 9 5-5 5 5`,key:`sgt6xg`}]]),F=w(`CircleCheck`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),I=w(`CircleStop`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`rect`,{x:`9`,y:`9`,width:`6`,height:`6`,rx:`1`,key:`1ssd4o`}]]),te=w(`Clock`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`polyline`,{points:`12 6 12 12 16 14`,key:`68esgv`}]]),ne=w(`Coins`,[[`circle`,{cx:`8`,cy:`8`,r:`6`,key:`3yglwk`}],[`path`,{d:`M18.09 10.37A6 6 0 1 1 10.34 18`,key:`t5s6rm`}],[`path`,{d:`M7 6h1v4`,key:`1obek4`}],[`path`,{d:`m16.71 13.88.7.71-2.82 2.82`,key:`1rbuyh`}]]),re=w(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),ie=w(`Download`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`7 10 12 15 17 10`,key:`2ggqvy`}],[`line`,{x1:`12`,x2:`12`,y1:`15`,y2:`3`,key:`1vk2je`}]]),L=w(`Eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),ae=w(`FileCode`,[[`path`,{d:`M10 12.5 8 15l2 2.5`,key:`1tg20x`}],[`path`,{d:`m14 12.5 2 2.5-2 2.5`,key:`yinavb`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z`,key:`1mlx9k`}]]),oe=w(`FileOutput`,[[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2`,key:`1vk7w2`}],[`path`,{d:`M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6`,key:`1jink5`}],[`path`,{d:`m5 11-3 3`,key:`1dgrs4`}],[`path`,{d:`m5 17-3-3h10`,key:`1mvvaf`}]]),se=w(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),ce=w(`GitBranch`,[[`line`,{x1:`6`,x2:`6`,y1:`3`,y2:`15`,key:`17qcm7`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M18 9a9 9 0 0 1-9 9`,key:`n2h4wq`}]]),le=w(`Hash`,[[`line`,{x1:`4`,x2:`20`,y1:`9`,y2:`9`,key:`4lhtct`}],[`line`,{x1:`4`,x2:`20`,y1:`15`,y2:`15`,key:`vyu0kd`}],[`line`,{x1:`10`,x2:`8`,y1:`3`,y2:`21`,key:`1ggp8o`}],[`line`,{x1:`16`,x2:`14`,y1:`3`,y2:`21`,key:`weycgp`}]]),ue=w(`Layers`,[[`path`,{d:`M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z`,key:`zw3jo`}],[`path`,{d:`M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12`,key:`1wduqc`}],[`path`,{d:`M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17`,key:`kqbvx6`}]]),de=w(`ListChecks`,[[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`m3 7 2 2 4-4`,key:`1obspn`}],[`path`,{d:`M13 6h8`,key:`15sg57`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 18h8`,key:`oe0vm4`}]]),fe=w(`LoaderCircle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),pe=w(`Maximize`,[[`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`,key:`1dcmit`}],[`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`,key:`1e4gt3`}],[`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`,key:`wsl5sc`}],[`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`,key:`18trek`}]]),me=w(`MessageCircle`,[[`path`,{d:`M7.9 20A9 9 0 1 0 4 16.1L2 22Z`,key:`vv11sd`}]]),he=w(`MessageSquarePlus`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M12 7v6`,key:`lw1j43`}],[`path`,{d:`M9 10h6`,key:`9gxzsh`}]]),ge=w(`Octagon`,[[`path`,{d:`M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z`,key:`2d38gg`}]]),_e=w(`Pause`,[[`rect`,{x:`14`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`zuxfzm`}],[`rect`,{x:`6`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`1okwgv`}]]),ve=w(`Play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),ye=w(`Repeat`,[[`path`,{d:`m17 2 4 4-4 4`,key:`nntrym`}],[`path`,{d:`M3 11v-1a4 4 0 0 1 4-4h14`,key:`84bu3i`}],[`path`,{d:`m7 22-4-4 4-4`,key:`1wqhfi`}],[`path`,{d:`M21 13v1a4 4 0 0 1-4 4H3`,key:`1rx37r`}]]),be=w(`Search`,[[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`path`,{d:`m21 21-4.3-4.3`,key:`1qie3q`}]]),xe=w(`Send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),Se=w(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Ce=w(`SkipForward`,[[`polygon`,{points:`5 4 15 12 5 20 5 4`,key:`16p6eg`}],[`line`,{x1:`19`,x2:`19`,y1:`5`,y2:`19`,key:`futhcm`}]]),we=w(`SquareTerminal`,[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]]),Te=w(`Square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Ee=w(`Terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),De=w(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Oe=w(`Variable`,[[`path`,{d:`M8 21s-4-3-4-9 4-9 4-9`,key:`uto9ud`}],[`path`,{d:`M16 3s4 3 4 9-4 9-4 9`,key:`4w2vsq`}],[`line`,{x1:`15`,x2:`9`,y1:`9`,y2:`15`,key:`f7djnv`}],[`line`,{x1:`9`,x2:`15`,y1:`9`,y2:`15`,key:`1shsy8`}]]),ke=w(`WifiOff`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}],[`path`,{d:`M5 12.859a10 10 0 0 1 5.17-2.69`,key:`1dl1wf`}],[`path`,{d:`M19 12.859a10 10 0 0 0-2.007-1.523`,key:`4k23kn`}],[`path`,{d:`M2 8.82a15 15 0 0 1 4.177-2.643`,key:`1grhjp`}],[`path`,{d:`M22 8.82a15 15 0 0 0-11.288-3.764`,key:`z3jwby`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),Ae=w(`Wifi`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M2 8.82a15 15 0 0 1 20 0`,key:`dnpr2z`}],[`path`,{d:`M5 12.859a10 10 0 0 1 14 0`,key:`1x1e6c`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}]]),je=w(`X`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),Me=w(`Zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]),Ne=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},Pe=(e=>e?Ne(e):Ne),Fe=e=>e;function Ie(e,t=Fe){let n=v.useSyncExternalStore(e.subscribe,v.useCallback(()=>t(e.getState()),[e,t]),v.useCallback(()=>t(e.getInitialState()),[e,t]));return v.useDebugValue(n),n}var Le=e=>{let t=Pe(e),n=e=>Ie(t,e);return Object.assign(n,t),n},Re=(e=>e?Le(e):Le);function ze(e,t){if(t.type===`guidance_received`)return[...e,{text:t.data.text,applied:!1}];let n=e.findIndex(e=>!e.applied&&e.text===t.data.text);if(n===-1)return[...e,{text:t.data.text,applied:!0,source:t.data.source,agentName:t.data.agent_name}];let r=[...e];return r[n]={...r[n],applied:!0,source:t.data.source,agentName:t.data.agent_name},r}function Be(){return window.__CONDUCTOR_TOKEN__}function Ve(){let e=Be();return e?{Authorization:`Bearer ${e}`}:{}}function He(e){let t=Be();return t?`${e}${e.includes(`?`)?`&`:`?`}token=${encodeURIComponent(t)}`:e}function R(e,t,n=`agent`){return e[t]||(e[t]={name:t,status:`pending`,type:n,activity:[]}),e[t].activity||(e[t].activity=[]),e[t]}function Ue(e,t,n){R(e,t).activity.push(n)}function z(e,t){e[t]&&(e[t]={...e[t]})}function We(e,t,n,r){let i=e[t];if(!i?.for_each_items)return;let a=i.for_each_items.find(e=>e.key===n);a&&a.activity.push(r)}function Ge(e,t,n,r){return{parentAgent:e,iteration:t,slotKey:r??e,workflowFile:n,workflowName:``,status:`pending`,agents:[],routes:[],parallelGroups:[],forEachGroups:[],nodes:{},groupProgress:{},highlightedEdges:[],entryPoint:null,children:[],agentsCompleted:0,agentsTotal:0,totalCost:0,totalTokens:0,unpricedCount:0,eventLog:[],activityLog:[],workflowOutput:null,workflowFailure:null}}function Ke(e,t,n){let r=Ge(e,1,n,e);r.workflowName=t.name||``,r.entryPoint=t.entry_point||null,r.agents=t.agents,r.routes=t.routes||[],r.parallelGroups=t.parallel_groups||[],r.forEachGroups=t.for_each_groups||[];let i=new Set,a=new Set;for(let e of r.parallelGroups){for(let t of e.agents)i.add(t);a.add(e.name),R(r.nodes,e.name,`parallel_group`),r.groupProgress[e.name]={total:e.agents.length,completed:0,failed:0};for(let t of e.agents)R(r.nodes,t,`agent`)}for(let e of r.forEachGroups)a.add(e.name),R(r.nodes,e.name,`for_each_group`),r.groupProgress[e.name]={total:0,completed:0,failed:0};for(let e of r.agents){if(a.has(e.name)||i.has(e.name))continue;let t=e.type||`agent`;R(r.nodes,e.name,t),a.add(e.name)}return qe(r.agents,r.children),r}function qe(e,t){for(let n of e)n.type!==`workflow`||!n.subworkflow||t.some(e=>e.slotKey===n.name)||t.push(Ke(n.name,n.subworkflow,``))}function Je(e){return{...e,agents:[...e.agents],routes:[...e.routes],parallelGroups:[...e.parallelGroups],forEachGroups:[...e.forEachGroups],nodes:{...e.nodes},groupProgress:{...e.groupProgress},highlightedEdges:[...e.highlightedEdges],eventLog:[...e.eventLog],activityLog:[...e.activityLog],children:[...e.children]}}function Ye(e,t){function n(e,t){let r=[...e];if(t.length===0)return{contexts:r,ctx:null};let i=t[0],a=r[i];if(!a)return{contexts:r,ctx:null};let o=Je(a);if(t.length>1){let e=n(a.children,t.slice(1));return o.children=e.contexts,r[i]=o,{contexts:r,ctx:e.ctx}}return r[i]=o,{contexts:r,ctx:o}}let r=n(e.subworkflowContexts,t);return e.subworkflowContexts=r.contexts,r.ctx}function Xe(e,t){let n=Qe(e.subworkflowContexts,t);if(!n)return null;let r=Ye(e,n.indexPath);return{indexPath:n.indexPath,ctx:r}}function Ze(e,t){if(t.length===0)return null;let n=e[t[0]];for(let e=1;e=0;n--)if(r[n].slotKey===e){t=n;break}if(t===-1)return null;n.push(t),i=r[t],r=i.children}return{indexPath:n,ctx:i}}function $e(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.slotKey===t)return{ctx:r,index:n}}return null}var B=Re((e,t)=>({workflowName:``,workflowStatus:`pending`,workflowStartTime:null,workflowFailure:null,workflowFailedAgent:null,workflowTermination:null,workflowYaml:null,conductorVersion:null,entryPoint:null,agents:[],routes:[],parallelGroups:[],forEachGroups:[],nodes:{},groupProgress:{},highlightedEdges:[],agentsCompleted:0,agentsTotal:0,totalCost:0,totalTokens:0,unpricedCount:0,selectedNode:null,wsStatus:`connecting`,wsDisconnectedSince:null,wsAuthFailed:!1,wsSendFailed:!1,systemLogFile:null,bgStderrLog:null,bgStdoutLog:null,eventLog:[],activityLog:[],workflowOutput:null,lastEventTime:null,isPaused:!1,iterationLimitGate:null,userGuidance:[],wfDepth:0,subworkflowContexts:[],activeContextPath:[],viewContextPath:[],expandedContexts:new Set,replayMode:!1,replayEvents:[],replayPosition:0,replayTotalEvents:0,replayPlaying:!1,replaySpeed:1,_wsSend:null,setWsSend:t=>{e({_wsSend:t})},sendGateResponse:(t,n,r,i)=>{let a=B.getState()._wsSend;a?(a({type:`gate_response`,agent_name:t,selected_value:n,additional_input:r||{},prompt_id:i??null}),e({wsSendFailed:!1})):(console.error(`sendGateResponse: WebSocket not connected, response was not sent`),e({wsSendFailed:!0}))},activeDialog:null,dialogEngaged:!1,engageDialog:()=>{e({dialogEngaged:!0})},sendDialogMessage:(t,n,r)=>{let i=B.getState()._wsSend;i?(i({type:`dialog_message`,agent_name:t,dialog_id:n,content:r}),e({wsSendFailed:!1})):(console.error(`sendDialogMessage: WebSocket not connected, message was not sent`),e({wsSendFailed:!0}))},sendDialogDecline:(t,n)=>{let r=B.getState()._wsSend;r?(r({type:`dialog_decline`,agent_name:t,dialog_id:n}),e({wsSendFailed:!1})):(console.error(`sendDialogDecline: WebSocket not connected, decline was not sent`),e({wsSendFailed:!0}))},sendIterationLimitResponse:(t,n,r)=>{let i=B.getState()._wsSend;if(!i){console.error(`sendIterationLimitResponse: WebSocket not connected, response was not sent`),e({wsSendFailed:!0});return}let a=Math.max(0,Math.floor(Number(r)||0));i({type:`iteration_limit_response`,gate_id:n,...`agent_name`in t?{agent_name:t.agent_name}:{group_name:t.group_name},additional_iterations:a}),e({wsSendFailed:!1})},sendGuidance:async e=>{try{let t=await fetch(`/api/guidance`,{method:`POST`,headers:{"Content-Type":`application/json`,...Ve()},body:JSON.stringify({text:e})}),n=await t.json().catch(()=>({}));return t.ok?{ok:!0,pending:n.pending??0,paused:n.paused??!1}:{ok:!1,status:t.status,error:n.error||`HTTP ${t.status}`}}catch{return{ok:!1,status:null,error:`The dashboard is unreachable.`}}},processEvent:t=>{let n=tt[t.type];e(e=>{let r={...e,nodes:{...e.nodes},groupProgress:{...e.groupProgress},eventLog:[...e.eventLog],activityLog:[...e.activityLog],lastEventTime:t.timestamp};n&&n(r,t.data,t.timestamp);let i=rt(t);i&&r.eventLog.push(i);let a=at(t);return a&&r.activityLog.push(a),r})},replayState:t=>{e(e=>{let n={...e,agentsCompleted:0,totalCost:0,totalTokens:0,unpricedCount:0,nodes:{},groupProgress:{},highlightedEdges:[],eventLog:[],activityLog:[],workflowOutput:null,workflowFailedAgent:null,workflowTermination:null,activeDialog:null,dialogEngaged:!1,wfDepth:0,subworkflowContexts:[],activeContextPath:[]};for(let e of t){let t=tt[e.type];t&&t(n,e.data,e.timestamp);let r=rt(e);r&&n.eventLog.push(r);let i=at(e);i&&n.activityLog.push(i),n.lastEventTime=e.timestamp}return n})},selectNode:t=>{e({selectedNode:t})},toggleContextExpanded:t=>{e(e=>{let n=new Set(e.expandedContexts);return n.has(t)?n.delete(t):n.add(t),{expandedContexts:n}})},expandContexts:t=>{t.length!==0&&e(e=>{let n=new Set(e.expandedContexts),r=!1;for(let e of t)n.has(e)||(n.add(e),r=!0);return r?{expandedContexts:n}:{}})},collapseContexts:t=>{t.length!==0&&e(e=>{let n=new Set(e.expandedContexts),r=!1;for(let e of t)n.delete(e)&&(r=!0);return r?{expandedContexts:n}:{}})},markReplayMode:()=>{e({replayMode:!0})},setReplayMode:t=>{e(e=>{let n={...e,replayMode:!0,replayEvents:t,replayTotalEvents:t.length,replayPosition:t.length,replayPlaying:!1,replaySpeed:1,agentsCompleted:0,totalCost:0,totalTokens:0,unpricedCount:0,nodes:{},groupProgress:{},highlightedEdges:[],eventLog:[],activityLog:[],workflowOutput:null,workflowFailedAgent:null,workflowTermination:null,activeDialog:null,dialogEngaged:!1,wfDepth:0,subworkflowContexts:[],activeContextPath:[],viewContextPath:[]};for(let e of t){let t=tt[e.type];t&&t(n,e.data,e.timestamp);let r=rt(e);r&&n.eventLog.push(r);let i=at(e);i&&n.activityLog.push(i),n.lastEventTime=e.timestamp}return n})},setReplayPosition:t=>{e(e=>{let n=e.replayEvents.slice(0,t),r={...e,replayPosition:t,agentsCompleted:0,totalCost:0,totalTokens:0,unpricedCount:0,nodes:{},groupProgress:{},highlightedEdges:[],eventLog:[],activityLog:[],workflowOutput:null,workflowFailedAgent:null,workflowTermination:null,workflowStatus:`pending`,workflowStartTime:null,workflowName:``,workflowFailure:null,entryPoint:null,agents:[],routes:[],parallelGroups:[],forEachGroups:[],isPaused:!1,iterationLimitGate:null,userGuidance:[],lastEventTime:null,activeDialog:null,dialogEngaged:!1,wfDepth:0,subworkflowContexts:[],activeContextPath:[],viewContextPath:[]};for(let e of n){let t=tt[e.type];t&&t(r,e.data,e.timestamp);let n=rt(e);n&&r.eventLog.push(n);let i=at(e);i&&r.activityLog.push(i),r.lastEventTime=e.timestamp}return r})},setReplayPlaying:t=>{e({replayPlaying:t})},setReplaySpeed:t=>{e({replaySpeed:t})},setWsStatus:t=>{e(e=>{let n=e.wsDisconnectedSince;return t===`connected`?n=null:(e.wsStatus===`connected`||n===null)&&(n=Date.now()),{wsStatus:t,wsDisconnectedSince:n}})},setWsAuthFailed:t=>{e({wsAuthFailed:t})},setWsSendFailed:t=>{e({wsSendFailed:t})},setEdgeHighlight:(t,n,r)=>{e(e=>({highlightedEdges:[...e.highlightedEdges.filter(e=>!(e.from===t&&e.to===n)),{from:t,to:n,state:r}]}))},clearEdgeHighlight:(t,n)=>{e(e=>({highlightedEdges:e.highlightedEdges.filter(e=>!(e.from===t&&e.to===n))}))},navigateToContext:t=>{e({viewContextPath:t,selectedNode:null})},navigateUp:()=>{e(e=>({viewContextPath:e.viewContextPath.slice(0,-1),selectedNode:null}))},navigateIntoSubworkflow:n=>{let r=t(),i=r.viewContextPath,a;if(i.length===0)a=r.subworkflowContexts;else{let e=Ze(r.subworkflowContexts,i);if(!e)return;a=e.children}let o=$e(a,n);o&&e({viewContextPath:[...i,o.index],selectedNode:null})},getViewedContext:()=>{let e=t();if(e.viewContextPath.length===0)return{workflowName:e.workflowName,agents:e.agents,routes:e.routes,parallelGroups:e.parallelGroups,forEachGroups:e.forEachGroups,nodes:e.nodes,groupProgress:e.groupProgress,highlightedEdges:e.highlightedEdges,entryPoint:e.entryPoint,subworkflowContexts:e.subworkflowContexts};let n=Ze(e.subworkflowContexts,e.viewContextPath);return n?{workflowName:n.workflowName,agents:n.agents,routes:n.routes,parallelGroups:n.parallelGroups,forEachGroups:n.forEachGroups,nodes:n.nodes,groupProgress:n.groupProgress,highlightedEdges:n.highlightedEdges,entryPoint:n.entryPoint,subworkflowContexts:n.children}:{workflowName:e.workflowName,agents:e.agents,routes:e.routes,parallelGroups:e.parallelGroups,forEachGroups:e.forEachGroups,nodes:e.nodes,groupProgress:e.groupProgress,highlightedEdges:e.highlightedEdges,entryPoint:e.entryPoint,subworkflowContexts:e.subworkflowContexts}},getBreadcrumbs:()=>{let e=t(),n=[{label:e.workflowName||`Root`,path:[]}],r=e.subworkflowContexts;for(let t=0;te.slotKey===a.slotKey).length>1?`${o} (iteration ${a.iteration})`:o;n.push({label:s,path:e.viewContextPath.slice(0,t+1)}),r=a.children}return n}}));function V(e,t){let n=null,r=t?.subworkflow_path;if(Array.isArray(r)&&r.length>0&&(n=Xe(e,r)?.ctx??null),n){let t=n;return{nodes:t.nodes,groupProgress:t.groupProgress,routes:t.routes,highlightedEdges:t.highlightedEdges,addCost:n=>{t.totalCost+=n,e.totalCost+=n},addTokens:n=>{t.totalTokens+=n,e.totalTokens+=n},addUnpriced:()=>{t.unpricedCount++,e.unpricedCount++},incrCompleted:()=>{t.agentsCompleted++,e.agentsCompleted++}}}return{nodes:e.nodes,groupProgress:e.groupProgress,routes:e.routes,highlightedEdges:e.highlightedEdges,addCost:t=>{e.totalCost+=t},addTokens:t=>{e.totalTokens+=t},addUnpriced:()=>{e.unpricedCount++},incrCompleted:()=>{e.agentsCompleted++}}}function et(e,t){let n=e.findIndex(e=>e.slotKey===t.slotKey&&e.status===`pending`);if(n>=0){let r=e[n];return e[n]={...r,parentAgent:t.parentAgent,iteration:t.iteration,workflowFile:t.workflowFile||r.workflowFile},n}return e.push(t),e.length-1}var tt={workflow_started:(e,t,n)=>{let r=t;if(e.wfDepth===0){e.workflowStatus=`running`,e.workflowStartTime=n??Date.now()/1e3,e.workflowName=r.name||``,e.workflowYaml=t.yaml_source??null,e.conductorVersion=t.version??null,e.entryPoint=r.entry_point||null,e.systemLogFile=r.system?.log_file||null,e.bgStderrLog=r.system?.bg_stderr_log??null,e.bgStdoutLog=r.system?.bg_stdout_log??null,e.agents=r.agents||[],e.routes=r.routes||[],e.parallelGroups=r.parallel_groups||[],e.forEachGroups=r.for_each_groups||[],e.userGuidance=[],R(e.nodes,`$start`,`start`),e.nodes.$start.status=`running`,z(e.nodes,`$start`);let i=new Set,a=new Set;for(let t of e.parallelGroups){for(let e of t.agents)i.add(e);a.add(t.name),R(e.nodes,t.name,`parallel_group`),e.groupProgress[t.name]={total:t.agents.length,completed:0,failed:0};for(let n of t.agents)R(e.nodes,n,`agent`)}for(let t of e.forEachGroups)a.add(t.name),R(e.nodes,t.name,`for_each_group`),e.groupProgress[t.name]={total:0,completed:0,failed:0};for(let t of e.agents)if(!a.has(t.name)&&!i.has(t.name)){let n=t.type||`agent`;if(R(e.nodes,t.name,n),t.model&&(e.nodes[t.name].model=t.model),t.reasoning_effort&&(e.nodes[t.name].reasoning_effort=t.reasoning_effort),t.provider_name){e.nodes[t.name].provider_name=t.provider_name;let n=r.providers?.[t.provider_name];n?.tier&&(e.nodes[t.name].provider_tier=n.tier)}a.add(t.name)}e.agentsTotal=a.size,Ye(e,[]),qe(e.agents,e.subworkflowContexts)}else{let n=t.subworkflow_path,i=Array.isArray(n)&&n.length>0?Xe(e,n)?.ctx??null:Ye(e,e.activeContextPath);if(i){i.workflowName=r.name||``,i.status=`running`,i.entryPoint=r.entry_point||null,i.agents=r.agents||[],i.routes=r.routes||[],i.parallelGroups=r.parallel_groups||[],i.forEachGroups=r.for_each_groups||[],R(i.nodes,`$start`,`start`),i.nodes.$start.status=`running`;let e=new Set,t=new Set;for(let n of i.parallelGroups){for(let t of n.agents)e.add(t);t.add(n.name),R(i.nodes,n.name,`parallel_group`),i.groupProgress[n.name]={total:n.agents.length,completed:0,failed:0};for(let e of n.agents)R(i.nodes,e,`agent`)}for(let e of i.forEachGroups)t.add(e.name),R(i.nodes,e.name,`for_each_group`),i.groupProgress[e.name]={total:0,completed:0,failed:0};for(let n of i.agents)if(!t.has(n.name)&&!e.has(n.name)){let e=n.type||`agent`;if(R(i.nodes,n.name,e),n.model&&(i.nodes[n.name].model=n.model),n.reasoning_effort&&(i.nodes[n.name].reasoning_effort=n.reasoning_effort),n.provider_name){i.nodes[n.name].provider_name=n.provider_name;let e=r.providers?.[n.provider_name];e?.tier&&(i.nodes[n.name].provider_tier=e.tier)}t.add(n.name)}i.agentsTotal=t.size,qe(i.agents,i.children)}}e.wfDepth++},agent_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.iteration!=null&&(a.output!=null||a.error_type!=null)&&(a.iterationHistory||=[],a.iterationHistory.push({iteration:a.iteration,prompt:a.prompt,output:a.output,elapsed:a.elapsed,model:a.model,reasoning_effort:a.reasoning_effort,tokens:a.tokens,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd,activity:a.activity,error_type:a.error_type,error_message:a.error_message})),a.status=`running`,a.iteration=r.iteration,a.startedAt=n??Date.now()/1e3,a.activity=[],r.context_window_max!=null&&(a.context_window_max=r.context_window_max),a.prompt=void 0,a.output=void 0,a.error_type=void 0,a.error_message=void 0,a.context_pct=void 0,z(i.nodes,r.agent_name)},agent_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.model=n.model,i.tokens=n.tokens,i.input_tokens=n.input_tokens,i.output_tokens=n.output_tokens,i.cost_usd=n.cost_usd,i.output=n.output,i.output_keys=n.output_keys,i.context_window_used=n.context_window_used,i.context_window_max=n.context_window_max,n.context_window_used!=null&&n.context_window_max!=null&&n.context_window_max>0?i.context_pct=Math.round(n.context_window_used/n.context_window_max*100):i.context_pct=void 0,n.cost_usd&&r.addCost(n.cost_usd),n.tokens&&r.addTokens(n.tokens),n.tokens&&n.cost_usd==null&&r.addUnpriced();let a=t;a.terminated_by&&(i.termination_status=a.status??`success`,i.termination_reason=a.termination_reason,i.terminated_by=a.terminated_by),z(r.nodes,n.agent_name)},agent_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message;for(let e of r.routes)e.to===n.agent_name&&r.highlightedEdges.push({from:e.from,to:e.to,state:`failed`});let a=t;a.terminated_by&&(i.termination_status=a.status??`failed`,i.termination_reason=a.termination_reason,i.terminated_by=a.terminated_by),z(r.nodes,n.agent_name)},agent_prompt_rendered:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=R(i.nodes,n.agent_name);if(a.prompt=n.continuation?`${a.prompt??``}\n\n${n.rendered_prompt}`:n.rendered_prompt,a.context_keys=n.context_keys,r){We(i.nodes,n.agent_name,r,{type:`prompt`,icon:`📝`,label:`prompt`,text:`Prompt rendered`,detail:n.rendered_prompt?.slice(0,500)||null});let e=i.nodes[n.agent_name];if(e?.for_each_items){let t=e.for_each_items.find(e=>e.key===r);t&&(t.prompt=n.continuation?`${t.prompt??``}\n\n${n.rendered_prompt}`:n.rendered_prompt)}}z(i.nodes,n.agent_name)},agent_reasoning:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`reasoning`,icon:`💭`,label:`thinking`,text:n.content};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_tool_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`tool-start`,icon:`🔧`,label:`tool`,text:n.tool_name,detail:n.arguments||null};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_tool_complete:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`tool-complete`,icon:`✓`,label:`result`,text:n.tool_name||`done`,detail:n.result||null};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_compaction_config:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=n.enabled===!1?{type:`compaction-config`,icon:`⚙`,label:`compaction`,text:`disabled${n.disabled_reason?`: ${n.disabled_reason}`:``}`}:{type:`compaction-config`,icon:`⚙`,label:`compaction`,text:`armed (window ${n.context_window} from ${n.context_window_source}, output limit ${n.output_limit} from ${n.output_limit_source}, trigger ${n.trigger_tokens??`?`}, target ${n.target_tokens??`?`})`};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_compaction_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`compaction-start`,icon:`🧹`,label:`compacting`,text:`compacting context (${n.tokens_before??`?`} tokens, window ${n.context_window} from ${n.context_window_source})`};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_compaction_complete:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a;if(n.errored)a={type:`compaction-error`,icon:`⚠️`,label:`compaction failed`,text:`${n.error_type||`Error`}: ${n.message||`unknown`}`};else if(n.still_over_trigger||n.degraded_tiers&&n.degraded_tiers.length>0){let e=[...n.degraded_tiers&&n.degraded_tiers.length>0?[`degraded tiers: ${n.degraded_tiers.join(`, `)}`]:[],...n.still_over_trigger?[`still over trigger`]:[]];a={type:`compaction-error`,icon:`⚠️`,label:`compacted with warnings`,text:`${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${e.join(`; `)})`}}else a={type:`compaction-complete`,icon:`🧹`,label:`compacted`,text:`${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${n.messages_before??`?`} → ${n.messages_after??`?`} messages, ${n.elapsed==null?`?`:it(n.elapsed)}${n.tokens_saved==null?``:`, saved ${n.tokens_saved} tokens`})`};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_tool_output_truncated:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`tool-complete`,icon:`✂`,label:`truncated`,text:n.tool_name||`tool`,detail:`${n.original_chars}→${n.kept_chars} chars${n.spill_path?` · full: `+n.spill_path:``}`};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_parse_recovery:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`parse-recovery`,icon:`↻`,label:`retry`,text:`${n.reason===`schema`?`output schema mismatch`:`invalid JSON`} (${n.attempt??`?`}/${n.max_attempts??`?`})`,detail:n.error||null};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_turn_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`turn`,icon:`⏳`,label:`turn`,text:`Turn ${n.turn??`?`}`};Ue(i.nodes,n.agent_name,a),r&&We(i.nodes,n.agent_name,r,a),z(i.nodes,n.agent_name)},agent_message:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.latest_message=n.content,z(r.nodes,n.agent_name)},script_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.status=`running`,a.startedAt=n??Date.now()/1e3,z(i.nodes,r.agent_name)},script_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.stdout=n.stdout,i.stderr=n.stderr,i.exit_code=n.exit_code,z(r.nodes,n.agent_name)},script_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name)},wait_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.status=`running`,a.startedAt=n??Date.now()/1e3,a.duration_seconds=r.duration_seconds??null,a.reason=r.reason??null,a.iteration=r.iteration,z(i.nodes,r.agent_name)},wait_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.waited_seconds=n.waited_seconds,i.requested_seconds=n.requested_seconds,i.reason=n.reason??null,i.interrupted=n.interrupted,z(r.nodes,n.agent_name)},wait_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name)},set_started:(e,t,n)=>{let r=t,i=V(e,t),a=R(i.nodes,r.agent_name);a.status=`running`,a.startedAt=n??Date.now()/1e3,z(i.nodes,r.agent_name)},set_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.elapsed=n.elapsed,i.set_output_type=n.output_type,i.set_output_keys=n.output_keys,i.set_value_repr=n.value_repr,z(r.nodes,n.agent_name)},set_failed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name)},gate_presented:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`waiting`,i.options=n.options,i.option_details=n.option_details,i.prompt=n.prompt,i.gate_prompt_id=n.prompt_id??null,z(r.nodes,n.agent_name)},gate_resolved:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name);i.status=`completed`,r.incrCompleted(),i.selected_option=n.selected_option,i.route=n.route,i.additional_input=n.additional_input,z(r.nodes,n.agent_name)},questions_presented:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.status=`waiting`,i.questions_total=n.total,i.questions_answered_count=0,i.questions_skipped_count=0,i.questions_outcomes={},i.questions_outcome=void 0,z(r.nodes,n.agent_name)},questions_answered:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.questions_total=n.total;let a={...i.questions_outcomes||{}};a[n.question_id]=n.skipped?`skipped`:`answered`,i.questions_outcomes=a;let o=Object.values(a);i.questions_answered_count=o.filter(e=>e===`answered`).length,i.questions_skipped_count=o.filter(e=>e===`skipped`).length,i.questions_reject_reason=null,z(r.nodes,n.agent_name)},questions_answer_rejected:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.questions_reject_reason=n.reason,z(r.nodes,n.agent_name)},questions_completed:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.agent_name,`questions`);i.status=`completed`,r.incrCompleted(),i.questions_outcome=n.outcome,i.questions_answered_count=n.answered_count,i.questions_skipped_count=n.skipped_count,i.questions_reject_reason=null,z(r.nodes,n.agent_name)},route_taken:(e,t)=>{let n=t;V(e,t).highlightedEdges.push({from:n.from_agent,to:n.to_agent,state:`taken`})},parallel_started:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.group_name,`parallel_group`);i.status=`running`,r.groupProgress[n.group_name]&&(r.groupProgress[n.group_name].total=n.agents.length,r.groupProgress[n.group_name].completed=0,r.groupProgress[n.group_name].failed=0),z(r.nodes,n.group_name)},parallel_agent_completed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].completed++;let i=R(r.nodes,n.agent_name);i.status=`completed`,i.elapsed=n.elapsed,i.model=n.model,i.tokens=n.tokens,i.cost_usd=n.cost_usd,i.context_window_used=n.context_window_used,i.context_window_max=n.context_window_max,n.context_window_used!=null&&n.context_window_max!=null&&n.context_window_max>0?i.context_pct=Math.round(n.context_window_used/n.context_window_max*100):i.context_pct=void 0,n.cost_usd&&r.addCost(n.cost_usd),n.tokens&&r.addTokens(n.tokens),n.tokens&&n.cost_usd==null&&r.addUnpriced(),z(r.nodes,n.agent_name),z(r.nodes,n.group_name)},parallel_agent_failed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].failed++;let i=R(r.nodes,n.agent_name);i.status=`failed`,i.elapsed=n.elapsed,i.error_type=n.error_type,i.error_message=n.message,z(r.nodes,n.agent_name),z(r.nodes,n.group_name)},parallel_completed:(e,t)=>{let n=t,r=V(e,t);r.incrCompleted();let i=R(r.nodes,n.group_name,`parallel_group`);i.status=n.failure_count===0?`completed`:`failed`,z(r.nodes,n.group_name)},for_each_started:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.group_name,`for_each_group`);i.status=`running`,i.for_each_items=[],r.groupProgress[n.group_name]&&(r.groupProgress[n.group_name].total=n.item_count,r.groupProgress[n.group_name].completed=0,r.groupProgress[n.group_name].failed=0),z(r.nodes,n.group_name)},for_each_item_started:(e,t)=>{let n=t,r=V(e,t),i=R(r.nodes,n.group_name,`for_each_group`);i.for_each_items||=[],i.for_each_items.push({key:n.item_key??String(n.index),index:n.index,status:`running`,activity:[]}),z(r.nodes,n.group_name)},for_each_item_completed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].completed++;let i=R(r.nodes,n.group_name,`for_each_group`);if(i.for_each_items){let e=n.item_key??String(n.index),t=i.for_each_items.find(t=>t.key===e);t&&(t.status=`completed`,t.elapsed=n.elapsed,t.tokens=n.tokens,t.cost_usd=n.cost_usd,t.output=n.output)}z(r.nodes,n.group_name)},for_each_item_failed:(e,t)=>{let n=t,r=V(e,t);r.groupProgress[n.group_name]&&r.groupProgress[n.group_name].failed++;let i=R(r.nodes,n.group_name,`for_each_group`);if(i.for_each_items){let e=n.item_key??String(n.index),t=i.for_each_items.find(t=>t.key===e);t&&(t.status=`failed`,t.elapsed=n.elapsed,t.error_type=n.error_type,t.error_message=n.message)}z(r.nodes,n.group_name)},for_each_completed:(e,t)=>{let n=t,r=V(e,t);r.incrCompleted();let i=R(r.nodes,n.group_name,`for_each_group`);i.status=(n.failure_count??0)===0?`completed`:`failed`,i.elapsed=n.elapsed,i.success_count=n.success_count,i.failure_count=n.failure_count,z(r.nodes,n.group_name)},workflow_completed:(e,t)=>{if(e.wfDepth=Math.max(0,e.wfDepth-1),e.wfDepth===0){let n=t;e.workflowStatus=`completed`,e.isPaused=!1,e.iterationLimitGate=null,e.workflowOutput=n.output??null,n.is_explicit?e.workflowTermination={is_explicit:!0,status:n.status??`success`,termination_reason:n.termination_reason,terminated_by:n.terminated_by}:e.workflowTermination=null,e.nodes.$end&&(e.nodes.$end.status=`completed`,z(e.nodes,`$end`)),e.nodes.$start&&(e.nodes.$start.status=`completed`,z(e.nodes,`$start`)),e.highlightedEdges=[]}else{let n=t,r=n.subworkflow_path?Xe(e,n.subworkflow_path)?.ctx:Ye(e,e.activeContextPath);r&&(r.status=`completed`,r.workflowOutput=n.output??null,r.nodes.$end&&(r.nodes.$end.status=`completed`),r.nodes.$start&&(r.nodes.$start.status=`completed`),r.highlightedEdges=[])}},workflow_failed:(e,t)=>{let n=t;if(e.wfDepth=n.stopped_by_user&&!n.subworkflow_path?0:Math.max(0,e.wfDepth-1),e.wfDepth===0){if(e.workflowStatus=`failed`,e.isPaused=!1,e.iterationLimitGate=null,e.workflowFailedAgent=n.agent_name||null,n.agent_name&&e.nodes[n.agent_name]){e.nodes[n.agent_name].status=`failed`,z(e.nodes,n.agent_name);for(let t of e.routes)t.to===n.agent_name&&e.highlightedEdges.push({from:t.from,to:t.to,state:`failed`})}e.workflowFailure={error_type:n.error_type,message:n.message,elapsed_seconds:n.elapsed_seconds,timeout_seconds:n.timeout_seconds,current_agent:n.current_agent,checkpoint_path:n.checkpoint_path,checkpoint_unavailable_reason:n.checkpoint_unavailable_reason,stopped_by_user:n.stopped_by_user,termination_reason:n.termination_reason,terminated_by:n.terminated_by,is_explicit:n.is_explicit,status:n.status},n.is_explicit?e.workflowTermination={is_explicit:!0,status:n.status??`failed`,termination_reason:n.termination_reason,terminated_by:n.terminated_by}:e.workflowTermination=null,e.nodes.$start&&(e.nodes.$start.status=`completed`,z(e.nodes,`$start`))}else{let t=n.subworkflow_path?Xe(e,n.subworkflow_path)?.ctx:Ye(e,e.activeContextPath);t&&(t.status=`failed`,t.workflowFailure={error_type:n.error_type,message:n.message})}},subworkflow_started:(e,t)=>{let n=t,r=n.slot_key??(n.item_key==null?n.agent_name:`${n.agent_name}[${n.item_key}]`),i=Ge(n.agent_name,n.iteration??1,n.workflow,r),a;if(n.parent_path!==void 0){let t=Qe(e.subworkflowContexts,n.parent_path);if(!t)return;a=t.indexPath}else a=e.activeContextPath;let o,s=null;if(a.length===0)Ye(e,[]),o=[et(e.subworkflowContexts,i)];else{if(s=Ye(e,a),!s)return;let t=et(s.children,i);o=[...a,t]}if(e.activeContextPath=o,a.length===0){let t=e.nodes[n.agent_name];t&&(t.status=`running`,z(e.nodes,n.agent_name))}else if(s){let e=s.nodes[n.agent_name];e&&(e.status=`running`,z(s.nodes,n.agent_name))}},subworkflow_completed:(e,t)=>{let n=t,r;if(n.parent_path!==void 0){let t=Qe(e.subworkflowContexts,n.parent_path);if(!t)return;r=t.indexPath}else r=e.activeContextPath;let i=r.length===0?null:Ye(e,r),a=r.length===0?e.nodes:i?.nodes;if(a){let t=a[n.agent_name];t&&(n.item_key??(t.status=`completed`,t.elapsed=n.elapsed,r.length===0?e.agentsCompleted++:i&&i.agentsCompleted++),z(a,n.agent_name))}e.activeContextPath=r},subworkflow_failed:(e,t)=>{let n=t,r;if(n.parent_path!==void 0){let t=Qe(e.subworkflowContexts,n.parent_path);if(!t)return;r=t.indexPath}else r=e.activeContextPath;let i=r.length===0?e.nodes:Ye(e,r)?.nodes;if(i){let e=i[n.agent_name];e&&n.item_key==null&&(e.status=`failed`,e.elapsed=n.elapsed,e.error_type=n.error_type,e.error_message=n.message,z(i,n.agent_name))}e.activeContextPath=r},checkpoint_saved:(e,t)=>{let n=t;n.path&&e.workflowFailure&&(e.workflowFailure={...e.workflowFailure,checkpoint_path:n.path})},agent_paused:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.status=`waiting`,r.activity.push({type:`agent_paused`,icon:`⏸`,label:`Paused`,text:`Agent paused — click Resume to re-execute`}),z(e.nodes,n.agent_name),e.isPaused=!0},agent_resumed:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.status=`running`,r.activity.push({type:`agent_resumed`,icon:`▶`,label:`Resumed`,text:n.with_guidance?`Agent resumed with guidance — re-executing`:`Agent resumed — re-executing`}),z(e.nodes,n.agent_name),e.isPaused=!1},guidance_received:(e,t)=>{let n=t;e.userGuidance=ze(e.userGuidance,{type:`guidance_received`,data:n})},guidance_applied:(e,t)=>{let n=t;e.userGuidance=ze(e.userGuidance,{type:`guidance_applied`,data:n}),n.agent_name&&(R(e.nodes,n.agent_name).activity.push({type:`guidance_applied`,icon:`💬`,label:`Guidance`,text:`Guidance applied (${n.source}): ${n.text}`}),z(e.nodes,n.agent_name))},iteration_limit_reached:(e,t)=>{let n=t;e.iterationLimitGate=n;let r=n.agent_name??n.group_name;r?(R(e.nodes,r).activity.push({type:`iteration_limit_reached`,icon:`⚠`,label:`Iteration limit`,text:`Reached ${n.current_iteration}/${n.max_iterations} iterations — ${n.skip_gates?`auto-stopping (--skip-gates)`:`awaiting decision`}`}),z(e.nodes,r)):typeof console<`u`&&console.warn(`[workflow-store] iteration_limit_reached event missing both agent_name and group_name`,n)},iteration_limit_resolved:(e,t)=>{let n=t;e.iterationLimitGate=null;let r=n.agent_name??n.group_name;r?(R(e.nodes,r).activity.push({type:`iteration_limit_resolved`,icon:n.continue_execution?`▶`:`■`,label:`Iteration limit`,text:n.aborted?`Gate aborted unexpectedly — stopping workflow`:n.continue_execution?`Continuing with ${n.additional_iterations} more iteration(s)`:`Stopping workflow`}),z(e.nodes,r)):typeof console<`u`&&console.warn(`[workflow-store] iteration_limit_resolved event missing both agent_name and group_name`,n)},dialog_started:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.dialog_id=n.dialog_id,r.dialog_messages=[],r.dialog_active=!0,r.dialog_awaiting_response=!1,e.activeDialog={agentName:n.agent_name,dialogId:n.dialog_id},e.dialogEngaged=!1,z(e.nodes,n.agent_name)},dialog_message:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.dialog_messages||=[],r.dialog_messages.push({role:n.role,content:n.content}),n.role===`user`?r.dialog_awaiting_response=!0:n.role===`agent`&&(r.dialog_awaiting_response=!1),z(e.nodes,n.agent_name)},dialog_completed:(e,t)=>{let n=t,r=R(e.nodes,n.agent_name);r.dialog_active=!1,r.dialog_awaiting_response=!1,e.activeDialog=null,e.dialogEngaged=!1,z(e.nodes,n.agent_name)},agent_validator_start:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a={type:`validator-start`,icon:`🔎`,label:`validator`,text:`validating output`,detail:n.criteria_preview||null};if(Ue(i.nodes,n.agent_name,a),r!=null)We(i.nodes,n.agent_name,String(r),a);else{let e=R(i.nodes,n.agent_name);e.validator_state=`running`,e.validator_model=n.model??null,e.validator_attempts=(e.validator_attempts??0)+1}z(i.nodes,n.agent_name)},agent_validator_complete:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=n.errored?`error`:n.passed?`passed`:`failed`,o={type:`validator-complete`,icon:n.errored?`⚠️`:n.passed?`✅`:`❌`,label:`validator`,text:n.errored?`validation error (treated as pass)`:n.passed?`validation passed`:`validation failed`,detail:n.issues&&n.issues.length?n.issues.join(` -`):null};if(Ue(i.nodes,n.agent_name,o),r!=null)We(i.nodes,n.agent_name,String(r),o);else{let e=R(i.nodes,n.agent_name);e.validator_state=a,e.validator_issues=n.issues??[],e.validator_cost_usd=n.cost_usd??null,e.validator_model=n.model??e.validator_model??null}z(i.nodes,n.agent_name)},agent_validation_failed:(e,t)=>{let n=t,r=t.item_key,i=V(e,t),a=n.rerun_errored===!0,o={type:`validation-failed`,icon:a?`⚠️`:`❌`,label:`validator`,text:a?`re-run failed — keeping original output`:n.will_retry?`re-running once with feedback`:`validation failed (no retry)`,detail:[...n.issues&&n.issues.length?[n.issues.join(` -`)]:[],...a&&n.error?[`cause: ${n.error}`]:[]].join(` -`)||null};if(Ue(i.nodes,n.agent_name,o),r!=null)We(i.nodes,n.agent_name,String(r),o);else{let e=R(i.nodes,n.agent_name);e.validator_will_retry=n.will_retry,e.validator_issues=n.issues??[],a&&(e.validator_state=`error`)}z(i.nodes,n.agent_name)}};function nt(e){return e.item_key==null?String(e.agent_name):`${e.agent_name}[${e.item_key}]`}function rt(e){let t=e.timestamp,n=e.data;switch(e.type){case`workflow_started`:return{timestamp:t,level:`info`,source:`workflow`,message:`Workflow "${n.name||``}" started`};case`agent_started`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Agent started${n.iteration==null?``:` (iteration ${n.iteration})`}`};case`agent_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Agent completed${n.elapsed==null?``:` in ${it(n.elapsed)}`}${n.tokens==null?``:` · ${n.tokens.toLocaleString()} tokens`}${n.cost_usd==null?``:` · $${n.cost_usd.toFixed(4)}`}`};case`agent_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Agent failed: ${n.message||n.error_type||`unknown error`}`};case`script_started`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Script started`};case`script_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Script completed (exit ${n.exit_code??`?`})${n.elapsed==null?``:` in ${it(n.elapsed)}`}`};case`script_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Script failed: ${n.message||n.error_type||`unknown error`}`};case`wait_started`:{let e=n.duration_seconds,r=n.reason,i=typeof e==`number`?it(e):`?`;return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Waiting ${i}${r?` — ${r}`:``}`}}case`wait_completed`:{let e=n.waited_seconds,r=n.interrupted;return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Wait completed${e==null?``:` (${it(e)})`}${r?` — interrupted`:``}`}}case`wait_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Wait failed: ${n.message||n.error_type||`unknown error`}`};case`set_started`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`Set started`};case`set_completed`:{let e=n.output_keys??[],r=e.length>0?` · ${e.join(`, `)}`:``;return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Set completed${r}${n.elapsed==null?``:` in ${it(n.elapsed)}`}`}}case`set_failed`:return{timestamp:t,level:`error`,source:String(n.agent_name),message:`Set failed: ${n.message||n.error_type||`unknown error`}`};case`gate_presented`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Waiting for human input…`};case`gate_resolved`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Gate resolved → ${n.selected_option||`continue`}`};case`questions_presented`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Asking ${n.total} question(s)…`};case`questions_answered`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:`${n.skipped?`Skipped`:`Answered`} ${n.question_id} (${n.cursor+1}/${n.total})`};case`questions_answer_rejected`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:String(n.reason)};case`questions_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Questions ${n.outcome} — ${n.answered_count} answered, ${n.skipped_count} skipped`};case`route_taken`:return{timestamp:t,level:`debug`,source:`router`,message:`${n.from_agent} → ${n.to_agent}`};case`parallel_started`:return{timestamp:t,level:`info`,source:String(n.group_name),message:`Parallel group started (${n.agents?.length||`?`} agents)`};case`parallel_completed`:return{timestamp:t,level:n.failure_count===0?`success`:`error`,source:String(n.group_name),message:`Parallel group completed${n.failure_count>0?` with ${n.failure_count} failure(s)`:``}`};case`for_each_started`:return{timestamp:t,level:`info`,source:String(n.group_name),message:`For-each started (${n.item_count} items)`};case`for_each_completed`:return{timestamp:t,level:(n.failure_count??0)===0?`success`:`error`,source:String(n.group_name),message:`For-each completed · ${n.success_count} succeeded${n.failure_count>0?` · ${n.failure_count} failed`:``}`};case`workflow_completed`:return{timestamp:t,level:`success`,source:`workflow`,message:`Workflow completed${n.elapsed==null?``:` in ${it(n.elapsed)}`}`};case`workflow_failed`:return{timestamp:t,level:`error`,source:`workflow`,message:`Workflow failed: ${n.message||n.error_type||`unknown error`}`};case`budget_exceeded`:{let e=n.spent_usd??0,r=n.budget_usd??0,i=String(n.budget_mode??`audit`),a=n.current_agent?` at ${n.current_agent}`:``;return{timestamp:t,level:i===`enforce`?`error`:`warning`,source:`workflow`,message:`Budget exceeded — $${e.toFixed(2)} of $${r.toFixed(2)} (${i})${a}`}}case`checkpoint_saved`:return{timestamp:t,level:`info`,source:`workflow`,message:`Checkpoint saved: ${n.path?.split(`/`).pop()||`unknown`}`};case`agent_paused`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Agent paused — waiting for resume`};case`agent_resumed`:return{timestamp:t,level:`info`,source:String(n.agent_name),message:n.with_guidance?`Agent resumed with guidance — re-executing`:`Agent resumed — re-executing`};case`guidance_received`:return{timestamp:t,level:`info`,source:`guidance`,message:`Guidance received (pending: ${n.pending}): ${n.text}`};case`guidance_applied`:return{timestamp:t,level:`info`,source:n.agent_name||`workflow`,message:`Guidance applied (${n.source}): ${n.text}`};case`iteration_limit_reached`:{let e=n.agent_name??n.group_name??`workflow`,r=n.skip_gates?` — auto-stopping (--skip-gates)`:` — awaiting decision`;return{timestamp:t,level:`warning`,source:String(e),message:`Iteration limit reached (${n.current_iteration}/${n.max_iterations})${r}`}}case`iteration_limit_resolved`:{let e=n.agent_name??n.group_name??`workflow`,r=!!n.continue_execution,i=n.additional_iterations??0;return{timestamp:t,level:r?`info`:`warning`,source:String(e),message:r?`Iteration limit resolved — continuing with ${i} more`:`Iteration limit resolved — stopping workflow`}}case`dialog_started`:return{timestamp:t,level:`warning`,source:String(n.agent_name),message:`Dialog started — waiting for user…`};case`dialog_completed`:return{timestamp:t,level:`success`,source:String(n.agent_name),message:`Dialog completed (${n.turn_count||0} messages)`};case`agent_validator_start`:return{timestamp:t,level:`info`,source:nt(n),message:`Validating output…`};case`agent_validator_complete`:{let e=nt(n);if(n.errored)return{timestamp:t,level:`warning`,source:e,message:`Validator error — treated as pass`};if(n.passed)return{timestamp:t,level:`success`,source:e,message:`Validation passed`};let r=Array.isArray(n.issues)?n.issues.length:0;return{timestamp:t,level:`warning`,source:e,message:`Validation failed (${r} issue${r===1?``:`s`})`}}case`agent_validation_failed`:{let e=nt(n);return n.rerun_errored?{timestamp:t,level:`error`,source:e,message:`Validation re-run failed — keeping original output`}:{timestamp:t,level:`warning`,source:e,message:`Validation failed — ${n.will_retry?`re-running once with feedback`:`no retry`}`}}default:return null}}function it(e){return e<1?`${(e*1e3).toFixed(0)}ms`:e<60?`${e.toFixed(1)}s`:`${Math.floor(e/60)}m ${(e%60).toFixed(0)}s`}function at(e){let t=e.timestamp,n=e.data;switch(e.type){case`agent_started`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Agent started${n.iteration==null?``:` (iteration ${n.iteration})`}`};case`agent_prompt_rendered`:return{timestamp:t,source:String(n.agent_name),type:`prompt`,message:`Prompt rendered`,detail:ot(String(n.rendered_prompt||``),500)};case`agent_reasoning`:return{timestamp:t,source:String(n.agent_name),type:`reasoning`,message:String(n.content||``)};case`agent_tool_start`:return{timestamp:t,source:String(n.agent_name),type:`tool-start`,message:`→ ${n.tool_name}`,detail:n.arguments?ot(String(n.arguments),300):null};case`agent_tool_complete`:return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`← ${n.tool_name||`done`}`,detail:n.result?ot(String(n.result),300):null};case`agent_compaction_config`:return n.enabled===!1?{timestamp:t,source:String(n.agent_name),type:`compaction-config`,message:`⚙ compaction disabled${n.disabled_reason?`: ${n.disabled_reason}`:``}`}:{timestamp:t,source:String(n.agent_name),type:`compaction-config`,message:`⚙ compaction armed (window ${n.context_window} from ${n.context_window_source}, output limit ${n.output_limit} from ${n.output_limit_source}, trigger ${n.trigger_tokens??`?`}, target ${n.target_tokens??`?`})`};case`agent_compaction_start`:return{timestamp:t,source:String(n.agent_name),type:`compaction-start`,message:`🧹 compacting context (${n.tokens_before??`?`} tokens, window ${n.context_window} from ${n.context_window_source})`};case`agent_compaction_complete`:if(n.errored)return{timestamp:t,source:String(n.agent_name),type:`compaction-error`,message:`⚠️ compaction failed — ${n.error_type||`Error`}: ${n.message||`unknown`}`};if(n.still_over_trigger||Array.isArray(n.degraded_tiers)&&n.degraded_tiers.length>0){let e=[...Array.isArray(n.degraded_tiers)&&n.degraded_tiers.length>0?[`degraded tiers: ${n.degraded_tiers.join(`, `)}`]:[],...n.still_over_trigger?[`still over trigger`]:[]];return{timestamp:t,source:String(n.agent_name),type:`compaction-error`,message:`⚠️ context compacted with warnings: ${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${e.join(`; `)})`}}return{timestamp:t,source:String(n.agent_name),type:`compaction-complete`,message:`🧹 context compacted: ${n.tokens_before??`?`} → ${n.tokens_after??`?`} tokens (${n.messages_before??`?`} → ${n.messages_after??`?`} messages, ${n.elapsed==null?`?`:it(n.elapsed)}${typeof n.tokens_saved==`number`?`, saved ${n.tokens_saved} tokens`:``})`};case`agent_tool_output_truncated`:return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`✂ ${n.tool_name||`tool`} truncated`,detail:`${n.original_chars}→${n.kept_chars} chars${n.spill_path?` · full: `+n.spill_path:``}`};case`agent_parse_recovery`:return{timestamp:t,source:String(n.agent_name),type:`parse-recovery`,message:`↻ retrying output — ${n.reason===`schema`?`output schema mismatch`:`invalid JSON`} (${n.attempt??`?`}/${n.max_attempts??`?`})`,detail:n.error?ot(String(n.error),300):null};case`agent_turn_start`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Turn ${n.turn??`?`}`};case`agent_message`:return{timestamp:t,source:String(n.agent_name),type:`message`,message:ot(String(n.content||``),500)};case`agent_completed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Completed${n.elapsed==null?``:` in ${it(n.elapsed)}`}${n.tokens==null?``:` · ${n.tokens.toLocaleString()} tokens`}`};case`agent_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Failed: ${n.message||n.error_type||`unknown`}`};case`script_started`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Script started`};case`script_completed`:return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`Script completed (exit ${n.exit_code??`?`})`,detail:n.stdout?ot(String(n.stdout),300):null};case`script_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Script failed: ${n.message||n.error_type||`unknown`}`};case`wait_started`:{let e=n.duration_seconds,r=n.reason,i=typeof e==`number`?it(e):`?`;return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Waiting ${i}${r?` — ${r}`:``}`}}case`wait_completed`:{let e=n.waited_seconds,r=n.interrupted;return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`Wait completed${e==null?``:` (${it(e)})`}${r?` — interrupted`:``}`}}case`wait_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Wait failed: ${n.message||n.error_type||`unknown`}`};case`set_started`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Set started`};case`set_completed`:{let e=n.output_keys??[],r=e.length>0?` (${e.join(`, `)})`:``;return{timestamp:t,source:String(n.agent_name),type:`tool-complete`,message:`Set completed${r}`,detail:n.value_repr?ot(String(n.value_repr),300):null}}case`set_failed`:return{timestamp:t,source:String(n.agent_name),type:`turn`,message:`Set failed: ${n.message||n.error_type||`unknown`}`};default:return null}}function ot(e,t){return e.length<=t?e:e.slice(0,t)+`…`}var st=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),H=o(((e,t)=>{t.exports=st()}))();function ct(e){let t=e.match(/^(\s*)/);return t?t[1].length:0}function lt(e){let t=new Map;for(let n=0;ni)a=t;else break}a>n&&t.set(n,a)}return t}function ut(e){if(/^\s*#/.test(e))return(0,H.jsx)(`span`,{className:`text-emerald-500/70`,children:e});let t=e.match(/^(\s*)(- )?([a-zA-Z_][\w.-]*)(:\s*)(.*)/);if(t){let[,e,n,r,i,a]=t;return(0,H.jsxs)(`span`,{children:[e,n??``,(0,H.jsx)(`span`,{className:`text-sky-400`,children:r}),(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:i}),dt(a??``)]})}let n=e.match(/^(\s*)(- )(.*)/);if(n){let[,e,t,r]=n;return(0,H.jsxs)(`span`,{children:[e,(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:t}),dt(r??``)]})}return(0,H.jsx)(`span`,{children:e})}function dt(e){if(!e)return``;let t=e.indexOf(` #`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t):``,i=n;return/^(true|false|null|yes|no)$/i.test(n.trim())||/^\d+(\.\d+)?$/.test(n.trim())?i=(0,H.jsx)(`span`,{className:`text-amber-400`,children:n}):/^["'].*["']$/.test(n.trim())?i=(0,H.jsx)(`span`,{className:`text-green-400`,children:n}):(n.includes(`|`)||n.includes(`>`))&&(i=(0,H.jsx)(`span`,{className:`text-[var(--text-secondary)]`,children:n})),(0,H.jsxs)(H.Fragment,{children:[i,r&&(0,H.jsx)(`span`,{className:`text-emerald-500/70`,children:r})]})}function ft({yaml:e,onClose:t}){let[n,r]=(0,v.useState)(new Set);(0,v.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let i=(0,v.useMemo)(()=>e.split(` -`),[e]),a=(0,v.useMemo)(()=>lt(i),[i]),o=(0,v.useCallback)(e=>{r(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),s=(0,v.useMemo)(()=>{let e=[],t=-1;for(let r=0;r(0,H.jsxs)(`div`,{className:`flex`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center justify-center flex-shrink-0`,style:{width:`1.25rem`},children:n?(0,H.jsx)(`button`,{onClick:()=>o(e),className:`text-[var(--text-muted)] hover:text-[var(--text)] p-0 leading-none`,style:{background:`none`,border:`none`,cursor:`pointer`},children:r?(0,H.jsx)(M,{className:`w-3 h-3`}):(0,H.jsx)(j,{className:`w-3 h-3`})}):null}),(0,H.jsxs)(`span`,{className:`flex-1`,children:[ut(t),r&&(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] text-[11px] ml-2 px-1.5 py-0.5 rounded bg-[var(--surface-hover)] cursor-pointer`,onClick:()=>o(e),children:`···`})]})]},e))})})]})]})}function pt({onClose:e}){let t=B(e=>e.isPaused),n=B(e=>e.wsStatus),r=B(e=>e.userGuidance),i=B(e=>e.sendGuidance),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(null),d=n===`connected`&&!s,f=a.trim(),p=!d||f.length===0,m=async()=>{if(p)return;c(!0),u(null);let e=await i(f);c(!1),e.ok?o(``):u(e.error)};return(0,v.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]),(0,H.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`guidance-title`,"data-testid":`guidance-modal`,className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm`,onClick:e,children:(0,H.jsxs)(`div`,{className:`relative flex flex-col w-[90vw] max-w-lg rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-2xl overflow-hidden`,onClick:e=>e.stopPropagation(),children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2.5 px-4 py-3 border-b border-[var(--border)] bg-[var(--surface-raised)]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,H.jsx)(he,{className:`w-4 h-4 text-sky-400 flex-shrink-0`}),(0,H.jsx)(`h2`,{id:`guidance-title`,className:`text-sm font-semibold text-[var(--text)]`,children:`Guide this run`})]}),(0,H.jsx)(`button`,{type:`button`,onClick:e,className:`p-1 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,"aria-label":`Close`,children:(0,H.jsx)(je,{className:`w-4 h-4`})})]}),(0,H.jsxs)(`div`,{className:`px-4 py-4 space-y-3`,children:[(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Applied at the next step boundary, or immediately if an agent is currently paused.`}),(0,H.jsx)(`textarea`,{"data-testid":`guidance-textarea`,value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),m())},disabled:!d,autoFocus:!0,rows:3,placeholder:`e.g. Prefer Python 3.12 examples`,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-sky-400 transition-colors disabled:opacity-50 resize-none`}),l&&(0,H.jsx)(`div`,{className:`text-[11px] text-red-300`,role:`alert`,children:l}),n!==`connected`&&(0,H.jsx)(`div`,{className:`text-[11px] text-red-300`,children:`Disconnected from server — reconnect to send guidance.`}),r.length>0&&(0,H.jsxs)(`div`,{className:`space-y-1 max-h-40 overflow-y-auto`,children:[(0,H.jsx)(`h3`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Guidance this run`}),(0,H.jsx)(`ul`,{className:`space-y-1`,children:r.map((e,t)=>(0,H.jsxs)(`li`,{className:`flex items-start gap-1.5 text-[11px] text-[var(--text-secondary)]`,children:[(0,H.jsx)(`span`,{"data-testid":`guidance-entry-marker`,className:e.applied?`text-emerald-400`:`text-amber-400`,children:e.applied?`✓`:`…`}),(0,H.jsx)(`span`,{children:e.text})]},`${t}-${e.text}`))})]})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-2 px-4 py-3 border-t border-[var(--border)] bg-[var(--surface-raised)]`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:e,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg border border-[var(--border)] text-[var(--text)] hover:bg-[var(--surface-hover)] transition-colors`,children:`Close`}),(0,H.jsxs)(`button`,{type:`button`,"data-testid":`guidance-send`,onClick:()=>void m(),disabled:p,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg bg-sky-500 text-white hover:bg-sky-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium`,children:[(0,H.jsx)(xe,{className:`w-3.5 h-3.5`}),s?`Sending…`:t?`Send & resume`:`Send`]})]})]})})}function mt(){let e=B(e=>e.workflowName),t=B(e=>e.workflowStatus),n=B(e=>e.isPaused),r=B(e=>e.workflowYaml),i=B(e=>e.conductorVersion),a=B(e=>e.replayMode),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(!1),[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(!1),[m,h]=(0,v.useState)(!1),[g,_]=(0,v.useState)(null),y=!a&&n,b=!a&&!n&&(t===`running`||t===`pending`);(0,v.useEffect)(()=>{n||(s(!1),l(!1),d(!1))},[n]);let x=async(e,t,n)=>{n(!0),_(null);try{let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`,...Ve()}});if(n.ok)return;console.error(`Failed to ${t}: HTTP ${n.status} from ${e}`),_(`Could not ${t} — server returned HTTP ${n.status}.`)}catch(e){console.error(`Failed to ${t}:`,e),_(`Could not ${t} — the dashboard is unreachable.`)}n(!1)};return(0,H.jsxs)(`header`,{className:`flex items-center justify-between px-4 py-2 bg-[var(--surface)] border-b border-[var(--border)] flex-shrink-0`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(T,{className:`w-4 h-4 text-[var(--running)]`}),(0,H.jsx)(`h1`,{className:`text-sm font-semibold text-[var(--text)]`,children:`Conductor`}),e&&(0,H.jsxs)(`span`,{className:`text-sm text-[var(--text-muted)] font-normal`,children:[`— `,e]})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3`,children:[g&&(0,H.jsx)(`span`,{className:`text-xs text-red-400`,role:`alert`,children:g}),y&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{onClick:()=>x(`/api/resume`,`resume the agent`,l),disabled:c,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded - bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 - hover:bg-emerald-500/20 hover:border-emerald-500/30 - disabled:opacity-50 disabled:cursor-not-allowed - transition-colors`,title:`Re-execute the paused agent`,children:[(0,H.jsx)(ve,{className:`w-3 h-3`}),c?`Resuming...`:`Resume`]}),(0,H.jsxs)(`button`,{onClick:()=>x(`/api/kill`,`kill the workflow`,d),disabled:u,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded - bg-red-500/10 text-red-400 border border-red-500/20 - hover:bg-red-500/20 hover:border-red-500/30 - disabled:opacity-50 disabled:cursor-not-allowed - transition-colors`,title:`Stop the workflow and save a checkpoint for CLI resume`,children:[(0,H.jsx)(je,{className:`w-3 h-3`}),u?`Killing...`:`Kill`]})]}),b&&(0,H.jsxs)(`button`,{onClick:()=>x(`/api/stop`,`stop the agent`,s),disabled:o,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded - bg-red-500/10 text-red-400 border border-red-500/20 - hover:bg-red-500/20 hover:border-red-500/30 - disabled:opacity-50 disabled:cursor-not-allowed - transition-colors`,title:`Pause the current agent, then choose Resume or Kill`,children:[(0,H.jsx)(Te,{className:`w-3 h-3`}),o?`Stopping...`:`Stop`]}),r&&(0,H.jsxs)(`button`,{onClick:()=>p(!0),className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded - bg-[var(--surface-hover)] text-[var(--text-secondary)] border border-[var(--border)] - hover:text-[var(--text)] hover:bg-[var(--surface)] - transition-colors`,title:`View workflow YAML configuration`,children:[(0,H.jsx)(ae,{className:`w-3 h-3`}),`YAML`]}),!a&&(0,H.jsxs)(`button`,{onClick:()=>h(!0),className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded - bg-[var(--surface-hover)] text-[var(--text-secondary)] border border-[var(--border)] - hover:text-[var(--text)] hover:bg-[var(--surface)] - transition-colors`,title:`Send mid-run guidance to the workflow`,children:[(0,H.jsx)(he,{className:`w-3 h-3`}),`Guide`]}),(0,H.jsxs)(`a`,{href:`/api/logs`,download:`conductor-logs.json`,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded - bg-[var(--surface-hover)] text-[var(--text-secondary)] border border-[var(--border)] - hover:text-[var(--text)] hover:bg-[var(--surface)] - transition-colors`,title:`Download full event log as JSON`,children:[(0,H.jsx)(ie,{className:`w-3 h-3`}),`Logs`]}),(0,H.jsxs)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:[`v`,i??`—`]})]}),f&&r&&(0,H.jsx)(ft,{yaml:r,onClose:()=>p(!1)}),m&&(0,H.jsx)(pt,{onClose:()=>h(!1)})]})}function ht(){let e=B(e=>e.getBreadcrumbs),t=B(e=>e.navigateToContext),n=B(e=>e.viewContextPath);if(B(e=>e.subworkflowContexts).length===0&&n.length===0)return null;let r=e();return(0,H.jsxs)(`div`,{className:`flex items-center gap-1 px-4 py-1.5 bg-[var(--surface)] border-b border-[var(--border)] text-xs flex-shrink-0`,children:[(0,H.jsx)(ue,{className:`w-3 h-3 text-[var(--text-muted)] mr-1`}),r.map((e,i)=>{let a=i===r.length-1,o=JSON.stringify(e.path)===JSON.stringify(n);return(0,H.jsxs)(`span`,{className:`flex items-center gap-1`,children:[i>0&&(0,H.jsx)(M,{className:`w-3 h-3 text-[var(--text-muted)]`}),a?(0,H.jsx)(`span`,{className:`font-semibold text-[var(--text)]`,children:e.label}):(0,H.jsx)(`button`,{onClick:()=>t(e.path),className:`hover:text-[var(--running)] transition-colors ${o?`text-[var(--text)] font-medium`:`text-[var(--text-muted)]`}`,children:e.label})]},i)})]})}function U(...e){return e.filter(Boolean).join(` `)}function gt(e){return e==null?``:e<60?`${e.toFixed(1)}s`:`${Math.floor(e/60)}m ${(e%60).toFixed(0)}s`}function _t(e){return e==null?``:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:`${e}`}function vt(e){return e==null?``:`$${e.toFixed(4)}`}function yt(e){return e==null?``:typeof e==`string`?e:JSON.stringify(e,null,2)}function bt(e,t){if(t<=0)return`${e.toLocaleString()} tokens (limit unknown)`;let n=e=>e.toLocaleString(),r=(e/t*100).toFixed(1);return`${n(e)} / ${n(t)} (${r}%)`}function xt(){let e=B(e=>e.workflowStatus),t=B(e=>e.workflowStartTime),n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`—`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t!=null){if(n){o.current&&=(clearInterval(o.current),null),a(gt((r??t)-t));return}if(e===`running`){let e=()=>{a(gt(Date.now()/1e3-t))};return e(),o.current=setInterval(e,500),()=>{o.current&&clearInterval(o.current)}}else (e===`completed`||e===`failed`)&&(o.current&&=(clearInterval(o.current),null))}},[e,t,n,r]),i}function St(){let e=B(e=>e.workflowStatus),t=B(e=>e.agentsCompleted),n=B(e=>e.agentsTotal),r=B(e=>e.totalCost),i=B(e=>e.totalTokens),a=B(e=>e.unpricedCount),o=B(e=>e.wsStatus),s=B(e=>e.workflowFailure),c=B(e=>e.lastEventTime),l=B(e=>e.iterationLimitGate),u=xt(),[d,f]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(e!==`running`||c==null){f(null);return}let t=()=>{f(Math.floor(Date.now()/1e3-c))};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[e,c]);let p=e===`failed`,m=(()=>{if(l&&e===`running`){let e=l.agent_name??l.group_name??`workflow`,t=l.skip_gates?` — auto-stopping`:` — awaiting decision`;return`Iteration limit reached: ${e} ${l.current_iteration}/${l.max_iterations}${t}`}switch(e){case`pending`:return`Waiting for workflow…`;case`running`:return`Running`;case`completed`:return`Completed`;case`failed`:{if(!s)return`Failed`;let e=s.error_type||``;return e===`MaxIterationsError`?`Failed: exceeded maximum iterations`:e===`TimeoutError`?`Failed: workflow timed out`:s.message?`Failed: ${s.message.length>60?s.message.slice(0,57)+`...`:s.message}`:`Failed: ${e}`}}})(),h=l!=null&&e===`running`,g=h?`bg-[var(--waiting)] animate-pulse`:{pending:`bg-[var(--pending)]`,running:`bg-[var(--running)] animate-pulse`,completed:`bg-[var(--completed)]`,failed:`bg-[var(--failed)]`}[e],_=(()=>{switch(o){case`connected`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--completed)]`,children:[(0,H.jsx)(Ae,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Connected`})]});case`disconnected`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--failed)]`,children:[(0,H.jsx)(ke,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Disconnected`})]});case`reconnecting`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--waiting)]`,children:[(0,H.jsx)(fe,{className:`w-3 h-3 animate-spin`}),(0,H.jsx)(`span`,{children:`Reconnecting\\u2026`})]});case`connecting`:return(0,H.jsxs)(`span`,{className:`flex items-center gap-1 text-[var(--text-muted)]`,children:[(0,H.jsx)(fe,{className:`w-3 h-3 animate-spin`}),(0,H.jsx)(`span`,{children:`Connecting\\u2026`})]})}})();return(0,H.jsxs)(`footer`,{className:U(`flex items-center gap-4 px-4 py-1.5 border-t text-xs flex-shrink-0 transition-colors duration-300`,p?`bg-red-950/50 border-red-500/30`:h?`bg-amber-950/30 border-amber-500/30`:`bg-[var(--surface)] border-[var(--border)]`),children:[(0,H.jsx)(`span`,{className:U(`w-2 h-2 rounded-full flex-shrink-0`,g)}),(0,H.jsx)(`span`,{className:U(p?`text-red-300`:h?`text-amber-200`:`text-[var(--text)]`),children:m}),n>0&&(0,H.jsxs)(`span`,{className:U(p?`text-red-400/60`:`text-[var(--text-muted)]`),children:[t,`/`,n,` agents`]}),e!==`pending`&&(0,H.jsx)(`span`,{className:U(`font-mono`,p?`text-red-400/60`:`text-[var(--text-muted)]`),children:u}),i>0&&(0,H.jsxs)(`span`,{className:U(`flex items-center gap-1`,p?`text-red-400/60`:`text-[var(--text-muted)]`),title:`Total tokens used`,children:[(0,H.jsx)(le,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{className:`font-mono`,children:i.toLocaleString()})]}),(r>0||a>0)&&(0,H.jsxs)(`span`,{className:U(`flex items-center gap-1`,p?`text-red-400/60`:`text-[var(--text-muted)]`),title:a>0?`Total cost (partial \u2014 ${a} agent${a===1?``:`s`} with no available pricing)`:`Total cost`,children:[(0,H.jsx)(ne,{className:`w-3 h-3`}),r>0&&(0,H.jsxs)(`span`,{className:`font-mono`,children:[a>0?`~`:``,`$`,r.toFixed(4)]}),a>0&&(0,H.jsx)(`span`,{className:`text-amber-400`,children:r>0?`(${a} unpriced)`:`${a} unpriced`})]}),d!=null&&d>=5&&(0,H.jsxs)(`span`,{className:U(`flex items-center gap-1 font-mono`,d>=60?`text-amber-400`:`text-[var(--text-muted)]`),title:`Time since last event from the provider`,children:[(0,H.jsx)(te,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:d>=60?`${Math.floor(d/60)}m ${d%60}s idle`:`${d}s idle`})]}),(0,H.jsx)(`span`,{className:`flex-1`}),_]})}var Ct=[1,5,10,20,50];function wt(e,t){if(t===0||e.length===0)return`+0.0s`;let n=e[0].timestamp,r=e[Math.min(t,e.length)-1].timestamp-n;return r<60?`+${r.toFixed(1)}s`:`+${Math.floor(r/60)}m${(r%60).toFixed(0)}s`}function Tt(){let e=B(e=>e.replayPosition),t=B(e=>e.replayTotalEvents),n=B(e=>e.replayPlaying),r=B(e=>e.replaySpeed),i=B(e=>e.replayEvents),a=B(e=>e.setReplayPosition),o=B(e=>e.setReplayPlaying),s=B(e=>e.setReplaySpeed),c=e=>{a(parseInt(e.target.value,10)),n&&o(!1)},l=()=>{!n&&e>=t&&a(0),o(!n)},u=t>0?e/t*100:0;return(0,H.jsxs)(`footer`,{className:`flex items-center gap-3 px-4 py-1.5 border-t bg-[var(--surface)] border-[var(--border)] text-xs flex-shrink-0`,children:[(0,H.jsx)(`button`,{onClick:l,className:`flex items-center justify-center w-6 h-6 rounded hover:bg-[var(--surface-hover)] text-[var(--text-secondary)] hover:text-[var(--text)] transition-colors`,title:n?`Pause`:`Play`,children:n?(0,H.jsx)(_e,{className:`w-3.5 h-3.5`}):(0,H.jsx)(ve,{className:`w-3.5 h-3.5`})}),(0,H.jsxs)(`div`,{className:`flex-1 relative flex items-center`,children:[(0,H.jsx)(`input`,{type:`range`,min:0,max:t,value:e,onChange:c,className:`w-full h-1 appearance-none rounded-full cursor-pointer`,style:{background:`linear-gradient(to right, var(--accent) 0%, var(--accent) ${u}%, var(--border) ${u}%, var(--border) 100%)`,WebkitAppearance:`none`}}),(0,H.jsx)(`style`,{children:` - footer input[type="range"]::-webkit-slider-thumb { - -webkit-appearance: none; - width: 12px; - height: 12px; - border-radius: 50%; - background: var(--accent); - border: 2px solid var(--surface); - cursor: pointer; - box-shadow: 0 0 4px rgba(99, 102, 241, 0.4); - } - footer input[type="range"]::-moz-range-thumb { - width: 12px; - height: 12px; - border-radius: 50%; - background: var(--accent); - border: 2px solid var(--surface); - cursor: pointer; - box-shadow: 0 0 4px rgba(99, 102, 241, 0.4); - } - `})]}),(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] font-mono whitespace-nowrap`,children:wt(i,e)}),(0,H.jsxs)(`span`,{className:`text-[var(--text-muted)] font-mono whitespace-nowrap`,children:[`Event `,e,`/`,t]}),(0,H.jsx)(`div`,{className:`flex items-center gap-0.5`,children:Ct.map(e=>(0,H.jsxs)(`button`,{onClick:()=>s(e),className:U(`px-1.5 py-0.5 rounded text-xs font-mono transition-colors`,r===e?`bg-[var(--accent)] text-white`:`text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]`),children:[e,`×`]},e))})]})}var Et=(0,v.createContext)(null);Et.displayName=`PanelGroupContext`;var Dt={group:`data-panel-group`,groupDirection:`data-panel-group-direction`,groupId:`data-panel-group-id`,panel:`data-panel`,panelCollapsible:`data-panel-collapsible`,panelId:`data-panel-id`,panelSize:`data-panel-size`,resizeHandle:`data-resize-handle`,resizeHandleActive:`data-resize-handle-active`,resizeHandleEnabled:`data-panel-resize-handle-enabled`,resizeHandleId:`data-panel-resize-handle-id`,resizeHandleState:`data-resize-handle-state`},Ot=10,kt=v.useLayoutEffect,At=v.useId,jt=typeof At==`function`?At:()=>null,Mt=0;function Nt(e=null){let t=jt(),n=(0,v.useRef)(e||t||null);return n.current===null&&(n.current=``+ Mt++),e??n.current}function Pt({children:e,className:t=``,collapsedSize:n,collapsible:r,defaultSize:i,forwardedRef:a,id:o,maxSize:s,minSize:c,onCollapse:l,onExpand:u,onResize:d,order:f,style:p,tagName:m=`div`,...h}){let g=(0,v.useContext)(Et);if(g===null)throw Error(`Panel components must be rendered within a PanelGroup container`);let{collapsePanel:_,expandPanel:y,getPanelSize:b,getPanelStyle:x,groupId:S,isPanelCollapsed:C,reevaluatePanelConstraints:w,registerPanel:T,resizePanel:E,unregisterPanel:D}=g,O=Nt(o),k=(0,v.useRef)({callbacks:{onCollapse:l,onExpand:u,onResize:d},constraints:{collapsedSize:n,collapsible:r,defaultSize:i,maxSize:s,minSize:c},id:O,idIsFromProps:o!==void 0,order:f});(0,v.useRef)({didLogMissingDefaultSizeWarning:!1}),kt(()=>{let{callbacks:e,constraints:t}=k.current,a={...t};k.current.id=O,k.current.idIsFromProps=o!==void 0,k.current.order=f,e.onCollapse=l,e.onExpand=u,e.onResize=d,t.collapsedSize=n,t.collapsible=r,t.defaultSize=i,t.maxSize=s,t.minSize=c,(a.collapsedSize!==t.collapsedSize||a.collapsible!==t.collapsible||a.maxSize!==t.maxSize||a.minSize!==t.minSize)&&w(k.current,a)}),kt(()=>{let e=k.current;return T(e),()=>{D(e)}},[f,O,T,D]),(0,v.useImperativeHandle)(a,()=>({collapse:()=>{_(k.current)},expand:e=>{y(k.current,e)},getId(){return O},getSize(){return b(k.current)},isCollapsed(){return C(k.current)},isExpanded(){return!C(k.current)},resize:e=>{E(k.current,e)}}),[_,y,b,C,O,E]);let A=x(k.current,i);return(0,v.createElement)(m,{...h,children:e,className:t,id:O,style:{...A,...p},[Dt.groupId]:S,[Dt.panel]:``,[Dt.panelCollapsible]:r||void 0,[Dt.panelId]:O,[Dt.panelSize]:parseFloat(``+A.flexGrow).toFixed(1)})}var Ft=(0,v.forwardRef)((e,t)=>(0,v.createElement)(Pt,{...e,forwardedRef:t}));Pt.displayName=`Panel`,Ft.displayName=`forwardRef(Panel)`;var It;function Lt(){return It}var Rt=null,zt=!0,Bt=-1,Vt=null;function Ht(e,t){if(t){let e=(t&on)!==0,n=(t&sn)!==0,r=(t&cn)!==0,i=(t&ln)!==0;if(e)return r?`se-resize`:i?`ne-resize`:`e-resize`;if(n)return r?`sw-resize`:i?`nw-resize`:`w-resize`;if(r)return`s-resize`;if(i)return`n-resize`}switch(e){case`horizontal`:return`ew-resize`;case`intersection`:return`move`;case`vertical`:return`ns-resize`}}function Ut(){Vt!==null&&(document.head.removeChild(Vt),Rt=null,Vt=null,Bt=-1)}function Wt(e,t){if(!zt)return;let n=Ht(e,t);if(Rt!==n){if(Rt=n,Vt===null){Vt=document.createElement(`style`);let e=Lt();e&&Vt.setAttribute(`nonce`,e),document.head.appendChild(Vt)}if(Bt>=0){var r;(r=Vt.sheet)==null||r.removeRule(Bt)}Bt=Vt.sheet?.insertRule(`*{cursor: ${n} !important;}`)??-1}}function Gt(e){return e.type===`keydown`}function Kt(e){return e.type.startsWith(`pointer`)}function qt(e){return e.type.startsWith(`mouse`)}function Jt(e){if(Kt(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(qt(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function Yt(){if(typeof matchMedia==`function`)return matchMedia(`(pointer:coarse)`).matches?`coarse`:`fine`}function Xt(e,t,n){return n?e.xt.x&&e.yt.y:e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function Zt(e,t){if(e===t)throw Error(`Cannot compare node with itself`);let n={a:rn(e),b:rn(t)},r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;W(r,`Stacking order can only be calculated for elements with a common ancestor`);let i={a:nn(tn(n.a)),b:nn(tn(n.b))};if(i.a===i.b){let e=r.childNodes,t={a:n.a.at(-1),b:n.b.at(-1)},i=e.length;for(;i--;){let n=e[i];if(n===t.a)return 1;if(n===t.b)return-1}}return Math.sign(i.a-i.b)}var Qt=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function $t(e){let t=getComputedStyle(an(e)??e).display;return t===`flex`||t===`inline-flex`}function en(e){let t=getComputedStyle(e);return!!(t.position===`fixed`||t.zIndex!==`auto`&&(t.position!==`static`||$t(e))||+t.opacity<1||`transform`in t&&t.transform!==`none`||`webkitTransform`in t&&t.webkitTransform!==`none`||`mixBlendMode`in t&&t.mixBlendMode!==`normal`||`filter`in t&&t.filter!==`none`||`webkitFilter`in t&&t.webkitFilter!==`none`||`isolation`in t&&t.isolation===`isolate`||Qt.test(t.willChange)||t.webkitOverflowScrolling===`touch`)}function tn(e){let t=e.length;for(;t--;){let n=e[t];if(W(n,`Missing node`),en(n))return n}return null}function nn(e){return e&&Number(getComputedStyle(e).zIndex)||0}function rn(e){let t=[];for(;e;)t.push(e),e=an(e);return t}function an(e){let{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}var on=1,sn=2,cn=4,ln=8,un=Yt()===`coarse`,dn=[],fn=!1,pn=new Map,mn=new Map,hn=new Set;function gn(e,t,n,r,i){let{ownerDocument:a}=t,o={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:i},s=pn.get(a)??0;return pn.set(a,s+1),hn.add(o),Tn(),function(){mn.delete(e),hn.delete(o);let t=pn.get(a)??1;if(pn.set(a,t-1),Tn(),t===1&&pn.delete(a),dn.includes(o)){let e=dn.indexOf(o);e>=0&&dn.splice(e,1),Cn(),i(`up`,!0,null)}}}function _n(e){let{target:t}=e,{x:n,y:r}=Jt(e);fn=!0,xn({target:t,x:n,y:r}),Tn(),dn.length>0&&(En(`down`,e),e.preventDefault(),bn(t)||e.stopImmediatePropagation())}function vn(e){let{x:t,y:n}=Jt(e);if(fn&&e.buttons===0&&(fn=!1,En(`up`,e)),!fn){let{target:r}=e;xn({target:r,x:t,y:n})}En(`move`,e),Cn(),dn.length>0&&e.preventDefault()}function yn(e){let{target:t}=e,{x:n,y:r}=Jt(e);mn.clear(),fn=!1,dn.length>0&&(e.preventDefault(),bn(t)||e.stopImmediatePropagation()),En(`up`,e),xn({target:t,x:n,y:r}),Cn(),Tn()}function bn(e){let t=e;for(;t;){if(t.hasAttribute(Dt.resizeHandle))return!0;t=t.parentElement}return!1}function xn({target:e,x:t,y:n}){dn.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),hn.forEach(e=>{let{element:i,hitAreaMargins:a}=e,o=i.getBoundingClientRect(),{bottom:s,left:c,right:l,top:u}=o,d=un?a.coarse:a.fine;if(t>=c-d&&t<=l+d&&n>=u-d&&n<=s+d){if(r!==null&&document.contains(r)&&i!==r&&!i.contains(r)&&!r.contains(i)&&Zt(r,i)>0){let e=r,t=!1;for(;e&&!e.contains(i);){if(Xt(e.getBoundingClientRect(),o,!0)){t=!0;break}e=e.parentElement}if(t)return}dn.push(e)}})}function Sn(e,t){mn.set(e,t)}function Cn(){let e=!1,t=!1;dn.forEach(n=>{let{direction:r}=n;r===`horizontal`?e=!0:t=!0});let n=0;mn.forEach(e=>{n|=e}),e&&t?Wt(`intersection`,n):e?Wt(`horizontal`,n):t?Wt(`vertical`,n):Ut()}var wn=new AbortController;function Tn(){wn.abort(),wn=new AbortController;let e={capture:!0,signal:wn.signal};hn.size&&(fn?(dn.length>0&&pn.forEach((t,n)=>{let{body:r}=n;t>0&&(r.addEventListener(`contextmenu`,yn,e),r.addEventListener(`pointerleave`,vn,e),r.addEventListener(`pointermove`,vn,e))}),window.addEventListener(`pointerup`,yn,e),window.addEventListener(`pointercancel`,yn,e)):pn.forEach((t,n)=>{let{body:r}=n;t>0&&(r.addEventListener(`pointerdown`,_n,e),r.addEventListener(`pointermove`,vn,e))}))}function En(e,t){hn.forEach(n=>{let{setResizeHandlerState:r}=n;r(e,dn.includes(n),t)})}function Dn(){let[e,t]=(0,v.useState)(0);return(0,v.useCallback)(()=>t(e=>e+1),[])}function W(e,t){if(!e)throw console.error(t),Error(t)}function On(e,t,n=Ot){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function kn(e,t,n=Ot){return On(e,t,n)===0}function An(e,t,n){return On(e,t,n)===0}function jn(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-t:t)}}}{let r=e<0?s:c,i=n[r];W(i,`No panel constraints found for index ${r}`);let{collapsedSize:a=0,collapsible:o,minSize:l=0}=i;if(o){let n=t[r];if(W(n!=null,`Previous layout not found for panel index ${r}`),An(n,l)){let t=n-a;On(t,Math.abs(e))>0&&(e=e<0?0-t:t)}}}}{let r=e<0?1:-1,i=e<0?c:s,a=0;for(;;){let e=t[i];W(e!=null,`Previous layout not found for panel index ${i}`);let o=Mn({panelConstraints:n,panelIndex:i,size:100})-e;if(a+=o,i+=r,i<0||i>=n.length)break}let o=Math.min(Math.abs(e),Math.abs(a));e=e<0?0-o:o}{let r=e<0?s:c;for(;r>=0&&r=0))break;e<0?r--:r++}}if(jn(i,o))return i;{let r=e<0?c:s,i=t[r];W(i!=null,`Previous layout not found for panel index ${r}`);let a=i+l,u=Mn({panelConstraints:n,panelIndex:r,size:a});if(o[r]=u,!An(u,a)){let t=a-u,r=e<0?c:s;for(;r>=0&&r0?r--:r++}}}return An(o.reduce((e,t)=>t+e,0),100)?o:i}function Pn({layout:e,panelsArray:t,pivotIndices:n}){let r=0,i=100,a=0,o=0,s=n[0];return W(s!=null,`No pivot index found`),t.forEach((e,t)=>{let{constraints:n}=e,{maxSize:c=100,minSize:l=0}=n;t===s?(r=l,i=c):(a+=l,o+=c)}),{valueMax:Math.min(i,100-a),valueMin:Math.max(r,100-o),valueNow:e[s]}}function Fn(e,t=document){return Array.from(t.querySelectorAll(`[${Dt.resizeHandleId}][data-panel-group-id="${e}"]`))}function In(e,t,n=document){return Fn(e,n).findIndex(e=>e.getAttribute(Dt.resizeHandleId)===t)??null}function Ln(e,t,n){let r=In(e,t,n);return r==null?[-1,-1]:[r,r+1]}function Rn(e,t=document){return t instanceof HTMLElement&&t?.dataset?.panelGroupId==e?t:t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`)||null}function zn(e,t=document){return t.querySelector(`[${Dt.resizeHandleId}="${e}"]`)||null}function Bn(e,t,n,r=document){let i=zn(t,r),a=Fn(e,r),o=i?a.indexOf(i):-1;return[n[o]?.id??null,n[o+1]?.id??null]}function Vn({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:i,panelGroupElement:a,setLayout:o}){(0,v.useRef)({didWarnAboutMissingResizeHandle:!1}),kt(()=>{if(!a)return;let e=Fn(n,a);for(let t=0;t{e.forEach((e,t)=>{e.removeAttribute(`aria-controls`),e.removeAttribute(`aria-valuemax`),e.removeAttribute(`aria-valuemin`),e.removeAttribute(`aria-valuenow`)})}},[n,r,i,a]),(0,v.useEffect)(()=>{if(!a)return;let e=t.current;W(e,`Eager values not found`);let{panelDataArray:i}=e;W(Rn(n,a)!=null,`No group found for id "${n}"`);let s=Fn(n,a);W(s,`No resize handles found for group id "${n}"`);let c=s.map(e=>{let t=e.getAttribute(Dt.resizeHandleId);W(t,`Resize handle element has no handle id attribute`);let[s,c]=Bn(n,t,i,a);if(s==null||c==null)return()=>{};let l=e=>{if(!e.defaultPrevented)switch(e.key){case`Enter`:{e.preventDefault();let c=i.findIndex(e=>e.id===s);if(c>=0){let e=i[c];W(e,`No panel data found for index ${c}`);let s=r[c],{collapsedSize:l=0,collapsible:u,minSize:d=0}=e.constraints;if(s!=null&&u){let e=Nn({delta:An(s,l)?d-l:l-s,initialLayout:r,panelConstraints:i.map(e=>e.constraints),pivotIndices:Ln(n,t,a),prevLayout:r,trigger:`keyboard`});r!==e&&o(e)}}break}}};return e.addEventListener(`keydown`,l),()=>{e.removeEventListener(`keydown`,l)}});return()=>{c.forEach(e=>e())}},[a,e,t,n,r,i,o])}function Hn(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.constraints),r=0,i=100;for(let a=0;a{let i=e[r];W(i,`Panel data not found for index ${r}`);let{callbacks:a,constraints:o,id:s}=i,{collapsedSize:c=0,collapsible:l}=o,u=n[s];if(u==null||t!==u){n[s]=t;let{onCollapse:e,onExpand:r,onResize:i}=a;i&&i(t,u),l&&(e||r)&&(r&&(u==null||kn(u,c))&&!kn(t,c)&&r(),e&&(u==null||!kn(u,c))&&kn(t,c)&&e())}})}function Jn(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function Zn(e){try{if(typeof localStorage<`u`)e.getItem=e=>localStorage.getItem(e),e.setItem=(e,t)=>{localStorage.setItem(e,t)};else throw Error(`localStorage not supported in this environment`)}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function Qn(e){return`react-resizable-panels:${e}`}function $n(e){return e.map(e=>{let{constraints:t,id:n,idIsFromProps:r,order:i}=e;return r?n:i?`${i}:${JSON.stringify(t)}`:JSON.stringify(t)}).sort((e,t)=>e.localeCompare(t)).join(`,`)}function er(e,t){try{let n=Qn(e),r=t.getItem(n);if(r){let e=JSON.parse(r);if(typeof e==`object`&&e)return e}}catch{}return null}function tr(e,t,n){return(er(e,n)??{})[$n(t)]??null}function nr(e,t,n,r,i){let a=Qn(e),o=$n(t),s=er(e,i)??{};s[o]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{i.setItem(a,JSON.stringify(s))}catch(e){console.error(e)}}function rr({layout:e,panelConstraints:t}){let n=[...e],r=n.reduce((e,t)=>e+t,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(e=>`${e}%`).join(`, `)}`);if(!An(r,100)&&n.length>0)for(let e=0;e(Zn(ar),ar.getItem(e)),setItem:(e,t)=>{Zn(ar),ar.setItem(e,t)}},or={};function sr({autoSaveId:e=null,children:t,className:n=``,direction:r,forwardedRef:i,id:a=null,onLayout:o=null,keyboardResizeBy:s=null,storage:c=ar,style:l,tagName:u=`div`,...d}){let f=Nt(a),p=(0,v.useRef)(null),[m,h]=(0,v.useState)(null),[g,_]=(0,v.useState)([]),y=Dn(),b=(0,v.useRef)({}),x=(0,v.useRef)(new Map),S=(0,v.useRef)(0),C=(0,v.useRef)({autoSaveId:e,direction:r,dragState:m,id:f,keyboardResizeBy:s,onLayout:o,storage:c}),w=(0,v.useRef)({layout:g,panelDataArray:[],panelDataArrayChanged:!1});(0,v.useRef)({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),(0,v.useImperativeHandle)(i,()=>({getId:()=>C.current.id,getLayout:()=>{let{layout:e}=w.current;return e},setLayout:e=>{let{onLayout:t}=C.current,{layout:n,panelDataArray:r}=w.current,i=rr({layout:e,panelConstraints:r.map(e=>e.constraints)});Hn(n,i)||(_(i),w.current.layout=i,t&&t(i),qn(r,i,b.current))}}),[]),kt(()=>{C.current.autoSaveId=e,C.current.direction=r,C.current.dragState=m,C.current.id=f,C.current.onLayout=o,C.current.storage=c}),Vn({committedValuesRef:C,eagerValuesRef:w,groupId:f,layout:g,panelDataArray:w.current.panelDataArray,setLayout:_,panelGroupElement:p.current}),(0,v.useEffect)(()=>{let{panelDataArray:t}=w.current;if(e){if(g.length===0||g.length!==t.length)return;let n=or[e];n??(n=Xn(nr,ir),or[e]=n);let r=[...t],i=new Map(x.current);n(e,r,i,g,c)}},[e,g,c]),(0,v.useEffect)(()=>{});let T=(0,v.useCallback)(e=>{let{onLayout:t}=C.current,{layout:n,panelDataArray:r}=w.current;if(e.constraints.collapsible){let i=r.map(e=>e.constraints),{collapsedSize:a=0,panelSize:o,pivotIndices:s}=ur(r,e,n);if(W(o!=null,`Panel size not found for panel "${e.id}"`),!kn(o,a)){x.current.set(e.id,o);let c=Nn({delta:lr(r,e)===r.length-1?o-a:a-o,initialLayout:n,panelConstraints:i,pivotIndices:s,prevLayout:n,trigger:`imperative-api`});Jn(n,c)||(_(c),w.current.layout=c,t&&t(c),qn(r,c,b.current))}}},[]),E=(0,v.useCallback)((e,t)=>{let{onLayout:n}=C.current,{layout:r,panelDataArray:i}=w.current;if(e.constraints.collapsible){let a=i.map(e=>e.constraints),{collapsedSize:o=0,panelSize:s=0,minSize:c=0,pivotIndices:l}=ur(i,e,r),u=t??c;if(kn(s,o)){let t=x.current.get(e.id),o=t!=null&&t>=u?t:u,c=Nn({delta:lr(i,e)===i.length-1?s-o:o-s,initialLayout:r,panelConstraints:a,pivotIndices:l,prevLayout:r,trigger:`imperative-api`});Jn(r,c)||(_(c),w.current.layout=c,n&&n(c),qn(i,c,b.current))}}},[]),D=(0,v.useCallback)(e=>{let{layout:t,panelDataArray:n}=w.current,{panelSize:r}=ur(n,e,t);return W(r!=null,`Panel size not found for panel "${e.id}"`),r},[]),O=(0,v.useCallback)((e,t)=>{let{panelDataArray:n}=w.current;return Yn({defaultSize:t,dragState:m,layout:g,panelData:n,panelIndex:lr(n,e)})},[m,g]),k=(0,v.useCallback)(e=>{let{layout:t,panelDataArray:n}=w.current,{collapsedSize:r=0,collapsible:i,panelSize:a}=ur(n,e,t);return W(a!=null,`Panel size not found for panel "${e.id}"`),i===!0&&kn(a,r)},[]),A=(0,v.useCallback)(e=>{let{layout:t,panelDataArray:n}=w.current,{collapsedSize:r=0,collapsible:i,panelSize:a}=ur(n,e,t);return W(a!=null,`Panel size not found for panel "${e.id}"`),!i||On(a,r)>0},[]),j=(0,v.useCallback)(e=>{let{panelDataArray:t}=w.current;t.push(e),t.sort((e,t)=>{let n=e.order,r=t.order;return n==null&&r==null?0:n==null?-1:r==null?1:n-r}),w.current.panelDataArrayChanged=!0,y()},[y]);kt(()=>{if(w.current.panelDataArrayChanged){w.current.panelDataArrayChanged=!1;let{autoSaveId:e,onLayout:t,storage:n}=C.current,{layout:r,panelDataArray:i}=w.current,a=null;if(e){let t=tr(e,i,n);t&&(x.current=new Map(Object.entries(t.expandToSizes)),a=t.layout)}a??=Kn({panelDataArray:i});let o=rr({layout:a,panelConstraints:i.map(e=>e.constraints)});Hn(r,o)||(_(o),w.current.layout=o,t&&t(o),qn(i,o,b.current))}}),kt(()=>{let e=w.current;return()=>{e.layout=[]}},[]);let M=(0,v.useCallback)(e=>{let t=!1,n=p.current;return n&&window.getComputedStyle(n,null).getPropertyValue(`direction`)===`rtl`&&(t=!0),function(n){n.preventDefault();let r=p.current;if(!r)return()=>null;let{direction:i,dragState:a,id:o,keyboardResizeBy:s,onLayout:c}=C.current,{layout:l,panelDataArray:u}=w.current,{initialLayout:d}=a??{},f=Ln(o,e,r),m=Gn(n,e,i,a,s,r),h=i===`horizontal`;h&&t&&(m=-m);let g=u.map(e=>e.constraints),v=Nn({delta:m,initialLayout:d??l,panelConstraints:g,pivotIndices:f,prevLayout:l,trigger:Gt(n)?`keyboard`:`mouse-or-touch`}),y=!Jn(l,v);(Kt(n)||qt(n))&&S.current!=m&&(S.current=m,!y&&m!==0?h?Sn(e,m<0?on:sn):Sn(e,m<0?cn:ln):Sn(e,0)),y&&(_(v),w.current.layout=v,c&&c(v),qn(u,v,b.current))}},[]),N=(0,v.useCallback)((e,t)=>{let{onLayout:n}=C.current,{layout:r,panelDataArray:i}=w.current,a=i.map(e=>e.constraints),{panelSize:o,pivotIndices:s}=ur(i,e,r);W(o!=null,`Panel size not found for panel "${e.id}"`);let c=Nn({delta:lr(i,e)===i.length-1?o-t:t-o,initialLayout:r,panelConstraints:a,pivotIndices:s,prevLayout:r,trigger:`imperative-api`});Jn(r,c)||(_(c),w.current.layout=c,n&&n(c),qn(i,c,b.current))},[]),P=(0,v.useCallback)((e,t)=>{let{layout:n,panelDataArray:r}=w.current,{collapsedSize:i=0,collapsible:a}=t,{collapsedSize:o=0,collapsible:s,maxSize:c=100,minSize:l=0}=e.constraints,{panelSize:u}=ur(r,e,n);u!=null&&(a&&s&&kn(u,i)?kn(i,o)||N(e,o):uc&&N(e,c))},[N]),ee=(0,v.useCallback)((e,t)=>{let{direction:n}=C.current,{layout:r}=w.current;if(!p.current)return;let i=zn(e,p.current);W(i,`Drag handle element not found for id "${e}"`);let a=Un(n,t);h({dragHandleId:e,dragHandleRect:i.getBoundingClientRect(),initialCursorPosition:a,initialLayout:r})},[]),F=(0,v.useCallback)(()=>{h(null)},[]),I=(0,v.useCallback)(e=>{let{panelDataArray:t}=w.current,n=lr(t,e);n>=0&&(t.splice(n,1),delete b.current[e.id],w.current.panelDataArrayChanged=!0,y())},[y]),te=(0,v.useMemo)(()=>({collapsePanel:T,direction:r,dragState:m,expandPanel:E,getPanelSize:D,getPanelStyle:O,groupId:f,isPanelCollapsed:k,isPanelExpanded:A,reevaluatePanelConstraints:P,registerPanel:j,registerResizeHandle:M,resizePanel:N,startDragging:ee,stopDragging:F,unregisterPanel:I,panelGroupElement:p.current}),[T,m,r,E,D,O,f,k,A,P,j,M,N,ee,F,I]),ne={display:`flex`,flexDirection:r===`horizontal`?`row`:`column`,height:`100%`,overflow:`hidden`,width:`100%`};return(0,v.createElement)(Et.Provider,{value:te},(0,v.createElement)(u,{...d,children:t,className:n,id:a,ref:p,style:{...ne,...l},[Dt.group]:``,[Dt.groupDirection]:r,[Dt.groupId]:f}))}var cr=(0,v.forwardRef)((e,t)=>(0,v.createElement)(sr,{...e,forwardedRef:t}));sr.displayName=`PanelGroup`,cr.displayName=`forwardRef(PanelGroup)`;function lr(e,t){return e.findIndex(e=>e===t||e.id===t.id)}function ur(e,t,n){let r=lr(e,t),i=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:i}}function dr({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){(0,v.useEffect)(()=>{if(e||n==null||r==null)return;let i=zn(t,r);if(i==null)return;let a=e=>{if(!e.defaultPrevented)switch(e.key){case`ArrowDown`:case`ArrowLeft`:case`ArrowRight`:case`ArrowUp`:case`End`:case`Home`:e.preventDefault(),n(e);break;case`F6`:{e.preventDefault();let n=i.getAttribute(Dt.groupId);W(n,`No group element found for id "${n}"`);let a=Fn(n,r),o=In(n,t,r);W(o!==null,`No resize element found for id "${t}"`),a[e.shiftKey?o>0?o-1:a.length-1:o+1{i.removeEventListener(`keydown`,a)}},[r,e,t,n])}function fr({children:e=null,className:t=``,disabled:n=!1,hitAreaMargins:r,id:i,onBlur:a,onClick:o,onDragging:s,onFocus:c,onPointerDown:l,onPointerUp:u,style:d={},tabIndex:f=0,tagName:p=`div`,...m}){let h=(0,v.useRef)(null),g=(0,v.useRef)({onClick:o,onDragging:s,onPointerDown:l,onPointerUp:u});(0,v.useEffect)(()=>{g.current.onClick=o,g.current.onDragging=s,g.current.onPointerDown=l,g.current.onPointerUp=u});let _=(0,v.useContext)(Et);if(_===null)throw Error(`PanelResizeHandle components must be rendered within a PanelGroup container`);let{direction:y,groupId:b,registerResizeHandle:x,startDragging:S,stopDragging:C,panelGroupElement:w}=_,T=Nt(i),[E,D]=(0,v.useState)(`inactive`),[O,k]=(0,v.useState)(!1),[A,j]=(0,v.useState)(null),M=(0,v.useRef)({state:E});kt(()=>{M.current.state=E}),(0,v.useEffect)(()=>{if(n)j(null);else{let e=x(T);j(()=>e)}},[n,T,x]);let N=r?.coarse??15,P=r?.fine??5;(0,v.useEffect)(()=>{if(n||A==null)return;let e=h.current;W(e,`Element ref not attached`);let t=!1;return gn(T,e,y,{coarse:N,fine:P},(e,n,r)=>{if(!n){D(`inactive`);return}switch(e){case`down`:{D(`drag`),t=!1,W(r,`Expected event to be defined for "down" action`),S(T,r);let{onDragging:e,onPointerDown:n}=g.current;e?.(!0),n?.();break}case`move`:{let{state:e}=M.current;t=!0,e!==`drag`&&D(`hover`),W(r,`Expected event to be defined for "move" action`),A(r);break}case`up`:{D(`hover`),C();let{onClick:e,onDragging:n,onPointerUp:r}=g.current;n?.(!1),r?.(),t||e?.();break}}})},[N,y,n,P,x,T,A,S,C]),dr({disabled:n,handleId:T,resizeHandler:A,panelGroupElement:w});let ee={touchAction:`none`,userSelect:`none`};return(0,v.createElement)(p,{...m,children:e,className:t,id:i,onBlur:()=>{k(!1),a?.()},onFocus:()=>{k(!0),c?.()},ref:h,role:`separator`,style:{...ee,...d},tabIndex:f,[Dt.groupDirection]:y,[Dt.groupId]:b,[Dt.resizeHandle]:``,[Dt.resizeHandleActive]:E===`drag`?`pointer`:O?`keyboard`:void 0,[Dt.resizeHandleEnabled]:!n,[Dt.resizeHandleId]:T,[Dt.resizeHandleState]:E})}fr.displayName=`PanelResizeHandle`;function pr(e){if(typeof e==`string`||typeof e==`number`)return``+e;let t=``;if(Array.isArray(e))for(let n=0,r;n{}};function hr(){for(var e=0,t=arguments.length,n={},r;e=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error(`unknown type: `+e);return{type:e,name:n}})}gr.prototype=hr.prototype={constructor:gr,on:function(e,t){var n=this._,r=_r(e+``,n),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var n=Array(i),r=0,i,a;r=0&&(t=e.slice(0,n))!==`xmlns`&&(e=e.slice(n+1)),br.hasOwnProperty(t)?{space:br[t],local:e}:e}function Sr(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===`http://www.w3.org/1999/xhtml`&&t.documentElement.namespaceURI===`http://www.w3.org/1999/xhtml`?t.createElement(e):t.createElementNS(n,e)}}function Cr(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function wr(e){var t=xr(e);return(t.local?Cr:Sr)(t)}function Tr(){}function Er(e){return e==null?Tr:function(){return this.querySelector(e)}}function Dr(e){typeof e!=`function`&&(e=Er(e));for(var t=this._groups,n=t.length,r=Array(n),i=0;i=v&&(v=_+1);!(b=g[v])&&++v=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function ri(e){e||=ii;function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}for(var n=this._groups,r=n.length,i=Array(r),a=0;at?1:e>=t?0:NaN}function ai(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function oi(){return Array.from(this)}function si(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?yi:typeof t==`function`?xi:bi)(e,t,n??``)):Ci(this.node(),e)}function Ci(e,t){return e.style.getPropertyValue(t)||vi(e).getComputedStyle(e,null).getPropertyValue(t)}function wi(e){return function(){delete this[e]}}function Ti(e,t){return function(){this[e]=t}}function Ei(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Di(e,t){return arguments.length>1?this.each((t==null?wi:typeof t==`function`?Ei:Ti)(e,t)):this.node()[e]}function Oi(e){return e.trim().split(/^|\s+/)}function G(e){return e.classList||new ki(e)}function ki(e){this._node=e,this._names=Oi(e.getAttribute(`class`)||``)}ki.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute(`class`,this._names.join(` `)))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute(`class`,this._names.join(` `)))},contains:function(e){return this._names.indexOf(e)>=0}};function Ai(e,t){for(var n=G(e),r=-1,i=t.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function aa(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n()=>e;function Da(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:a,x:o,y:s,dx:c,dy:l,dispatch:u}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:s,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:l,enumerable:!0,configurable:!0},_:{value:u}})}Da.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Oa(e){return!e.ctrlKey&&!e.button}function ka(){return this.parentNode}function Aa(e,t){return t??{x:e.x,y:e.y}}function ja(){return navigator.maxTouchPoints||`ontouchstart`in this}function Ma(){var e=Oa,t=ka,n=Aa,r=ja,i={},a=hr(`start`,`drag`,`end`),o=0,s,c,l,u,d=0;function f(e){e.on(`mousedown.drag`,p).filter(r).on(`touchstart.drag`,g).on(`touchmove.drag`,_,ba).on(`touchend.drag touchcancel.drag`,v).style(`touch-action`,`none`).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}function p(n,r){if(!(u||!e.call(this,n,r))){var i=y(this,t.call(this,n,r),n,r,`mouse`);i&&(_a(n.view).on(`mousemove.drag`,m,xa).on(`mouseup.drag`,h,xa),wa(n.view),Sa(n),l=!1,s=n.clientX,c=n.clientY,i(`start`,n))}}function m(e){if(Ca(e),!l){var t=e.clientX-s,n=e.clientY-c;l=t*t+n*n>d}i.mouse(`drag`,e)}function h(e){_a(e.view).on(`mousemove.drag mouseup.drag`,null),Ta(e.view,l),Ca(e),i.mouse(`end`,e)}function g(n,r){if(e.call(this,n,r)){var i=n.changedTouches,a=t.call(this,n,r),o=i.length,s,c;for(s=0;s>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?to(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?to(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Ha.exec(e))?new io(t[1],t[2],t[3],1):(t=Ua.exec(e))?new io(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Wa.exec(e))?to(t[1],t[2],t[3],t[4]):(t=Ga.exec(e))?to(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Ka.exec(e))?uo(t[1],t[2]/100,t[3]/100,1):(t=qa.exec(e))?uo(t[1],t[2]/100,t[3]/100,t[4]):Ja.hasOwnProperty(e)?eo(Ja[e]):e===`transparent`?new io(NaN,NaN,NaN,0):null}function eo(e){return new io(e>>16&255,e>>8&255,e&255,1)}function to(e,t,n,r){return r<=0&&(e=t=n=NaN),new io(e,t,n,r)}function no(e){return e instanceof Fa||(e=$a(e)),e?(e=e.rgb(),new io(e.r,e.g,e.b,e.opacity)):new io}function ro(e,t,n,r){return arguments.length===1?no(e):new io(e,t,n,r??1)}function io(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Na(io,ro,Pa(Fa,{brighter(e){return e=e==null?La:La**+e,new io(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Ia:Ia**+e,new io(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new io(co(this.r),co(this.g),co(this.b),so(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:ao,formatHex:ao,formatHex8:oo,formatRgb:K,toString:K}));function ao(){return`#${lo(this.r)}${lo(this.g)}${lo(this.b)}`}function oo(){return`#${lo(this.r)}${lo(this.g)}${lo(this.b)}${lo((isNaN(this.opacity)?1:this.opacity)*255)}`}function K(){let e=so(this.opacity);return`${e===1?`rgb(`:`rgba(`}${co(this.r)}, ${co(this.g)}, ${co(this.b)}${e===1?`)`:`, ${e})`}`}function so(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function co(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function lo(e){return e=co(e),(e<16?`0`:``)+e.toString(16)}function uo(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new mo(e,t,n,r)}function fo(e){if(e instanceof mo)return new mo(e.h,e.s,e.l,e.opacity);if(e instanceof Fa||(e=$a(e)),!e)return new mo;if(e instanceof mo)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=t===a?(n-r)/s+(n0&&c<1?0:o,new mo(o,s,c,e.opacity)}function po(e,t,n,r){return arguments.length===1?fo(e):new mo(e,t,n,r??1)}function mo(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Na(mo,po,Pa(Fa,{brighter(e){return e=e==null?La:La**+e,new mo(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Ia:Ia**+e,new mo(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new io(_o(e>=240?e-240:e+120,i,r),_o(e,i,r),_o(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new mo(ho(this.h),go(this.s),go(this.l),so(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=so(this.opacity);return`${e===1?`hsl(`:`hsla(`}${ho(this.h)}, ${go(this.s)*100}%, ${go(this.l)*100}%${e===1?`)`:`, ${e})`}`}}));function ho(e){return e=(e||0)%360,e<0?e+360:e}function go(e){return Math.max(0,Math.min(1,e||0))}function _o(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}var vo=e=>()=>e;function yo(e,t){return function(n){return e+n*t}}function bo(e,t,n){return e**=+n,t=t**+n-e,n=1/n,function(r){return(e+r*t)**+n}}function xo(e){return(e=+e)==1?So:function(t,n){return n-t?bo(t,n,e):vo(isNaN(t)?n:t)}}function So(e,t){var n=t-e;return n?yo(e,n):vo(isNaN(e)?t:e)}var Co=(function e(t){var n=xo(t);function r(e,t){var r=n((e=ro(e)).r,(t=ro(t)).r),i=n(e.g,t.g),a=n(e.b,t.b),o=So(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=a(t),e.opacity=o(t),e+``}}return r.gamma=e,r})(1);function wo(e,t){t||=[];var n=e?Math.min(t.length,e.length):0,r=t.slice(),i;return function(a){for(i=0;in&&(a=t.slice(n,a),s[o]?s[o]+=a:s[++o]=a),(r=r[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,c.push({i:o,x:Oo(r,i)})),n=jo.lastIndex;return n180?t+=360:t-e>180&&(e+=360),a.push({i:n.push(i(n)+`rotate(`,null,r)-2,x:Oo(e,t)}))}function s(e,t,n,a){e===t?t&&n.push(i(n)+`skewX(`+t+r):a.push({i:n.push(i(n)+`skewX(`,null,r)-2,x:Oo(e,t)})}function c(e,t,n,r,a,o){if(e!==n||t!==r){var s=a.push(i(a)+`scale(`,null,`,`,null,`)`);o.push({i:s-4,x:Oo(e,n)},{i:s-2,x:Oo(t,r)})}else (n!==1||r!==1)&&a.push(i(a)+`scale(`+n+`,`+r+`)`)}return function(t,n){var r=[],i=[];return t=e(t),n=e(n),a(t.translateX,t.translateY,n.translateX,n.translateY,r,i),o(t.rotate,n.rotate,r,i),s(t.skewX,n.skewX,r,i),c(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,i),t=n=null,function(e){for(var t=-1,n=i.length,a;++t=0&&e._call.call(void 0,t),e=e._next;--Xo}function fs(){rs=(ns=as.now())+is,Xo=Zo=0;try{ds()}finally{Xo=0,ms(),rs=0}}function ps(){var e=as.now(),t=e-ns;t>$o&&(is-=t,ns=e)}function ms(){for(var e,t=es,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:es=n);ts=e,hs(r)}function hs(e){Xo||(Zo&&=clearTimeout(Zo),e-rs>24?(e<1/0&&(Zo=setTimeout(fs,e-as.now()-is)),Qo&&=clearInterval(Qo)):(Qo||=(ns=as.now(),setInterval(ps,$o)),Xo=1,os(fs)))}function gs(e,t,n){var r=new ls;return t=t==null?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}var _s=hr(`start`,`end`,`cancel`,`interrupt`),vs=[];function ys(e,t,n,r,i,a){var o=e.__transition;if(!o)e.__transition={};else if(n in o)return;Cs(e,n,{name:t,index:r,group:i,on:_s,tween:vs,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0})}function bs(e,t){var n=Ss(e,t);if(n.state>0)throw Error(`too late; already scheduled`);return n}function xs(e,t){var n=Ss(e,t);if(n.state>3)throw Error(`too late; already running`);return n}function Ss(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error(`transition not found`);return n}function Cs(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=us(a,0,n.time);function a(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}function o(a){var l,u,d,f;if(n.state!==1)return c();for(l in r)if(f=r[l],f.name===n.name){if(f.state===3)return gs(o);f.state===4?(f.state=6,f.timer.stop(),f.on.call(`interrupt`,e,e.__data__,f.index,f.group),delete r[l]):+l2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(i?`interrupt`:`cancel`,e,e.__data__,r.index,r.group),delete n[o]}a&&delete e.__transition}}function Ts(e){return this.each(function(){ws(this,e)})}function Es(e,t){var n,r;return function(){var i=xs(this,e),a=i.tween;if(a!==n){r=n=a;for(var o=0,s=r.length;o=0&&(e=e.slice(0,t)),!e||e===`start`})}function nc(e,t,n){var r,i,a=tc(t)?bs:xs;return function(){var o=a(this,e),s=o.on;s!==r&&(i=(r=s).copy()).on(t,n),o.on=i}}function rc(e,t){var n=this._id;return arguments.length<2?Ss(this.node(),n).on.on(e):this.each(nc(n,e,t))}function ic(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function ac(){return this.on(`end.remove`,ic(this._id))}function oc(e){var t=this._name,n=this._id;typeof e!=`function`&&(e=Er(e));for(var r=this._groups,i=r.length,a=Array(i),o=0;o()=>e;function Lc(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function Rc(e,t,n){this.k=e,this.x=t,this.y=n}Rc.prototype={constructor:Rc,scale:function(e){return e===1?this:new Rc(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Rc(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return`translate(`+this.x+`,`+this.y+`) scale(`+this.k+`)`}};var zc=new Rc(1,0,0);Bc.prototype=Rc.prototype;function Bc(e){for(;!e.__zoom;)if(!(e=e.parentNode))return zc;return e.__zoom}function Vc(e){e.stopImmediatePropagation()}function Hc(e){e.preventDefault(),e.stopImmediatePropagation()}function Uc(e){return(!e.ctrlKey||e.type===`wheel`)&&!e.button}function Wc(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute(`viewBox`)?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function Gc(){return this.__zoom||zc}function Kc(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function qc(){return navigator.maxTouchPoints||`ontouchstart`in this}function Jc(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],o=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function Yc(){var e=Uc,t=Wc,n=Jc,r=Kc,i=qc,a=[0,1/0],o=[[-1/0,-1/0],[1/0,1/0]],s=250,c=Yo,l=hr(`start`,`zoom`,`end`),u,d,f,p=500,m=150,h=0,g=10;function _(e){e.property(`__zoom`,Gc).on(`wheel.zoom`,w,{passive:!1}).on(`mousedown.zoom`,T).on(`dblclick.zoom`,E).filter(i).on(`touchstart.zoom`,D).on(`touchmove.zoom`,O).on(`touchend.zoom touchcancel.zoom`,k).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}_.transform=function(e,t,n,r){var i=e.selection?e.selection():e;i.property(`__zoom`,Gc),e===i?i.interrupt().each(function(){S(this,arguments).event(r).start().zoom(null,typeof t==`function`?t.apply(this,arguments):t).end()}):x(e,t,n,r)},_.scaleBy=function(e,t,n,r){_.scaleTo(e,function(){return this.__zoom.k*(typeof t==`function`?t.apply(this,arguments):t)},n,r)},_.scaleTo=function(e,r,i,a){_.transform(e,function(){var e=t.apply(this,arguments),a=this.__zoom,s=i==null?b(e):typeof i==`function`?i.apply(this,arguments):i,c=a.invert(s),l=typeof r==`function`?r.apply(this,arguments):r;return n(y(v(a,l),s,c),e,o)},i,a)},_.translateBy=function(e,r,i,a){_.transform(e,function(){return n(this.__zoom.translate(typeof r==`function`?r.apply(this,arguments):r,typeof i==`function`?i.apply(this,arguments):i),t.apply(this,arguments),o)},null,a)},_.translateTo=function(e,r,i,a,s){_.transform(e,function(){var e=t.apply(this,arguments),s=this.__zoom,c=a==null?b(e):typeof a==`function`?a.apply(this,arguments):a;return n(zc.translate(c[0],c[1]).scale(s.k).translate(typeof r==`function`?-r.apply(this,arguments):-r,typeof i==`function`?-i.apply(this,arguments):-i),e,o)},a,s)};function v(e,t){return t=Math.max(a[0],Math.min(a[1],t)),t===e.k?e:new Rc(t,e.x,e.y)}function y(e,t,n){var r=t[0]-n[0]*e.k,i=t[1]-n[1]*e.k;return r===e.x&&i===e.y?e:new Rc(e.k,r,i)}function b(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function x(e,n,r,i){e.on(`start.zoom`,function(){S(this,arguments).event(i).start()}).on(`interrupt.zoom end.zoom`,function(){S(this,arguments).event(i).end()}).tween(`zoom`,function(){var e=this,a=arguments,o=S(e,a).event(i),s=t.apply(e,a),l=r==null?b(s):typeof r==`function`?r.apply(e,a):r,u=Math.max(s[1][0]-s[0][0],s[1][1]-s[0][1]),d=e.__zoom,f=typeof n==`function`?n.apply(e,a):n,p=c(d.invert(l).concat(u/d.k),f.invert(l).concat(u/f.k));return function(e){if(e===1)e=f;else{var t=p(e),n=u/t[2];e=new Rc(n,l[0]-t[0]*n,l[1]-t[1]*n)}o.zoom(null,e)}})}function S(e,t,n){return!n&&e.__zooming||new C(e,t)}function C(e,n){this.that=e,this.args=n,this.active=0,this.sourceEvent=null,this.extent=t.apply(e,n),this.taps=0}C.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit(`start`)),this},zoom:function(e,t){return this.mouse&&e!==`mouse`&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&e!==`touch`&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&e!==`touch`&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit(`zoom`),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit(`end`)),this},emit:function(e){var t=_a(this.that).datum();l.call(e,this.that,new Lc(e,{sourceEvent:this.sourceEvent,target:_,type:e,transform:this.that.__zoom,dispatch:l}),t)}};function w(t,...i){if(!e.apply(this,arguments))return;var s=S(this,i).event(t),c=this.__zoom,l=Math.max(a[0],Math.min(a[1],c.k*2**r.apply(this,arguments))),u=ya(t);if(s.wheel)(s.mouse[0][0]!==u[0]||s.mouse[0][1]!==u[1])&&(s.mouse[1]=c.invert(s.mouse[0]=u)),clearTimeout(s.wheel);else if(c.k===l)return;else s.mouse=[u,c.invert(u)],ws(this),s.start();Hc(t),s.wheel=setTimeout(d,m),s.zoom(`mouse`,n(y(v(c,l),s.mouse[0],s.mouse[1]),s.extent,o));function d(){s.wheel=null,s.end()}}function T(t,...r){if(f||!e.apply(this,arguments))return;var i=t.currentTarget,a=S(this,r,!0).event(t),s=_a(t.view).on(`mousemove.zoom`,d,!0).on(`mouseup.zoom`,p,!0),c=ya(t,i),l=t.clientX,u=t.clientY;wa(t.view),Vc(t),a.mouse=[c,this.__zoom.invert(c)],ws(this),a.start();function d(e){if(Hc(e),!a.moved){var t=e.clientX-l,r=e.clientY-u;a.moved=t*t+r*r>h}a.event(e).zoom(`mouse`,n(y(a.that.__zoom,a.mouse[0]=ya(e,i),a.mouse[1]),a.extent,o))}function p(e){s.on(`mousemove.zoom mouseup.zoom`,null),Ta(e.view,a.moved),Hc(e),a.event(e).end()}}function E(r,...i){if(e.apply(this,arguments)){var a=this.__zoom,c=ya(r.changedTouches?r.changedTouches[0]:r,this),l=a.invert(c),u=a.k*(r.shiftKey?.5:2),d=n(y(v(a,u),c,l),t.apply(this,i),o);Hc(r),s>0?_a(this).transition().duration(s).call(x,d,c,r):_a(this).call(_.transform,d,c,r)}}function D(t,...n){if(e.apply(this,arguments)){var r=t.touches,i=r.length,a=S(this,n,t.changedTouches.length===i).event(t),o,s,c,l;for(Vc(t),s=0;s`[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001`,error002:()=>`It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.`,error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>`The React Flow parent container needs a width and a height to render the graph.`,error005:()=>`Only child nodes can use a parent extent.`,error006:()=>`Can't create edge. An edge needs a source and a target.`,error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e===`source`?n:r}", edge id: ${t}.`,error010:()=>`Handle: No node id found. Make sure to only use a Handle inside a custom Node.`,error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e=`react`)=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>`useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.`,error015:()=>`It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs.`},Zc=[[-1/0,-1/0],[1/0,1/0]],Qc=[`Enter`,` `,`Escape`],$c={"node.a11yDescription.default":`Press enter or space to select a node. Press delete to remove it and escape to cancel.`,"node.a11yDescription.keyboardDisabled":`Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.`,"node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":`Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.`,"controls.ariaLabel":`Control Panel`,"controls.zoomIn.ariaLabel":`Zoom In`,"controls.zoomOut.ariaLabel":`Zoom Out`,"controls.fitView.ariaLabel":`Fit View`,"controls.interactive.ariaLabel":`Toggle Interactivity`,"minimap.ariaLabel":`Mini Map`,"handle.ariaLabel":`Handle`},el;(function(e){e.Strict=`strict`,e.Loose=`loose`})(el||={});var tl;(function(e){e.Free=`free`,e.Vertical=`vertical`,e.Horizontal=`horizontal`})(tl||={});var nl;(function(e){e.Partial=`partial`,e.Full=`full`})(nl||={});var rl={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null},il;(function(e){e.Bezier=`default`,e.Straight=`straight`,e.Step=`step`,e.SmoothStep=`smoothstep`,e.SimpleBezier=`simplebezier`})(il||={});var al;(function(e){e.Arrow=`arrow`,e.ArrowClosed=`arrowclosed`})(al||={});var q;(function(e){e.Left=`left`,e.Top=`top`,e.Right=`right`,e.Bottom=`bottom`})(q||={});var ol={[q.Left]:q.Right,[q.Right]:q.Left,[q.Top]:q.Bottom,[q.Bottom]:q.Top};function sl(e){return e===null?null:e?`valid`:`invalid`}var cl=e=>`id`in e&&`source`in e&&`target`in e,ll=e=>`id`in e&&`position`in e&&!(`source`in e)&&!(`target`in e),ul=e=>`id`in e&&`internals`in e&&!(`source`in e)&&!(`target`in e),dl=(e,t=[0,0])=>{let{width:n,height:r}=Ul(e),i=e.origin??t,a=n*i[0],o=r*i[1];return{x:e.position.x-a,y:e.position.y-o}},fl=(e,t={nodeOrigin:[0,0]})=>e.length===0?{x:0,y:0,width:0,height:0}:Dl(e.reduce((e,n)=>{let r=typeof n==`string`,i=!t.nodeLookup&&!r?n:void 0;return t.nodeLookup&&(i=r?t.nodeLookup.get(n):ul(n)?n:t.nodeLookup.get(n.id)),Tl(e,i?kl(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0})},{x:1/0,y:1/0,x2:-1/0,y2:-1/0})),pl=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(e=>{(t.filter===void 0||t.filter(e))&&(n=Tl(n,kl(e)),r=!0)}),r?Dl(n):{x:0,y:0,width:0,height:0}},ml=(e,t,[n,r,i]=[0,0,1],a=!1,o=!1)=>{let s={...Il(t,[n,r,i]),width:t.width/i,height:t.height/i},c=[];for(let t of e.values()){let{measured:e,selectable:n=!0,hidden:r=!1}=t;if(o&&!n||r)continue;let i=e.width??t.width??t.initialWidth??null,l=e.height??t.height??t.initialHeight??null,u=jl(s,Ol(t)),d=(i??0)*(l??0),f=a&&u>0;(!t.internals.handleBounds||f||u>=d||t.dragging)&&c.push(t)}return c},hl=(e,t)=>{let n=new Set;return e.forEach(e=>{n.add(e.id)}),t.filter(e=>n.has(e.source)||n.has(e.target))};function gl(e,t){let n=new Map,r=t?.nodes?new Set(t.nodes.map(e=>e.id)):null;return e.forEach(e=>{e.measured.width&&e.measured.height&&(t?.includeHiddenNodes||!e.hidden)&&(!r||r.has(e.id))&&n.set(e.id,e)}),n}async function _l({nodes:e,width:t,height:n,panZoom:r,minZoom:i,maxZoom:a},o){if(e.size===0)return Promise.resolve(!0);let s=Bl(pl(gl(e,o)),t,n,o?.minZoom??i,o?.maxZoom??a,o?.padding??.1);return await r.setViewport(s,{duration:o?.duration,ease:o?.ease,interpolate:o?.interpolate}),Promise.resolve(!0)}function vl({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:i,onError:a}){let o=n.get(e),s=o.parentId?n.get(o.parentId):void 0,{x:c,y:l}=s?s.internals.positionAbsolute:{x:0,y:0},u=o.origin??r,d=o.extent||i;if(o.extent===`parent`&&!o.expandParent)if(!s)a?.(`005`,Xc.error005());else{let e=s.measured.width,t=s.measured.height;e&&t&&(d=[[c,l],[c+e,l+t]])}else s&&Hl(o.extent)&&(d=[[o.extent[0][0]+c,o.extent[0][1]+l],[o.extent[1][0]+c,o.extent[1][1]+l]]);let f=Hl(d)?xl(t,d,o.measured):t;return(o.measured.width===void 0||o.measured.height===void 0)&&a?.(`015`,Xc.error015()),{position:{x:f.x-c+(o.measured.width??0)*u[0],y:f.y-l+(o.measured.height??0)*u[1]},positionAbsolute:f}}async function yl({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:i}){let a=new Set(e.map(e=>e.id)),o=[];for(let e of n){if(e.deletable===!1)continue;let t=a.has(e.id),n=!t&&e.parentId&&o.find(t=>t.id===e.parentId);(t||n)&&o.push(e)}let s=new Set(t.map(e=>e.id)),c=r.filter(e=>e.deletable!==!1),l=hl(o,c);for(let e of c)s.has(e.id)&&!l.find(t=>t.id===e.id)&&l.push(e);if(!i)return{edges:l,nodes:o};let u=await i({nodes:o,edges:l});return typeof u==`boolean`?u?{edges:l,nodes:o}:{edges:[],nodes:[]}:u}var bl=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),xl=(e={x:0,y:0},t,n)=>({x:bl(e.x,t[0][0],t[1][0]-(n?.width??0)),y:bl(e.y,t[0][1],t[1][1]-(n?.height??0))});function Sl(e,t,n){let{width:r,height:i}=Ul(n),{x:a,y:o}=n.internals.positionAbsolute;return xl(e,[[a,o],[a+r,o+i]],t)}var Cl=(e,t,n)=>en?-bl(Math.abs(e-n),1,t)/t:0,wl=(e,t,n=15,r=40)=>[Cl(e.x,r,t.width-r)*n,Cl(e.y,r,t.height-r)*n],Tl=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),El=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Dl=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Ol=(e,t=[0,0])=>{let{x:n,y:r}=ul(e)?e.internals.positionAbsolute:dl(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},kl=(e,t=[0,0])=>{let{x:n,y:r}=ul(e)?e.internals.positionAbsolute:dl(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},Al=(e,t)=>Dl(Tl(El(e),El(t))),jl=(e,t)=>{let n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},Ml=e=>Nl(e.width)&&Nl(e.height)&&Nl(e.x)&&Nl(e.y),Nl=e=>!isNaN(e)&&isFinite(e),Pl=(e,t)=>{},Fl=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Il=({x:e,y:t},[n,r,i],a=!1,o=[1,1])=>{let s={x:(e-n)/i,y:(t-r)/i};return a?Fl(s,o):s},Ll=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r});function Rl(e,t){if(typeof e==`number`)return Math.floor((t-t/(1+e))*.5);if(typeof e==`string`&&e.endsWith(`px`)){let t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if(typeof e==`string`&&e.endsWith(`%`)){let n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function J(e,t,n){if(typeof e==`string`||typeof e==`number`){let r=Rl(e,n),i=Rl(e,t);return{top:r,right:i,bottom:r,left:i,x:i*2,y:r*2}}if(typeof e==`object`){let r=Rl(e.top??e.y??0,n),i=Rl(e.bottom??e.y??0,n),a=Rl(e.left??e.x??0,t),o=Rl(e.right??e.x??0,t);return{top:r,right:o,bottom:i,left:a,x:a+o,y:r+i}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function zl(e,t,n,r,i,a){let{x:o,y:s}=Ll(e,[t,n,r]),{x:c,y:l}=Ll({x:e.x+e.width,y:e.y+e.height},[t,n,r]),u=i-c,d=a-l;return{left:Math.floor(o),top:Math.floor(s),right:Math.floor(u),bottom:Math.floor(d)}}var Bl=(e,t,n,r,i,a)=>{let o=J(a,t,n),s=(t-o.x)/e.width,c=(n-o.y)/e.height,l=bl(Math.min(s,c),r,i),u=e.x+e.width/2,d=e.y+e.height/2,f=t/2-u*l,p=n/2-d*l,m=zl(e,f,p,l,t,n),h={left:Math.min(m.left-o.left,0),top:Math.min(m.top-o.top,0),right:Math.min(m.right-o.right,0),bottom:Math.min(m.bottom-o.bottom,0)};return{x:f-h.left+h.right,y:p-h.top+h.bottom,zoom:l}},Vl=()=>typeof navigator<`u`&&navigator?.userAgent?.indexOf(`Mac`)>=0;function Hl(e){return e!=null&&e!==`parent`}function Ul(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Wl(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function Gl(e,t={width:0,height:0},n,r,i){let a={...e},o=r.get(n);if(o){let e=o.origin||i;a.x+=o.internals.positionAbsolute.x-(t.width??0)*e[0],a.y+=o.internals.positionAbsolute.y-(t.height??0)*e[1]}return a}function Kl(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ql(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function Jl(e){return{...$c,...e||{}}}function Yl(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:i}){let{x:a,y:o}=tu(e),s=Il({x:a-(i?.left??0),y:o-(i?.top??0)},r),{x:c,y:l}=n?Fl(s,t):s;return{xSnapped:c,ySnapped:l,...s}}var Xl=e=>({width:e.offsetWidth,height:e.offsetHeight}),Zl=e=>e?.getRootNode?.()||window?.document,Ql=[`INPUT`,`SELECT`,`TEXTAREA`];function $l(e){let t=e.composedPath?.()?.[0]||e.target;return t?.nodeType===1?Ql.includes(t.nodeName)||t.hasAttribute(`contenteditable`)||!!t.closest(`.nokey`):!1}var eu=e=>`clientX`in e,tu=(e,t)=>{let n=eu(e),r=n?e.clientX:e.touches?.[0].clientX,i=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:i-(t?.top??0)}},nu=(e,t,n,r,i)=>{let a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...Xl(t)}})};function ru({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:a,targetControlX:o,targetControlY:s}){let c=e*.125+i*.375+o*.375+n*.125,l=t*.125+a*.375+s*.375+r*.125;return[c,l,Math.abs(c-e),Math.abs(l-t)]}function iu(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function au({pos:e,x1:t,y1:n,x2:r,y2:i,c:a}){switch(e){case q.Left:return[t-iu(t-r,a),n];case q.Right:return[t+iu(r-t,a),n];case q.Top:return[t,n-iu(n-i,a)];case q.Bottom:return[t,n+iu(i-n,a)]}}function ou({sourceX:e,sourceY:t,sourcePosition:n=q.Bottom,targetX:r,targetY:i,targetPosition:a=q.Top,curvature:o=.25}){let[s,c]=au({pos:n,x1:e,y1:t,x2:r,y2:i,c:o}),[l,u]=au({pos:a,x1:r,y1:i,x2:e,y2:t,c:o}),[d,f,p,m]=ru({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:s,sourceControlY:c,targetControlX:l,targetControlY:u});return[`M${e},${t} C${s},${c} ${l},${u} ${r},${i}`,d,f,p,m]}function su({sourceX:e,sourceY:t,targetX:n,targetY:r}){let i=Math.abs(n-e)/2,a=n0}var uu=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||``}-${n}${r||``}`,du=(e,t)=>t.some(t=>t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle)),fu=(e,t,n={})=>{if(!e.source||!e.target)return Xc.error006(),t;let r=n.getEdgeId||uu,i;return i=cl(e)?{...e}:{...e,id:r(e)},du(i,t)?t:(i.sourceHandle===null&&delete i.sourceHandle,i.targetHandle===null&&delete i.targetHandle,t.concat(i))};function pu({sourceX:e,sourceY:t,targetX:n,targetY:r}){let[i,a,o,s]=su({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,a,o,s]}var mu={[q.Left]:{x:-1,y:0},[q.Right]:{x:1,y:0},[q.Top]:{x:0,y:-1},[q.Bottom]:{x:0,y:1}},hu=({source:e,sourcePosition:t=q.Bottom,target:n})=>t===q.Left||t===q.Right?e.xMath.sqrt((t.x-e.x)**2+(t.y-e.y)**2);function _u({source:e,sourcePosition:t=q.Bottom,target:n,targetPosition:r=q.Top,center:i,offset:a,stepPosition:o}){let s=mu[t],c=mu[r],l={x:e.x+s.x*a,y:e.y+s.y*a},u={x:n.x+c.x*a,y:n.y+c.y*a},d=hu({source:l,sourcePosition:t,target:u}),f=d.x===0?`y`:`x`,p=d[f],m=[],h,g,_={x:0,y:0},v={x:0,y:0},[,,y,b]=su({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(s[f]*c[f]===-1){f===`x`?(h=i.x??l.x+(u.x-l.x)*o,g=i.y??(l.y+u.y)/2):(h=i.x??(l.x+u.x)/2,g=i.y??l.y+(u.y-l.y)*o);let e=[{x:h,y:l.y},{x:h,y:u.y}],t=[{x:l.x,y:g},{x:u.x,y:g}];m=s[f]===p?f===`x`?e:t:f===`x`?t:e}else{let i=[{x:l.x,y:u.y}],o=[{x:u.x,y:l.y}];if(m=f===`x`?s.x===p?o:i:s.y===p?i:o,t===r){let t=Math.abs(e[f]-n[f]);if(t<=a){let r=Math.min(a-1,a-t);s[f]===p?_[f]=(l[f]>e[f]?-1:1)*r:v[f]=(u[f]>n[f]?-1:1)*r}}if(t!==r){let e=f===`x`?`y`:`x`,t=s[f]===c[e],n=l[e]>u[e],r=l[e]=Math.max(Math.abs(d.y-m[0].y),Math.abs(y.y-m[0].y))?(h=(d.x+y.x)/2,g=m[0].y):(h=m[0].x,g=(d.y+y.y)/2)}return[[e,{x:l.x+_.x,y:l.y+_.y},...m,{x:u.x+v.x,y:u.y+v.y},n],h,g,y,b]}function vu(e,t,n,r){let i=Math.min(gu(e,t)/2,gu(t,n)/2,r),{x:a,y:o}=t;if(e.x===a&&a===n.x||e.y===o&&o===n.y)return`L${a} ${o}`;if(e.y===o){let t=e.x{let r=``;return r=n>0&&ne.id===t):e[0])||null}function Tu(e,t){return e?typeof e==`string`?e:`${t?`${t}__`:``}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join(`&`)}`:``}function Eu(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:i}){let a=new Set;return e.reduce((e,o)=>([o.markerStart||r,o.markerEnd||i].forEach(r=>{if(r&&typeof r==`object`){let i=Tu(r,t);a.has(i)||(e.push({id:i,color:r.color||n,...r}),a.add(i))}}),e),[]).sort((e,t)=>e.id.localeCompare(t.id))}var Du=1e3,Ou=10,ku={nodeOrigin:[0,0],nodeExtent:Zc,elevateNodesOnSelect:!0,zIndexMode:`basic`,defaults:{}},Au={...ku,checkEquality:!0};function ju(e,t){let n={...e};for(let e in t)t[e]!==void 0&&(n[e]=t[e]);return n}function Mu(e,t,n){let r=ju(ku,n);for(let n of e.values())if(n.parentId)Lu(n,e,t,r);else{let e=xl(dl(n,r.nodeOrigin),Hl(n.extent)?n.extent:r.nodeExtent,Ul(n));n.internals.positionAbsolute=e}}function Nu(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;let n=[],r=[];for(let t of e.handles){let i={id:t.id,width:t.width??1,height:t.height??1,nodeId:e.id,x:t.x,y:t.y,position:t.position,type:t.type};t.type===`source`?n.push(i):t.type===`target`&&r.push(i)}return{source:n,target:r}}function Pu(e){return e===`manual`}function Fu(e,t,n,r={}){let i=ju(Au,r),a={i:0},o=new Map(t),s=i?.elevateNodesOnSelect&&!Pu(i.zIndexMode)?Du:0,c=e.length>0;t.clear(),n.clear();for(let l of e){let e=o.get(l.id);if(i.checkEquality&&l===e?.internals.userNode)t.set(l.id,e);else{let n=xl(dl(l,i.nodeOrigin),Hl(l.extent)?l.extent:i.nodeExtent,Ul(l));e={...i.defaults,...l,measured:{width:l.measured?.width,height:l.measured?.height},internals:{positionAbsolute:n,handleBounds:Nu(l,e),z:Ru(l,s,i.zIndexMode),userNode:l}},t.set(l.id,e)}(e.measured===void 0||e.measured.width===void 0||e.measured.height===void 0)&&!e.hidden&&(c=!1),l.parentId&&Lu(e,t,n,r,a)}return c}function Iu(e,t){if(!e.parentId)return;let n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function Lu(e,t,n,r,i){let{elevateNodesOnSelect:a,nodeOrigin:o,nodeExtent:s,zIndexMode:c}=ju(ku,r),l=e.parentId,u=t.get(l);if(!u){console.warn(`Parent node ${l} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}Iu(e,n),i&&!u.parentId&&u.internals.rootParentIndex===void 0&&c===`auto`&&(u.internals.rootParentIndex=++i.i,u.internals.z=u.internals.z+i.i*Ou),i&&u.internals.rootParentIndex!==void 0&&(i.i=u.internals.rootParentIndex);let{x:d,y:f,z:p}=zu(e,u,o,s,a&&!Pu(c)?Du:0,c),{positionAbsolute:m}=e.internals,h=d!==m.x||f!==m.y;(h||p!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:h?{x:d,y:f}:m,z:p}})}function Ru(e,t,n){let r=Nl(e.zIndex)?e.zIndex:0;return Pu(n)?r:r+(e.selected?t:0)}function zu(e,t,n,r,i,a){let{x:o,y:s}=t.internals.positionAbsolute,c=Ul(e),l=dl(e,n),u=Hl(e.extent)?xl(l,e.extent,c):l,d=xl({x:o+u.x,y:s+u.y},r,c);e.extent===`parent`&&(d=Sl(d,c,t));let f=Ru(e,i,a),p=t.internals.z??0;return{x:d.x,y:d.y,z:p>=f?p+1:f}}function Bu(e,t,n,r=[0,0]){let i=[],a=new Map;for(let n of e){let e=t.get(n.parentId);if(!e)continue;let r=Al(a.get(n.parentId)?.expandedRect??Ol(e),n.rect);a.set(n.parentId,{expandedRect:r,parent:e})}return a.size>0&&a.forEach(({expandedRect:t,parent:a},o)=>{let s=a.internals.positionAbsolute,c=Ul(a),l=a.origin??r,u=t.x0||d>0||m||h)&&(i.push({id:o,type:`position`,position:{x:a.position.x-u+m,y:a.position.y-d+h}}),n.get(o)?.forEach(t=>{e.some(e=>e.id===t.id)||i.push({id:t.id,type:`position`,position:{x:t.position.x+u,y:t.position.y+d}})})),(c.width0){let e=Bu(f,t,n,i);l.push(...e)}return{changes:l,updatedInternals:c}}async function Hu({delta:e,panZoom:t,transform:n,translateExtent:r,width:i,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);let o=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[i,a]],r),s=!!o&&(o.x!==n[0]||o.y!==n[1]||o.k!==n[2]);return Promise.resolve(s)}function Uu(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function Wu(e,t,n){e.clear(),t.clear();for(let r of n){let{source:n,target:i,sourceHandle:a=null,targetHandle:o=null}=r,s={edgeId:r.id,source:n,target:i,sourceHandle:a,targetHandle:o},c=`${n}-${a}--${i}-${o}`;Uu(`source`,s,`${i}-${o}--${n}-${a}`,e,n,a),Uu(`target`,s,c,e,i,o),t.set(r.id,r)}}function Gu(e,t){if(!e.parentId)return!1;let n=t.get(e.parentId);return n?n.selected?!0:Gu(n,t):!1}function Ku(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function qu(e,t,n,r){let i=new Map;for(let[a,o]of e)if((o.selected||o.id===r)&&(!o.parentId||!Gu(o,e))&&(o.draggable||t&&o.draggable===void 0)){let t=e.get(a);t&&i.set(a,{id:a,position:t.position||{x:0,y:0},distance:{x:n.x-t.internals.positionAbsolute.x,y:n.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return i}function Ju({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){let i=[];for(let[e,a]of t){let t=n.get(e)?.internals.userNode;t&&i.push({...t,position:a.position,dragging:r})}if(!e)return[i[0],i];let a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:i[0],i]}function Yu({dragItems:e,snapGrid:t,x:n,y:r}){let i=e.values().next().value;if(!i)return null;let a={x:n-i.distance.x,y:r-i.distance.y},o=Fl(a,t);return{x:o.x-a.x,y:o.y-a.y}}function Xu({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:i}){let a={x:null,y:null},o=0,s=new Map,c=!1,l={x:0,y:0},u=null,d=!1,f=null,p=!1,m=!1,h=null;function g({noDragClassName:g,handleSelector:_,domNode:v,isSelectable:y,nodeId:b,nodeClickDistance:x=0}){f=_a(v);function S({x:e,y:n}){let{nodeLookup:i,nodeExtent:o,snapGrid:c,snapToGrid:l,nodeOrigin:u,onNodeDrag:d,onSelectionDrag:f,onError:p,updateNodePositions:g}=t();a={x:e,y:n};let _=!1,v=s.size>1,y=v&&o?El(pl(s)):null,x=v&&l?Yu({dragItems:s,snapGrid:c,x:e,y:n}):null;for(let[t,r]of s){if(!i.has(t))continue;let a={x:e-r.distance.x,y:n-r.distance.y};l&&(a=x?{x:Math.round(a.x+x.x),y:Math.round(a.y+x.y)}:Fl(a,c));let s=null;if(v&&o&&!r.extent&&y){let{positionAbsolute:e}=r.internals,t=e.x-y.x+o[0][0],n=e.x+r.measured.width-y.x2+o[1][0],i=e.y-y.y+o[0][1],a=e.y+r.measured.height-y.y2+o[1][1];s=[[t,i],[n,a]]}let{position:d,positionAbsolute:f}=vl({nodeId:t,nextPosition:a,nodeLookup:i,nodeExtent:s||o,nodeOrigin:u,onError:p});_=_||r.position.x!==d.x||r.position.y!==d.y,r.position=d,r.internals.positionAbsolute=f}if(m||=_,_&&(g(s,!0),h&&(r||d||!b&&f))){let[e,t]=Ju({nodeId:b,dragItems:s,nodeLookup:i});r?.(h,s,e,t),d?.(h,e,t),b||f?.(h,t)}}async function C(){if(!u)return;let{transform:e,panBy:n,autoPanSpeed:r,autoPanOnNodeDrag:i}=t();if(!i){c=!1,cancelAnimationFrame(o);return}let[s,d]=wl(l,u,r);(s!==0||d!==0)&&(a.x=(a.x??0)-s/e[2],a.y=(a.y??0)-d/e[2],await n({x:s,y:d})&&S(a)),o=requestAnimationFrame(C)}function w(r){let{nodeLookup:i,multiSelectionActive:o,nodesDraggable:c,transform:l,snapGrid:f,snapToGrid:p,selectNodesOnDrag:m,onNodeDragStart:h,onSelectionDragStart:g,unselectNodesAndEdges:_}=t();d=!0,(!m||!y)&&!o&&b&&(i.get(b)?.selected||_()),y&&m&&b&&e?.(b);let v=Yl(r.sourceEvent,{transform:l,snapGrid:f,snapToGrid:p,containerBounds:u});if(a=v,s=qu(i,c,v,b),s.size>0&&(n||h||!b&&g)){let[e,t]=Ju({nodeId:b,dragItems:s,nodeLookup:i});n?.(r.sourceEvent,s,e,t),h?.(r.sourceEvent,e,t),b||g?.(r.sourceEvent,t)}}let T=Ma().clickDistance(x).on(`start`,e=>{let{domNode:n,nodeDragThreshold:r,transform:i,snapGrid:o,snapToGrid:s}=t();u=n?.getBoundingClientRect()||null,p=!1,m=!1,h=e.sourceEvent,r===0&&w(e),a=Yl(e.sourceEvent,{transform:i,snapGrid:o,snapToGrid:s,containerBounds:u}),l=tu(e.sourceEvent,u)}).on(`drag`,e=>{let{autoPanOnNodeDrag:n,transform:r,snapGrid:i,snapToGrid:o,nodeDragThreshold:f,nodeLookup:m}=t(),g=Yl(e.sourceEvent,{transform:r,snapGrid:i,snapToGrid:o,containerBounds:u});if(h=e.sourceEvent,(e.sourceEvent.type===`touchmove`&&e.sourceEvent.touches.length>1||b&&!m.has(b))&&(p=!0),!p){if(!c&&n&&d&&(c=!0,C()),!d){let t=tu(e.sourceEvent,u),n=t.x-l.x,r=t.y-l.y;Math.sqrt(n*n+r*r)>f&&w(e)}(a.x!==g.xSnapped||a.y!==g.ySnapped)&&s&&d&&(l=tu(e.sourceEvent,u),S(g))}}).on(`end`,e=>{if(!(!d||p)&&(c=!1,d=!1,cancelAnimationFrame(o),s.size>0)){let{nodeLookup:n,updateNodePositions:r,onNodeDragStop:a,onSelectionDragStop:o}=t();if(m&&=(r(s,!1),!1),i||a||!b&&o){let[t,r]=Ju({nodeId:b,dragItems:s,nodeLookup:n,dragging:!1});i?.(e.sourceEvent,s,t,r),a?.(e.sourceEvent,t,r),b||o?.(e.sourceEvent,r)}}}).filter(e=>{let t=e.target;return!e.button&&(!g||!Ku(t,`.${g}`,v))&&(!_||Ku(t,_,v))});f.call(T)}function _(){f?.on(`.drag`,null)}return{update:g,destroy:_}}function Zu(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())jl(i,Ol(e))>0&&r.push(e);return r}var Qu=250;function $u(e,t,n,r){let i=[],a=1/0,o=Zu(e,n,t+Qu);for(let n of o){let o=[...n.internals.handleBounds?.source??[],...n.internals.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=Cu(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function ed(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===`strict`?o.internals.handleBounds?.[t]:[...o.internals.handleBounds?.source??[],...o.internals.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...Cu(o,c,c.position,!0)}:c}function td(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function nd(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}var rd=()=>!0;function id(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:i,edgeUpdaterType:a,isTarget:o,domNode:s,nodeLookup:c,lib:l,autoPanOnConnect:u,flowId:d,panBy:f,cancelConnection:p,onConnectStart:m,onConnect:h,onConnectEnd:g,isValidConnection:_=rd,onReconnectEnd:v,updateConnection:y,getTransform:b,getFromHandle:x,autoPanSpeed:S,dragThreshold:C=1,handleDomNode:w}){let T=Zl(e.target),E=0,D,{x:O,y:k}=tu(e),A=td(a,w),j=s?.getBoundingClientRect(),M=!1;if(!j||!A)return;let N=ed(i,A,r,c,t);if(!N)return;let P=tu(e,j),ee=!1,F=null,I=!1,te=null;function ne(){if(!u||!j)return;let[e,t]=wl(P,j,S);f({x:e,y:t}),E=requestAnimationFrame(ne)}let re={...N,nodeId:i,type:A,position:N.position},ie=c.get(i),L={inProgress:!0,isValid:null,from:Cu(ie,re,q.Left,!0),fromHandle:re,fromPosition:re.position,fromNode:ie,to:P,toHandle:null,toPosition:ol[re.position],toNode:null,pointer:P};function ae(){M=!0,y(L),m?.(e,{nodeId:i,handleId:r,handleType:A})}C===0&&ae();function oe(e){if(!M){let{x:t,y:n}=tu(e),r=t-O,i=n-k;if(!(r*r+i*i>C*C))return;ae()}if(!x()||!re){se(e);return}let a=b();P=tu(e,j),D=$u(Il(P,a,!1,[1,1]),n,c,re),ee||=(ne(),!0);let s=ad(e,{handle:D,connectionMode:t,fromNodeId:i,fromHandleId:r,fromType:o?`target`:`source`,isValidConnection:_,doc:T,lib:l,flowId:d,nodeLookup:c});te=s.handleDomNode,F=s.connection,I=nd(!!D,s.isValid);let u=c.get(i),f=u?Cu(u,re,q.Left,!0):L.from,p={...L,from:f,isValid:I,to:s.toHandle&&I?Ll({x:s.toHandle.x,y:s.toHandle.y},a):P,toHandle:s.toHandle,toPosition:I&&s.toHandle?s.toHandle.position:ol[re.position],toNode:s.toHandle?c.get(s.toHandle.nodeId):null,pointer:P};y(p),L=p}function se(e){if(!(`touches`in e&&e.touches.length>0)){if(M){(D||te)&&F&&I&&h?.(F);let{inProgress:t,...n}=L,r={...n,toPosition:L.toHandle?L.toPosition:null};g?.(e,r),a&&v?.(e,r)}p(),cancelAnimationFrame(E),ee=!1,I=!1,F=null,te=null,T.removeEventListener(`mousemove`,oe),T.removeEventListener(`mouseup`,se),T.removeEventListener(`touchmove`,oe),T.removeEventListener(`touchend`,se)}}T.addEventListener(`mousemove`,oe),T.addEventListener(`mouseup`,se),T.addEventListener(`touchmove`,oe),T.addEventListener(`touchend`,se)}function ad(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=rd,nodeLookup:u}){let d=a===`target`,f=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=tu(e),h=o.elementFromPoint(p,m),g=h?.classList.contains(`${s}-flow__handle`)?h:f,_={handleDomNode:g,isValid:!1,connection:null,toHandle:null};if(g){let e=td(void 0,g),t=g.getAttribute(`data-nodeid`),a=g.getAttribute(`data-handleid`),o=g.classList.contains(`connectable`),s=g.classList.contains(`connectableend`);if(!t||!e)return _;let c={source:d?t:r,sourceHandle:d?a:i,target:d?r:t,targetHandle:d?i:a};_.connection=c,_.isValid=o&&s&&(n===el.Strict?d&&e===`source`||!d&&e===`target`:t!==r||a!==i)&&l(c),_.toHandle=ed(t,e,a,u,n,!0)}return _}var od={onPointerDown:id,isValid:ad};function sd({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){let i=_a(e);function a({translateExtent:e,width:a,height:o,zoomStep:s=1,pannable:c=!0,zoomable:l=!0,inversePan:u=!1}){let d=e=>{if(e.sourceEvent.type!==`wheel`||!t)return;let r=n(),i=e.sourceEvent.ctrlKey&&Vl()?10:1,a=-e.sourceEvent.deltaY*(e.sourceEvent.deltaMode===1?.05:e.sourceEvent.deltaMode?1:.002)*s,o=r[2]*2**(a*i);t.scaleTo(o)},f=[0,0],p=Yc().on(`start`,e=>{(e.sourceEvent.type===`mousedown`||e.sourceEvent.type===`touchstart`)&&(f=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])}).on(`zoom`,c?i=>{let s=n();if(i.sourceEvent.type!==`mousemove`&&i.sourceEvent.type!==`touchmove`||!t)return;let c=[i.sourceEvent.clientX??i.sourceEvent.touches[0].clientX,i.sourceEvent.clientY??i.sourceEvent.touches[0].clientY],l=[c[0]-f[0],c[1]-f[1]];f=c;let d=r()*Math.max(s[2],Math.log(s[2]))*(u?-1:1),p={x:s[0]-l[0]*d,y:s[1]-l[1]*d},m=[[0,0],[a,o]];t.setViewportConstrained({x:p.x,y:p.y,zoom:s[2]},m,e)}:null).on(`zoom.wheel`,l?d:null);i.call(p,{})}function o(){i.on(`zoom`,null)}return{update:a,destroy:o,pointer:ya}}var cd=e=>({x:e.x,y:e.y,zoom:e.k}),ld=({x:e,y:t,zoom:n})=>zc.translate(e,t).scale(n),ud=(e,t)=>e.target.closest(`.${t}`),dd=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),fd=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,pd=(e,t=0,n=fd,r=()=>{})=>{let i=typeof t==`number`&&t>0;return i||r(),i?e.transition().duration(t).ease(n).on(`end`,r):e},md=e=>{let t=e.ctrlKey&&Vl()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function hd({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:i,panOnScrollSpeed:a,zoomOnPinch:o,onPanZoomStart:s,onPanZoom:c,onPanZoomEnd:l}){return u=>{if(ud(u,t))return u.ctrlKey&&u.preventDefault(),!1;u.preventDefault(),u.stopImmediatePropagation();let d=n.property(`__zoom`).k||1;if(u.ctrlKey&&o){let e=ya(u),t=d*2**md(u);r.scaleTo(n,t,e,u);return}let f=u.deltaMode===1?20:1,p=i===tl.Vertical?0:u.deltaX*f,m=i===tl.Horizontal?0:u.deltaY*f;!Vl()&&u.shiftKey&&i!==tl.Vertical&&(p=u.deltaY*f,m=0),r.translateBy(n,-(p/d)*a,-(m/d)*a,{internal:!0});let h=cd(n.property(`__zoom`));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(u,h),e.panScrollTimeout=setTimeout(()=>{l?.(u,h),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,s?.(u,h))}}function gd({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,i){let a=r.type===`wheel`,o=!t&&a&&!r.ctrlKey,s=ud(r,e);if(r.ctrlKey&&a&&s&&r.preventDefault(),o||s)return null;r.preventDefault(),n.call(this,r,i)}}function _d({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;let i=cd(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=i,r.sourceEvent?.type===`mousedown`&&t(!0),n&&n?.(r.sourceEvent,i)}}function vd({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:i}){return a=>{e.usedRightMouseButton=!!(n&&dd(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),i&&!a.sourceEvent?.internal&&i?.(a.sourceEvent,cd(a.transform))}}function yd({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:i,onPaneContextMenu:a}){return o=>{if(!o.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&dd(t,e.mouseButton??0)&&!e.usedRightMouseButton&&o.sourceEvent&&a(o.sourceEvent),e.usedRightMouseButton=!1,r(!1),i)){let t=cd(o.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{i?.(o.sourceEvent,t)},n?150:0)}}}function bd({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:i,zoomOnDoubleClick:a,userSelectionActive:o,noWheelClassName:s,noPanClassName:c,lib:l,connectionInProgress:u}){return d=>{let f=e||t,p=n&&d.ctrlKey,m=d.type===`wheel`;if(d.button===1&&d.type===`mousedown`&&(ud(d,`${l}-flow__node`)||ud(d,`${l}-flow__edge`)))return!0;if(!r&&!f&&!i&&!a&&!n||o||u&&!m||ud(d,s)&&m||ud(d,c)&&(!m||i&&m&&!e)||!n&&d.ctrlKey&&m)return!1;if(!n&&d.type===`touchstart`&&d.touches?.length>1)return d.preventDefault(),!1;if(!f&&!i&&!p&&m||!r&&(d.type===`mousedown`||d.type===`touchstart`)||Array.isArray(r)&&!r.includes(d.button)&&d.type===`mousedown`)return!1;let h=Array.isArray(r)&&r.includes(d.button)||!d.button||d.button<=1;return(!d.ctrlKey||m)&&h}}function xd({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:i,onPanZoom:a,onPanZoomStart:o,onPanZoomEnd:s,onDraggingChange:c}){let l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{x:0,y:0,zoom:0},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},u=e.getBoundingClientRect(),d=Yc().scaleExtent([t,n]).translateExtent(r),f=_a(e).call(d);v({x:i.x,y:i.y,zoom:bl(i.zoom,t,n)},[[0,0],[u.width,u.height]],r);let p=f.on(`wheel.zoom`),m=f.on(`dblclick.zoom`);d.wheelDelta(md);function h(e,t){return f?new Promise(n=>{d?.interpolate(t?.interpolate===`linear`?Fo:Yo).transform(pd(f,t?.duration,t?.ease,()=>n(!0)),e)}):Promise.resolve(!1)}function g({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:n,userSelectionActive:r,panOnScroll:i,panOnDrag:u,panOnScrollMode:h,panOnScrollSpeed:g,preventScrolling:v,zoomOnPinch:y,zoomOnScroll:b,zoomOnDoubleClick:x,zoomActivationKeyPressed:S,lib:C,onTransformChange:w,connectionInProgress:T,paneClickDistance:E,selectionOnDrag:D}){r&&!l.isZoomingOrPanning&&_();let O=i&&!S&&!r;d.clickDistance(D?1/0:!Nl(E)||E<0?0:E);let k=O?hd({zoomPanValues:l,noWheelClassName:e,d3Selection:f,d3Zoom:d,panOnScrollMode:h,panOnScrollSpeed:g,zoomOnPinch:y,onPanZoomStart:o,onPanZoom:a,onPanZoomEnd:s}):gd({noWheelClassName:e,preventScrolling:v,d3ZoomHandler:p});if(f.on(`wheel.zoom`,k,{passive:!1}),!r){let e=_d({zoomPanValues:l,onDraggingChange:c,onPanZoomStart:o});d.on(`start`,e);let t=vd({zoomPanValues:l,panOnDrag:u,onPaneContextMenu:!!n,onPanZoom:a,onTransformChange:w});d.on(`zoom`,t);let r=yd({zoomPanValues:l,panOnDrag:u,panOnScroll:i,onPaneContextMenu:n,onPanZoomEnd:s,onDraggingChange:c});d.on(`end`,r)}let A=bd({zoomActivationKeyPressed:S,panOnDrag:u,zoomOnScroll:b,panOnScroll:i,zoomOnDoubleClick:x,zoomOnPinch:y,userSelectionActive:r,noPanClassName:t,noWheelClassName:e,lib:C,connectionInProgress:T});d.filter(A),x?f.on(`dblclick.zoom`,m):f.on(`dblclick.zoom`,null)}function _(){d.on(`zoom`,null)}async function v(e,t,n){let r=ld(e),i=d?.constrain()(r,t,n);return i&&await h(i),new Promise(e=>e(i))}async function y(e,t){let n=ld(e);return await h(n,t),new Promise(e=>e(n))}function b(e){if(f){let t=ld(e),n=f.property(`__zoom`);(n.k!==e.zoom||n.x!==e.x||n.y!==e.y)&&d?.transform(f,t,null,{sync:!0})}}function x(){let e=f?Bc(f.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}}function S(e,t){return f?new Promise(n=>{d?.interpolate(t?.interpolate===`linear`?Fo:Yo).scaleTo(pd(f,t?.duration,t?.ease,()=>n(!0)),e)}):Promise.resolve(!1)}function C(e,t){return f?new Promise(n=>{d?.interpolate(t?.interpolate===`linear`?Fo:Yo).scaleBy(pd(f,t?.duration,t?.ease,()=>n(!0)),e)}):Promise.resolve(!1)}function w(e){d?.scaleExtent(e)}function T(e){d?.translateExtent(e)}function E(e){let t=!Nl(e)||e<0?0:e;d?.clickDistance(t)}return{update:g,destroy:_,setViewport:y,setViewportConstrained:v,getViewport:x,scaleTo:S,scaleBy:C,setScaleExtent:w,setTranslateExtent:T,syncViewport:b,setClickDistance:E}}var Sd;(function(e){e.Line=`line`,e.Handle=`handle`})(Sd||={});function Y({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:i,affectsY:a}){let o=e-t,s=n-r,c=[o>0?1:o<0?-1:0,s>0?1:s<0?-1:0];return o&&i&&(c[0]*=-1),s&&a&&(c[1]*=-1),c}function Cd(e){return{isHorizontal:e.includes(`right`)||e.includes(`left`),isVertical:e.includes(`bottom`)||e.includes(`top`),affectsX:e.includes(`left`),affectsY:e.includes(`top`)}}function wd(e,t){return Math.max(0,t-e)}function Td(e,t){return Math.max(0,e-t)}function Ed(e,t,n){return Math.max(0,t-e,e-n)}function Dd(e,t){return e?!t:t}function Od(e,t,n,r,i,a,o,s){let{affectsX:c,affectsY:l}=t,{isHorizontal:u,isVertical:d}=t,f=u&&d,{xSnapped:p,ySnapped:m}=n,{minWidth:h,maxWidth:g,minHeight:_,maxHeight:v}=r,{x:y,y:b,width:x,height:S,aspectRatio:C}=e,w=Math.floor(u?p-e.pointerX:0),T=Math.floor(d?m-e.pointerY:0),E=x+(c?-w:w),D=S+(l?-T:T),O=-a[0]*x,k=-a[1]*S,A=Ed(E,h,g),j=Ed(D,_,v);if(o){let e=0,t=0;c&&w<0?e=wd(y+w+O,o[0][0]):!c&&w>0&&(e=Td(y+E+O,o[1][0])),l&&T<0?t=wd(b+T+k,o[0][1]):!l&&T>0&&(t=Td(b+D+k,o[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(s){let e=0,t=0;c&&w>0?e=Td(y+w,s[0][0]):!c&&w<0&&(e=wd(y+E,s[1][0])),l&&T>0?t=Td(b+T,s[0][1]):!l&&T<0&&(t=wd(b+D,s[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(i){if(u){let e=Ed(E/C,_,v)*C;if(A=Math.max(A,e),o){let e=0;e=!c&&!l||c&&!l&&f?Td(b+k+E/C,o[1][1])*C:wd(b+k+(c?w:-w)/C,o[0][1])*C,A=Math.max(A,e)}if(s){let e=0;e=!c&&!l||c&&!l&&f?wd(b+E/C,s[1][1])*C:Td(b+(c?w:-w)/C,s[0][1])*C,A=Math.max(A,e)}}if(d){let e=Ed(D*C,h,g)/C;if(j=Math.max(j,e),o){let e=0;e=!c&&!l||l&&!c&&f?Td(y+D*C+O,o[1][0])/C:wd(y+(l?T:-T)*C+O,o[0][0])/C,j=Math.max(j,e)}if(s){let e=0;e=!c&&!l||l&&!c&&f?wd(y+D*C,s[1][0])/C:Td(y+(l?T:-T)*C,s[0][0])/C,j=Math.max(j,e)}}}T+=T<0?j:-j,w+=w<0?A:-A,i&&(f?E>D*C?T=(Dd(c,l)?-w:w)/C:w=(Dd(c,l)?-T:T)*C:u?(T=w/C,l=c):(w=T*C,c=l));let M=c?y+w:y,N=l?b+T:b;return{width:x+(c?-w:w),height:S+(l?-T:T),x:a[0]*w*(c?-1:1)+M,y:a[1]*T*(l?-1:1)+N}}var kd={width:0,height:0,x:0,y:0},Ad={...kd,pointerX:0,pointerY:0,aspectRatio:1};function jd(e){return[[0,0],[e.measured.width,e.measured.height]]}function Md(e,t,n){let r=t.position.x+e.position.x,i=t.position.y+e.position.y,a=e.measured.width??0,o=e.measured.height??0,s=n[0]*a,c=n[1]*o;return[[r-s,i-c],[r+a-s,i+o-c]]}function Nd({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:i}){let a=_a(e),o={controlDirection:Cd(`bottom-right`),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function s({controlPosition:e,boundaries:s,keepAspectRatio:c,resizeDirection:l,onResizeStart:u,onResize:d,onResizeEnd:f,shouldResize:p}){let m={...kd},h={...Ad};o={boundaries:s,resizeDirection:l,keepAspectRatio:c,controlDirection:Cd(e)};let g,_=null,v=[],y,b,x,S=!1,C=Ma().on(`start`,e=>{let{nodeLookup:r,transform:i,snapGrid:a,snapToGrid:o,nodeOrigin:s,paneDomNode:c}=n();if(g=r.get(t),!g)return;_=c?.getBoundingClientRect()??null;let{xSnapped:l,ySnapped:d}=Yl(e.sourceEvent,{transform:i,snapGrid:a,snapToGrid:o,containerBounds:_});m={width:g.measured.width??0,height:g.measured.height??0,x:g.position.x??0,y:g.position.y??0},h={...m,pointerX:l,pointerY:d,aspectRatio:m.width/m.height},y=void 0,g.parentId&&(g.extent===`parent`||g.expandParent)&&(y=r.get(g.parentId),b=y&&g.extent===`parent`?jd(y):void 0),v=[],x=void 0;for(let[e,n]of r)if(n.parentId===t&&(v.push({id:e,position:{...n.position},extent:n.extent}),n.extent===`parent`||n.expandParent)){let e=Md(n,g,n.origin??s);x=x?[[Math.min(e[0][0],x[0][0]),Math.min(e[0][1],x[0][1])],[Math.max(e[1][0],x[1][0]),Math.max(e[1][1],x[1][1])]]:e}u?.(e,{...m})}).on(`drag`,e=>{let{transform:t,snapGrid:i,snapToGrid:a,nodeOrigin:s}=n(),c=Yl(e.sourceEvent,{transform:t,snapGrid:i,snapToGrid:a,containerBounds:_}),l=[];if(!g)return;let{x:u,y:f,width:C,height:w}=m,T={},E=g.origin??s,{width:D,height:O,x:k,y:A}=Od(h,o.controlDirection,c,o.boundaries,o.keepAspectRatio,E,b,x),j=D!==C,M=O!==w,N=k!==u&&j,P=A!==f&&M;if(!N&&!P&&!j&&!M)return;if((N||P||E[0]===1||E[1]===1)&&(T.x=N?k:m.x,T.y=P?A:m.y,m.x=T.x,m.y=T.y,v.length>0)){let e=k-u,t=A-f;for(let n of v)n.position={x:n.position.x-e+E[0]*(D-C),y:n.position.y-t+E[1]*(O-w)},l.push(n)}if((j||M)&&(T.width=j&&(!o.resizeDirection||o.resizeDirection===`horizontal`)?D:m.width,T.height=M&&(!o.resizeDirection||o.resizeDirection===`vertical`)?O:m.height,m.width=T.width,m.height=T.height),y&&g.expandParent){let e=E[0]*(T.width??0);T.x&&T.x{S&&=(f?.(e,{...m}),i?.({...m}),!1)});a.call(C)}function c(){a.on(`.drag`,null)}return{update:s,destroy:c}}var Pd=o((e=>{var t=d();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),Fd=o(((e,t)=>{t.exports=Pd()})),Id=o((e=>{var t=d(),n=Fd();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),Ld=l(o(((e,t)=>{t.exports=Id()}))(),1),Rd=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e)),destroy:()=>{n.clear()}},o=t=e(r,i,a);return a},zd=e=>e?Rd(e):Rd,{useDebugValue:Bd}=v.default,{useSyncExternalStoreWithSelector:Vd}=Ld.default,Hd=e=>e;function Ud(e,t=Hd,n){let r=Vd(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Bd(r),r}var Wd=(e,t)=>{let n=zd(e),r=(e,r=t)=>Ud(n,e,r);return Object.assign(r,n),r},Gd=(e,t)=>e?Wd(e,t):Wd;function Kd(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var qd=h(),Jd=(0,v.createContext)(null),Yd=Jd.Provider,Xd=Xc.error001();function Zd(e,t){let n=(0,v.useContext)(Jd);if(n===null)throw Error(Xd);return Ud(n,e,t)}function Qd(){let e=(0,v.useContext)(Jd);if(e===null)throw Error(Xd);return(0,v.useMemo)(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}var $d={display:`none`},ef={position:`absolute`,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0px, 0px, 0px, 0px)`,clipPath:`inset(100%)`},tf=`react-flow__node-desc`,nf=`react-flow__edge-desc`,rf=`react-flow__aria-live`,af=e=>e.ariaLiveMessage,of=e=>e.ariaLabelConfig;function sf({rfId:e}){let t=Zd(af);return(0,H.jsx)(`div`,{id:`${rf}-${e}`,"aria-live":`assertive`,"aria-atomic":`true`,style:ef,children:t})}function cf({rfId:e,disableKeyboardA11y:t}){let n=Zd(of);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{id:`${tf}-${e}`,style:$d,children:t?n[`node.a11yDescription.default`]:n[`node.a11yDescription.keyboardDisabled`]}),(0,H.jsx)(`div`,{id:`${nf}-${e}`,style:$d,children:n[`edge.a11yDescription.default`]}),!t&&(0,H.jsx)(sf,{rfId:e})]})}var lf=(0,v.forwardRef)(({position:e=`top-left`,children:t,className:n,style:r,...i},a)=>(0,H.jsx)(`div`,{className:pr([`react-flow__panel`,n,...`${e}`.split(`-`)]),style:r,ref:a,...i,children:t}));lf.displayName=`Panel`;function uf({proOptions:e,position:t=`bottom-right`}){return e?.hideAttribution?null:(0,H.jsx)(lf,{position:t,className:`react-flow__attribution`,"data-message":`Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev`,children:(0,H.jsx)(`a`,{href:`https://reactflow.dev`,target:`_blank`,rel:`noopener noreferrer`,"aria-label":`React Flow attribution`,children:`React Flow`})})}var df=e=>{let t=[],n=[];for(let[,n]of e.nodeLookup)n.selected&&t.push(n.internals.userNode);for(let[,t]of e.edgeLookup)t.selected&&n.push(t);return{selectedNodes:t,selectedEdges:n}},ff=e=>e.id;function pf(e,t){return Kd(e.selectedNodes.map(ff),t.selectedNodes.map(ff))&&Kd(e.selectedEdges.map(ff),t.selectedEdges.map(ff))}function mf({onSelectionChange:e}){let t=Qd(),{selectedNodes:n,selectedEdges:r}=Zd(df,pf);return(0,v.useEffect)(()=>{let i={nodes:n,edges:r};e?.(i),t.getState().onSelectionChangeHandlers.forEach(e=>e(i))},[n,r,e]),null}var hf=e=>!!e.onSelectionChangeHandlers;function gf({onSelectionChange:e}){let t=Zd(hf);return e||t?(0,H.jsx)(mf,{onSelectionChange:e}):null}var _f=[0,0],vf={x:0,y:0,zoom:1},yf=[...`nodes.edges.defaultNodes.defaultEdges.onConnect.onConnectStart.onConnectEnd.onClickConnectStart.onClickConnectEnd.nodesDraggable.autoPanOnNodeFocus.nodesConnectable.nodesFocusable.edgesFocusable.edgesReconnectable.elevateNodesOnSelect.elevateEdgesOnSelect.minZoom.maxZoom.nodeExtent.onNodesChange.onEdgesChange.elementsSelectable.connectionMode.snapGrid.snapToGrid.translateExtent.connectOnClick.defaultEdgeOptions.fitView.fitViewOptions.onNodesDelete.onEdgesDelete.onDelete.onNodeDrag.onNodeDragStart.onNodeDragStop.onSelectionDrag.onSelectionDragStart.onSelectionDragStop.onMoveStart.onMove.onMoveEnd.noPanClassName.nodeOrigin.autoPanOnConnect.autoPanOnNodeDrag.onError.connectionRadius.isValidConnection.selectNodesOnDrag.nodeDragThreshold.connectionDragThreshold.onBeforeDelete.debug.autoPanSpeed.ariaLabelConfig.zIndexMode`.split(`.`),`rfId`],bf=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),xf={translateExtent:Zc,nodeOrigin:_f,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:`nopan`,rfId:`1`};function Sf(e){let{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:i,setTranslateExtent:a,setNodeExtent:o,reset:s,setDefaultNodesAndEdges:c}=Zd(bf,Kd),l=Qd();(0,v.useEffect)(()=>(c(e.defaultNodes,e.defaultEdges),()=>{u.current=xf,s()}),[]);let u=(0,v.useRef)(xf);return(0,v.useEffect)(()=>{for(let s of yf){let c=e[s];c!==u.current[s]&&e[s]!==void 0&&(s===`nodes`?t(c):s===`edges`?n(c):s===`minZoom`?r(c):s===`maxZoom`?i(c):s===`translateExtent`?a(c):s===`nodeExtent`?o(c):s===`ariaLabelConfig`?l.setState({ariaLabelConfig:Jl(c)}):s===`fitView`?l.setState({fitViewQueued:c}):s===`fitViewOptions`?l.setState({fitViewOptions:c}):l.setState({[s]:c}))}u.current=e},yf.map(t=>e[t])),null}function Cf(){return typeof window>`u`||!window.matchMedia?null:window.matchMedia(`(prefers-color-scheme: dark)`)}function wf(e){let[t,n]=(0,v.useState)(e===`system`?null:e);return(0,v.useEffect)(()=>{if(e!==`system`){n(e);return}let t=Cf(),r=()=>n(t?.matches?`dark`:`light`);return r(),t?.addEventListener(`change`,r),()=>{t?.removeEventListener(`change`,r)}},[e]),t===null?Cf()?.matches?`dark`:`light`:t}var Tf=typeof document<`u`?document:null;function Ef(e=null,t={target:Tf,actInsideInputWithModifier:!0}){let[n,r]=(0,v.useState)(!1),i=(0,v.useRef)(!1),a=(0,v.useRef)(new Set([])),[o,s]=(0,v.useMemo)(()=>{if(e!==null){let t=(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`).map(e=>e.replace(`+`,` -`).replace(` - -`,` -+`).split(` -`));return[t,t.reduce((e,t)=>e.concat(...t),[])]}return[[],[]]},[e]);return(0,v.useEffect)(()=>{let n=t?.target??Tf,c=t?.actInsideInputWithModifier??!0;if(e!==null){let e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!c)&&$l(e))return!1;let n=Of(e.code,s);if(a.current.add(e[n]),Df(o,a.current,!1)){let n=e.composedPath?.()?.[0]||e.target,a=n?.nodeName===`BUTTON`||n?.nodeName===`A`;t.preventDefault!==!1&&(i.current||!a)&&e.preventDefault(),r(!0)}},l=e=>{let t=Of(e.code,s);Df(o,a.current,!0)?(r(!1),a.current.clear()):a.current.delete(e[t]),e.key===`Meta`&&a.current.clear(),i.current=!1},u=()=>{a.current.clear(),r(!1)};return n?.addEventListener(`keydown`,e),n?.addEventListener(`keyup`,l),window.addEventListener(`blur`,u),window.addEventListener(`contextmenu`,u),()=>{n?.removeEventListener(`keydown`,e),n?.removeEventListener(`keyup`,l),window.removeEventListener(`blur`,u),window.removeEventListener(`contextmenu`,u)}}},[e,r]),n}function Df(e,t,n){return e.filter(e=>n||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function Of(e,t){return t.includes(e)?`code`:`key`}var kf=()=>{let e=Qd();return(0,v.useMemo)(()=>({zoomIn:t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomOut:t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomTo:(t,n)=>{let{panZoom:r}=e.getState();return r?r.scaleTo(t,{duration:n?.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{let{transform:[r,i,a],panZoom:o}=e.getState();return o?(await o.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??a},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{let[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{let{width:r,height:i,minZoom:a,maxZoom:o,panZoom:s}=e.getState(),c=Bl(t,r,i,a,o,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{let{transform:r,snapGrid:i,snapToGrid:a,domNode:o}=e.getState();if(!o)return t;let{x:s,y:c}=o.getBoundingClientRect(),l={x:t.x-s,y:t.y-c},u=n.snapGrid??i;return Il(l,r,n.snapToGrid??a,u)},flowToScreenPosition:t=>{let{transform:n,domNode:r}=e.getState();if(!r)return t;let{x:i,y:a}=r.getBoundingClientRect(),o=Ll(t,n);return{x:o.x+i,y:o.y+a}}}),[])};function Af(e,t){let n=[],r=new Map,i=[];for(let t of e)if(t.type===`add`){i.push(t);continue}else if(t.type===`remove`||t.type===`replace`)r.set(t.id,[t]);else{let e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}for(let e of t){let t=r.get(e.id);if(!t){n.push(e);continue}if(t[0].type===`remove`)continue;if(t[0].type===`replace`){n.push({...t[0].item});continue}let i={...e};for(let e of t)jf(e,i);n.push(i)}return i.length&&i.forEach(e=>{e.index===void 0?n.push({...e.item}):n.splice(e.index,0,{...e.item})}),n}function jf(e,t){switch(e.type){case`select`:t.selected=e.selected;break;case`position`:e.position!==void 0&&(t.position=e.position),e.dragging!==void 0&&(t.dragging=e.dragging);break;case`dimensions`:e.dimensions!==void 0&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes===`width`)&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes===`height`)&&(t.height=e.dimensions.height))),typeof e.resizing==`boolean`&&(t.resizing=e.resizing);break}}function Mf(e,t){return Af(e,t)}function Nf(e,t){return Af(e,t)}function Pf(e,t){return{id:e,type:`select`,selected:t}}function Ff(e,t=new Set,n=!1){let r=[];for(let[i,a]of e){let e=t.has(i);!(a.selected===void 0&&!e)&&a.selected!==e&&(n&&(a.selected=e),r.push(Pf(a.id,e)))}return r}function If({items:e=[],lookup:t}){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let[r,i]of e.entries()){let e=t.get(i.id),a=e?.internals?.userNode??e;a!==void 0&&a!==i&&n.push({id:i.id,item:i,type:`replace`}),a===void 0&&n.push({item:i,type:`add`,index:r})}for(let[e]of t)r.get(e)===void 0&&n.push({id:e,type:`remove`});return n}function Lf(e){return{id:e.id,type:`remove`}}var Rf=e=>ll(e),zf=e=>cl(e);function Bf(e){return(0,v.forwardRef)(e)}var Vf=typeof window<`u`?v.useLayoutEffect:v.useEffect;function Hf(e){let[t,n]=(0,v.useState)(BigInt(0)),[r]=(0,v.useState)(()=>Uf(()=>n(e=>e+BigInt(1))));return Vf(()=>{let t=r.get();t.length&&(e(t),r.reset())},[t]),r}function Uf(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}var Wf=(0,v.createContext)(null);function Gf({children:e}){let t=Qd(),n=Hf((0,v.useCallback)(e=>{let{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:a,nodeLookup:o,fitViewQueued:s,onNodesChangeMiddlewareMap:c}=t.getState(),l=n;for(let t of e)l=typeof t==`function`?t(l):t;let u=If({items:l,lookup:o});for(let e of c.values())u=e(u);i&&r(l),u.length>0?a?.(u):s&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:n,setNodes:r}=t.getState();e&&r(n)})},[])),r=Hf((0,v.useCallback)(e=>{let{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:a,edgeLookup:o}=t.getState(),s=n;for(let t of e)s=typeof t==`function`?t(s):t;i?r(s):a&&a(If({items:s,lookup:o}))},[])),i=(0,v.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,H.jsx)(Wf.Provider,{value:i,children:e})}function Kf(){let e=(0,v.useContext)(Wf);if(!e)throw Error(`useBatchContext must be used within a BatchProvider`);return e}var qf=e=>!!e.panZoom;function Jf(){let e=kf(),t=Qd(),n=Kf(),r=Zd(qf),i=(0,v.useMemo)(()=>{let e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},a=e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState(),i=Rf(e)?e:n.get(e.id),a=i.parentId?Gl(i.position,i.measured,i.parentId,n,r):i.position;return Ol({...i,position:a,width:i.measured?.width??i.width,height:i.measured?.height??i.height})},o=(e,t,n={replace:!1})=>{r(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&Rf(e)?e:{...r,...e}}return r}))},s=(e,t,n={replace:!1})=>{i(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&zf(e)?e:{...r,...e}}return r}))};return{getNodes:()=>t.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=t.getState();return e.map(e=>({...e}))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{let t=Array.isArray(e)?e:[e];n.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];n.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,a,o]=r;return{nodes:e.map(e=>({...e})),edges:n.map(e=>({...e})),viewport:{x:i,y:a,zoom:o}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{let{nodes:r,edges:i,onNodesDelete:a,onEdgesDelete:o,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:l,onBeforeDelete:u}=t.getState(),{nodes:d,edges:f}=await yl({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:u}),p=f.length>0,m=d.length>0;if(p){let e=f.map(Lf);o?.(f),c(e)}if(m){let e=d.map(Lf);a?.(d),s(e)}return(m||p)&&l?.({nodes:d,edges:f}),{deletedNodes:d,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{let i=Ml(e),o=i?e:a(e),s=r!==void 0;return o?(r||t.getState().nodes).filter(r=>{let a=t.getState().nodeLookup.get(r.id);if(a&&!i&&(r.id===e.id||!a.internals.positionAbsolute))return!1;let c=Ol(s?r:a),l=jl(c,o);return n&&l>0||l>=c.width*c.height||l>=o.width*o.height}):[]},isNodeIntersecting:(e,t,n=!0)=>{let r=Ml(e)?e:a(e);if(!r)return!1;let i=jl(r,t);return n&&i>0||i>=t.width*t.height||i>=r.width*r.height},updateNode:o,updateNodeData:(e,t,n={replace:!1})=>{o(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},getNodesBounds:e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState();return fl(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:``}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:``}`)?.values()??[]),fitView:async e=>{let r=t.getState().fitViewResolver??ql();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push(e=>[...e]),r.promise}}},[]);return(0,v.useMemo)(()=>({...i,...e,viewportInitialized:r}),[r])}var Yf=e=>e.selected,Xf=typeof window<`u`?window:void 0;function Zf({deleteKeyCode:e,multiSelectionKeyCode:t}){let n=Qd(),{deleteElements:r}=Jf(),i=Ef(e,{actInsideInputWithModifier:!1}),a=Ef(t,{target:Xf});(0,v.useEffect)(()=>{if(i){let{edges:e,nodes:t}=n.getState();r({nodes:t.filter(Yf),edges:e.filter(Yf)}),n.setState({nodesSelectionActive:!1})}},[i]),(0,v.useEffect)(()=>{n.setState({multiSelectionActive:a})},[a])}function Qf(e){let t=Qd();(0,v.useEffect)(()=>{let n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;let n=Xl(e.current);(n.height===0||n.width===0)&&t.getState().onError?.(`004`,Xc.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener(`resize`,n);let t=new ResizeObserver(()=>n());return t.observe(e.current),()=>{window.removeEventListener(`resize`,n),t&&e.current&&t.unobserve(e.current)}}},[])}var $f={position:`absolute`,width:`100%`,height:`100%`,top:0,left:0},ep=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function tp({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:i=.5,panOnScrollMode:a=tl.Free,zoomOnDoubleClick:o=!0,panOnDrag:s=!0,defaultViewport:c,translateExtent:l,minZoom:u,maxZoom:d,zoomActivationKeyCode:f,preventScrolling:p=!0,children:m,noWheelClassName:h,noPanClassName:g,onViewportChange:_,isControlledViewport:y,paneClickDistance:b,selectionOnDrag:x}){let S=Qd(),C=(0,v.useRef)(null),{userSelectionActive:w,lib:T,connectionInProgress:E}=Zd(ep,Kd),D=Ef(f),O=(0,v.useRef)();Qf(C);let k=(0,v.useCallback)(e=>{_?.({x:e[0],y:e[1],zoom:e[2]}),y||S.setState({transform:e})},[_,y]);return(0,v.useEffect)(()=>{if(C.current){O.current=xd({domNode:C.current,minZoom:u,maxZoom:d,translateExtent:l,viewport:c,onDraggingChange:e=>S.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:n,onMoveStart:r}=S.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:n,onMove:r}=S.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:n,onMoveEnd:r}=S.getState();r?.(e,t),n?.(t)}});let{x:e,y:t,zoom:n}=O.current.getViewport();return S.setState({panZoom:O.current,transform:[e,t,n],domNode:C.current.closest(`.react-flow`)}),()=>{O.current?.destroy()}}},[]),(0,v.useEffect)(()=>{O.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:i,panOnScrollMode:a,zoomOnDoubleClick:o,panOnDrag:s,zoomActivationKeyPressed:D,preventScrolling:p,noPanClassName:g,userSelectionActive:w,noWheelClassName:h,lib:T,onTransformChange:k,connectionInProgress:E,selectionOnDrag:x,paneClickDistance:b})},[e,t,n,r,i,a,o,s,D,p,g,w,h,T,k,E,x,b]),(0,H.jsx)(`div`,{className:`react-flow__renderer`,ref:C,style:$f,children:m})}var np=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function rp(){let{userSelectionActive:e,userSelectionRect:t}=Zd(np,Kd);return e&&t?(0,H.jsx)(`div`,{className:`react-flow__selection react-flow__container`,style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var ip=(e,t)=>n=>{n.target===t.current&&e?.(n)},ap=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function op({isSelecting:e,selectionKeyPressed:t,selectionMode:n=nl.Full,panOnDrag:r,paneClickDistance:i,selectionOnDrag:a,onSelectionStart:o,onSelectionEnd:s,onPaneClick:c,onPaneContextMenu:l,onPaneScroll:u,onPaneMouseEnter:d,onPaneMouseMove:f,onPaneMouseLeave:p,children:m}){let h=Qd(),{userSelectionActive:g,elementsSelectable:_,dragging:y,connectionInProgress:b}=Zd(ap,Kd),x=_&&(e||g),S=(0,v.useRef)(null),C=(0,v.useRef)(),w=(0,v.useRef)(new Set),T=(0,v.useRef)(new Set),E=(0,v.useRef)(!1),D=e=>{if(E.current||b){E.current=!1;return}c?.(e),h.getState().resetSelectedElements(),h.setState({nodesSelectionActive:!1})},O=e=>{if(Array.isArray(r)&&r?.includes(2)){e.preventDefault();return}l?.(e)},k=u?e=>u(e):void 0;return(0,H.jsxs)(`div`,{className:pr([`react-flow__pane`,{draggable:r===!0||Array.isArray(r)&&r.includes(0),dragging:y,selection:e}]),onClick:x?void 0:ip(D,S),onContextMenu:ip(O,S),onWheel:ip(k,S),onPointerEnter:x?void 0:d,onPointerMove:x?e=>{let{userSelectionRect:r,transform:a,nodeLookup:s,edgeLookup:c,connectionLookup:l,triggerNodeChanges:u,triggerEdgeChanges:d,defaultEdgeOptions:f,resetSelectedElements:p}=h.getState();if(!C.current||!r)return;let{x:m,y:g}=tu(e.nativeEvent,C.current),{startX:_,startY:v}=r;if(!E.current){let n=t?0:i;if(Math.hypot(m-_,g-v)<=n)return;p(),o?.(e)}E.current=!0;let y={startX:_,startY:v,x:m<_?m:_,y:ge.id)),T.current=new Set;let S=f?.selectable??!0;for(let e of w.current){let t=l.get(e);if(t)for(let{edgeId:e}of t.values()){let t=c.get(e);t&&(t.selectable??S)&&T.current.add(e)}}Kl(b,w.current)||u(Ff(s,w.current,!0)),Kl(x,T.current)||d(Ff(c,T.current)),h.setState({userSelectionRect:y,userSelectionActive:!0,nodesSelectionActive:!1})}:f,onPointerUp:x?e=>{e.button===0&&(e.target?.releasePointerCapture?.(e.pointerId),!g&&e.target===S.current&&h.getState().userSelectionRect&&D?.(e),h.setState({userSelectionActive:!1,userSelectionRect:null}),E.current&&(s?.(e),h.setState({nodesSelectionActive:w.current.size>0})))}:void 0,onPointerDownCapture:x?n=>{let{domNode:r}=h.getState();if(C.current=r?.getBoundingClientRect(),!C.current)return;let i=n.target===S.current;if(!i&&n.target.closest(`.nokey`)||!e||!(a&&i||t)||n.button!==0||!n.isPrimary)return;n.target?.setPointerCapture?.(n.pointerId),E.current=!1;let{x:o,y:s}=tu(n.nativeEvent,C.current);h.setState({userSelectionRect:{width:0,height:0,startX:o,startY:s,x:o,y:s}}),i||(n.stopPropagation(),n.preventDefault())}:void 0,onClickCapture:x?e=>{E.current&&=(e.stopPropagation(),!1)}:void 0,onPointerLeave:p,ref:S,style:$f,children:[m,(0,H.jsx)(rp,{})]})}function sp({id:e,store:t,unselect:n=!1,nodeRef:r}){let{addSelectedNodes:i,unselectNodesAndEdges:a,multiSelectionActive:o,nodeLookup:s,onError:c}=t.getState(),l=s.get(e);if(!l){c?.(`012`,Xc.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&o)&&(a({nodes:[l],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):i([e])}function cp({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:a,nodeClickDistance:o}){let s=Qd(),[c,l]=(0,v.useState)(!1),u=(0,v.useRef)();return(0,v.useEffect)(()=>{u.current=Xu({getStoreItems:()=>s.getState(),onNodeMouseDown:t=>{sp({id:t,store:s,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}})},[]),(0,v.useEffect)(()=>{if(!(t||!e.current||!u.current))return u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:a,nodeId:i,nodeClickDistance:o}),()=>{u.current?.destroy()}},[n,r,t,a,e,i,o]),c}var lp=e=>t=>t.selected&&(t.draggable||e&&t.draggable===void 0);function up(){let e=Qd();return(0,v.useCallback)(t=>{let{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:a,onError:o,updateNodePositions:s,nodeLookup:c,nodeOrigin:l}=e.getState(),u=new Map,d=lp(a),f=r?i[0]:5,p=r?i[1]:5,m=t.direction.x*f*t.factor,h=t.direction.y*p*t.factor;for(let[,e]of c){if(!d(e))continue;let t={x:e.internals.positionAbsolute.x+m,y:e.internals.positionAbsolute.y+h};r&&(t=Fl(t,i));let{position:a,positionAbsolute:s}=vl({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:l,onError:o});e.position=a,e.internals.positionAbsolute=s,u.set(e.id,e)}s(u)},[])}var dp=(0,v.createContext)(null),fp=dp.Provider;dp.Consumer;var pp=()=>(0,v.useContext)(dp),mp=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),hp=(e,t,n)=>r=>{let{connectionClickStartHandle:i,connectionMode:a,connection:o}=r,{fromHandle:s,toHandle:c,isValid:l}=o,u=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:u,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:a===el.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:u&&l}};function gp({type:e=`source`,position:t=q.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:a=!0,id:o,onConnect:s,children:c,className:l,onMouseDown:u,onTouchStart:d,...f},p){let m=o||null,h=e===`target`,g=Qd(),_=pp(),{connectOnClick:v,noPanClassName:y,rfId:b}=Zd(mp,Kd),{connectingFrom:x,connectingTo:S,clickConnecting:C,isPossibleEndHandle:w,connectionInProcess:T,clickConnectionInProcess:E,valid:D}=Zd(hp(_,m,e),Kd);_||g.getState().onError?.(`010`,Xc.error010());let O=e=>{let{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=g.getState(),i={...t,...e};if(r){let{edges:e,setEdges:t}=g.getState();t(fu(i,e))}n?.(i),s?.(i)},k=e=>{if(!_)return;let t=eu(e.nativeEvent);if(i&&(t&&e.button===0||!t)){let t=g.getState();od.onPointerDown(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:h,handleId:m,nodeId:_,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>g.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:O,isValidConnection:n||((...e)=>g.getState().isValidConnection?.(...e)??!0),getTransform:()=>g.getState().transform,getFromHandle:()=>g.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?u?.(e):d?.(e)};return(0,H.jsx)(`div`,{"data-handleid":m,"data-nodeid":_,"data-handlepos":t,"data-id":`${b}-${_}-${m}-${e}`,className:pr([`react-flow__handle`,`react-flow__handle-${t}`,`nodrag`,y,l,{source:!h,target:h,connectable:r,connectablestart:i,connectableend:a,clickconnecting:C,connectingfrom:x,connectingto:S,valid:D,connectionindicator:r&&(!T||w)&&(T||E?a:i)}]),onMouseDown:k,onTouchStart:k,onClick:v?t=>{let{onClickConnectStart:r,onClickConnectEnd:a,connectionClickStartHandle:o,connectionMode:s,isValidConnection:c,lib:l,rfId:u,nodeLookup:d,connection:f}=g.getState();if(!_||!o&&!i)return;if(!o){r?.(t.nativeEvent,{nodeId:_,handleId:m,handleType:e}),g.setState({connectionClickStartHandle:{nodeId:_,type:e,id:m}});return}let p=Zl(t.target),h=n||c,{connection:v,isValid:y}=od.isValid(t.nativeEvent,{handle:{nodeId:_,id:m,type:e},connectionMode:s,fromNodeId:o.nodeId,fromHandleId:o.id||null,fromType:o.type,isValidConnection:h,flowId:u,doc:p,lib:l,nodeLookup:d});y&&v&&O(v);let b=structuredClone(f);delete b.inProgress,b.toPosition=b.toHandle?b.toHandle.position:null,a?.(t,b),g.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f,children:c})}var _p=(0,v.memo)(Bf(gp));function vp({data:e,isConnectable:t,sourcePosition:n=q.Bottom}){return(0,H.jsxs)(H.Fragment,{children:[e?.label,(0,H.jsx)(_p,{type:`source`,position:n,isConnectable:t})]})}function yp({data:e,isConnectable:t,targetPosition:n=q.Top,sourcePosition:r=q.Bottom}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:n,isConnectable:t}),e?.label,(0,H.jsx)(_p,{type:`source`,position:r,isConnectable:t})]})}function bp(){return null}function xp({data:e,isConnectable:t,targetPosition:n=q.Top}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:n,isConnectable:t}),e?.label]})}var Sp={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Cp={input:vp,default:yp,output:xp,group:bp};function wp(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}var Tp=e=>{let{width:t,height:n,x:r,y:i}=pl(e.nodeLookup,{filter:e=>!!e.selected});return{width:Nl(t)?t:null,height:Nl(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function Ep({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){let r=Qd(),{width:i,height:a,transformString:o,userSelectionActive:s}=Zd(Tp,Kd),c=up(),l=(0,v.useRef)(null);(0,v.useEffect)(()=>{n||l.current?.focus({preventScroll:!0})},[n]);let u=!s&&i!==null&&a!==null;if(cp({nodeRef:l,disabled:!u}),!u)return null;let d=e?t=>{e(t,r.getState().nodes.filter(e=>e.selected))}:void 0;return(0,H.jsx)(`div`,{className:pr([`react-flow__nodesselection`,`react-flow__container`,t]),style:{transform:o},children:(0,H.jsx)(`div`,{ref:l,className:`react-flow__nodesselection-rect`,onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(Sp,e.key)&&(e.preventDefault(),c({direction:Sp[e.key],factor:e.shiftKey?4:1}))},style:{width:i,height:a}})})}var Dp=typeof window<`u`?window:void 0,Op=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function kp({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,paneClickDistance:s,deleteKeyCode:c,selectionKeyCode:l,selectionOnDrag:u,selectionMode:d,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:g,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:b,panOnScrollSpeed:x,panOnScrollMode:S,zoomOnDoubleClick:C,panOnDrag:w,defaultViewport:T,translateExtent:E,minZoom:D,maxZoom:O,preventScrolling:k,onSelectionContextMenu:A,noWheelClassName:j,noPanClassName:M,disableKeyboardA11y:N,onViewportChange:P,isControlledViewport:ee}){let{nodesSelectionActive:F,userSelectionActive:I}=Zd(Op,Kd),te=Ef(l,{target:Dp}),ne=Ef(h,{target:Dp}),re=ne||w,ie=ne||b,L=u&&re!==!0,ae=te||I||L;return Zf({deleteKeyCode:c,multiSelectionKeyCode:m}),(0,H.jsx)(tp,{onPaneContextMenu:a,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:ie,panOnScrollSpeed:x,panOnScrollMode:S,zoomOnDoubleClick:C,panOnDrag:!te&&re,defaultViewport:T,translateExtent:E,minZoom:D,maxZoom:O,zoomActivationKeyCode:g,preventScrolling:k,noWheelClassName:j,noPanClassName:M,onViewportChange:P,isControlledViewport:ee,paneClickDistance:s,selectionOnDrag:L,children:(0,H.jsxs)(op,{onSelectionStart:f,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,panOnDrag:re,isSelecting:!!ae,selectionMode:d,selectionKeyPressed:te,paneClickDistance:s,selectionOnDrag:L,children:[e,F&&(0,H.jsx)(Ep,{onSelectionContextMenu:A,noPanClassName:M,disableKeyboardA11y:N})]})})}kp.displayName=`FlowRenderer`;var Ap=(0,v.memo)(kp),jp=e=>t=>e?ml(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(e=>e.id):Array.from(t.nodeLookup.keys());function Mp(e){return Zd((0,v.useCallback)(jp(e),[e]),Kd)}var Np=e=>e.updateNodeInternals;function Pp(){let e=Zd(Np),[t]=(0,v.useState)(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(t=>{let n=new Map;t.forEach(e=>{let t=e.target.getAttribute(`data-id`);n.set(t,{id:t,nodeElement:e.target,force:!0})}),e(n)}));return(0,v.useEffect)(()=>()=>{t?.disconnect()},[t]),t}function Fp({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){let i=Qd(),a=(0,v.useRef)(null),o=(0,v.useRef)(null),s=(0,v.useRef)(e.sourcePosition),c=(0,v.useRef)(e.targetPosition),l=(0,v.useRef)(t),u=n&&!!e.internals.handleBounds;return(0,v.useEffect)(()=>{a.current&&!e.hidden&&(!u||o.current!==a.current)&&(o.current&&r?.unobserve(o.current),r?.observe(a.current),o.current=a.current)},[u,e.hidden]),(0,v.useEffect)(()=>()=>{o.current&&=(r?.unobserve(o.current),null)},[]),(0,v.useEffect)(()=>{if(a.current){let n=l.current!==t,r=s.current!==e.sourcePosition,o=c.current!==e.targetPosition;(n||r||o)&&(l.current=t,s.current=e.sourcePosition,c.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:a.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),a}function Ip({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:i,onContextMenu:a,onDoubleClick:o,nodesDraggable:s,elementsSelectable:c,nodesConnectable:l,nodesFocusable:u,resizeObserver:d,noDragClassName:f,noPanClassName:p,disableKeyboardA11y:m,rfId:h,nodeTypes:g,nodeClickDistance:_,onError:v}){let{node:y,internals:b,isParent:x}=Zd(t=>{let n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}},Kd),S=y.type||`default`,C=g?.[S]||Cp[S];C===void 0&&(v?.(`003`,Xc.error003(S)),S=`default`,C=g?.default||Cp.default);let w=!!(y.draggable||s&&y.draggable===void 0),T=!!(y.selectable||c&&y.selectable===void 0),E=!!(y.connectable||l&&y.connectable===void 0),D=!!(y.focusable||u&&y.focusable===void 0),O=Qd(),k=Wl(y),A=Fp({node:y,nodeType:S,hasDimensions:k,resizeObserver:d}),j=cp({nodeRef:A,disabled:y.hidden||!w,noDragClassName:f,handleSelector:y.dragHandle,nodeId:e,isSelectable:T,nodeClickDistance:_}),M=up();if(y.hidden)return null;let N=Ul(y),P=wp(y),ee=T||w||t||n||r||i,F=n?e=>n(e,{...b.userNode}):void 0,I=r?e=>r(e,{...b.userNode}):void 0,te=i?e=>i(e,{...b.userNode}):void 0,ne=a?e=>a(e,{...b.userNode}):void 0,re=o?e=>o(e,{...b.userNode}):void 0,ie=n=>{let{selectNodesOnDrag:r,nodeDragThreshold:i}=O.getState();T&&(!r||!w||i>0)&&sp({id:e,store:O,nodeRef:A}),t&&t(n,{...b.userNode})},L=t=>{if(!($l(t.nativeEvent)||m)){if(Qc.includes(t.key)&&T)sp({id:e,store:O,unselect:t.key===`Escape`,nodeRef:A});else if(w&&y.selected&&Object.prototype.hasOwnProperty.call(Sp,t.key)){t.preventDefault();let{ariaLabelConfig:e}=O.getState();O.setState({ariaLiveMessage:e[`node.a11yDescription.ariaLiveMessage`]({direction:t.key.replace(`Arrow`,``).toLowerCase(),x:~~b.positionAbsolute.x,y:~~b.positionAbsolute.y})}),M({direction:Sp[t.key],factor:t.shiftKey?4:1})}}},ae=()=>{if(m||!A.current?.matches(`:focus-visible`))return;let{transform:t,width:n,height:r,autoPanOnNodeFocus:i,setCenter:a}=O.getState();i&&(ml(new Map([[e,y]]),{x:0,y:0,width:n,height:r},t,!0).length>0||a(y.position.x+N.width/2,y.position.y+N.height/2,{zoom:t[2]}))};return(0,H.jsx)(`div`,{className:pr([`react-flow__node`,`react-flow__node-${S}`,{[p]:w},y.className,{selected:y.selected,selectable:T,parent:x,draggable:w,dragging:j}]),ref:A,style:{zIndex:b.z,transform:`translate(${b.positionAbsolute.x}px,${b.positionAbsolute.y}px)`,pointerEvents:ee?`all`:`none`,visibility:k?`visible`:`hidden`,...y.style,...P},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:F,onMouseMove:I,onMouseLeave:te,onContextMenu:ne,onClick:ie,onDoubleClick:re,onKeyDown:D?L:void 0,tabIndex:D?0:void 0,onFocus:D?ae:void 0,role:y.ariaRole??(D?`group`:void 0),"aria-roledescription":`node`,"aria-describedby":m?void 0:`${tf}-${h}`,"aria-label":y.ariaLabel,...y.domAttributes,children:(0,H.jsx)(fp,{value:e,children:(0,H.jsx)(C,{id:e,data:y.data,type:S,positionAbsoluteX:b.positionAbsolute.x,positionAbsoluteY:b.positionAbsolute.y,selected:y.selected??!1,selectable:T,draggable:w,deletable:y.deletable??!0,isConnectable:E,sourcePosition:y.sourcePosition,targetPosition:y.targetPosition,dragging:j,dragHandle:y.dragHandle,zIndex:b.z,parentId:y.parentId,...N})})})}var Lp=(0,v.memo)(Ip),Rp=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function zp(e){let{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,onError:a}=Zd(Rp,Kd),o=Mp(e.onlyRenderVisibleElements),s=Pp();return(0,H.jsx)(`div`,{className:`react-flow__nodes`,style:$f,children:o.map(o=>(0,H.jsx)(Lp,{id:o,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:s,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,nodeClickDistance:e.nodeClickDistance,onError:a},o))})}zp.displayName=`NodeRenderer`;var Bp=(0,v.memo)(zp);function Vp(e){return Zd((0,v.useCallback)(t=>{if(!e)return t.edges.map(e=>e.id);let n=[];if(t.width&&t.height)for(let e of t.edges){let r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&lu({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n},[e]),Kd)}var Hp=({color:e=`none`,strokeWidth:t=1})=>(0,H.jsx)(`polyline`,{className:`arrow`,style:{strokeWidth:t,...e&&{stroke:e}},strokeLinecap:`round`,fill:`none`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4`}),Up=({color:e=`none`,strokeWidth:t=1})=>(0,H.jsx)(`polyline`,{className:`arrowclosed`,style:{strokeWidth:t,...e&&{stroke:e,fill:e}},strokeLinecap:`round`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4 -5,-4`}),Wp={[al.Arrow]:Hp,[al.ArrowClosed]:Up};function Gp(e){let t=Qd();return(0,v.useMemo)(()=>Object.prototype.hasOwnProperty.call(Wp,e)?Wp[e]:(t.getState().onError?.(`009`,Xc.error009(e)),null),[e])}var Kp=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:a=`strokeWidth`,strokeWidth:o,orient:s=`auto-start-reverse`})=>{let c=Gp(t);return c?(0,H.jsx)(`marker`,{className:`react-flow__arrowhead`,id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:`-10 -10 20 20`,markerUnits:a,orient:s,refX:`0`,refY:`0`,children:(0,H.jsx)(c,{color:n,strokeWidth:o})}):null},qp=({defaultColor:e,rfId:t})=>{let n=Zd(e=>e.edges),r=Zd(e=>e.defaultEdgeOptions),i=(0,v.useMemo)(()=>Eu(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return i.length?(0,H.jsx)(`svg`,{className:`react-flow__marker`,"aria-hidden":`true`,children:(0,H.jsx)(`defs`,{children:i.map(e=>(0,H.jsx)(Kp,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};qp.displayName=`MarkerDefinitions`;var Jp=(0,v.memo)(qp);function Yp({x:e,y:t,label:n,labelStyle:r,labelShowBg:i=!0,labelBgStyle:a,labelBgPadding:o=[2,4],labelBgBorderRadius:s=2,children:c,className:l,...u}){let[d,f]=(0,v.useState)({x:1,y:0,width:0,height:0}),p=pr([`react-flow__edge-textwrapper`,l]),m=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(m.current){let e=m.current.getBBox();f({x:e.x,y:e.y,width:e.width,height:e.height})}},[n]),n?(0,H.jsxs)(`g`,{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?`visible`:`hidden`,...u,children:[i&&(0,H.jsx)(`rect`,{width:d.width+2*o[0],x:-o[0],y:-o[1],height:d.height+2*o[1],className:`react-flow__edge-textbg`,style:a,rx:s,ry:s}),(0,H.jsx)(`text`,{className:`react-flow__edge-text`,y:d.height/2,dy:`0.3em`,ref:m,style:r,children:n}),c]}):null}Yp.displayName=`EdgeText`;var Xp=(0,v.memo)(Yp);function Zp({path:e,labelX:t,labelY:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c,interactionWidth:l=20,...u}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`path`,{...u,d:e,fill:`none`,className:pr([`react-flow__edge-path`,u.className])}),l?(0,H.jsx)(`path`,{d:e,fill:`none`,strokeOpacity:0,strokeWidth:l,className:`react-flow__edge-interaction`}):null,r&&Nl(t)&&Nl(n)?(0,H.jsx)(Xp,{x:t,y:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c}):null]})}function Qp({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===q.Left||e===q.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function $p({sourceX:e,sourceY:t,sourcePosition:n=q.Bottom,targetX:r,targetY:i,targetPosition:a=q.Top}){let[o,s]=Qp({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,l]=Qp({pos:a,x1:r,y1:i,x2:e,y2:t}),[u,d,f,p]=ru({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:o,sourceControlY:s,targetControlX:c,targetControlY:l});return[`M${e},${t} C${o},${s} ${c},${l} ${r},${i}`,u,d,f,p]}function em(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o,targetPosition:s,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})=>{let[v,y,b]=$p({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s});return(0,H.jsx)(Zp,{id:e.isInternal?void 0:t,path:v,labelX:y,labelY:b,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})})}var tm=em({isInternal:!1}),nm=em({isInternal:!0});tm.displayName=`SimpleBezierEdge`,nm.displayName=`SimpleBezierEdgeInternal`;function rm(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,sourcePosition:p=q.Bottom,targetPosition:m=q.Top,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,x]=yu({sourceX:n,sourceY:r,sourcePosition:p,targetX:i,targetY:a,targetPosition:m,borderRadius:_?.borderRadius,offset:_?.offset,stepPosition:_?.stepPosition});return(0,H.jsx)(Zp,{id:e.isInternal?void 0:t,path:y,labelX:b,labelY:x,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:g,interactionWidth:v})})}var im=rm({isInternal:!1}),am=rm({isInternal:!0});im.displayName=`SmoothStepEdge`,am.displayName=`SmoothStepEdgeInternal`;function om(e){return(0,v.memo)(({id:t,...n})=>{let r=e.isInternal?void 0:t;return(0,H.jsx)(im,{...n,id:r,pathOptions:(0,v.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}var sm=om({isInternal:!1}),cm=om({isInternal:!0});sm.displayName=`StepEdge`,cm.displayName=`StepEdgeInternal`;function lm(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})=>{let[g,_,v]=pu({sourceX:n,sourceY:r,targetX:i,targetY:a});return(0,H.jsx)(Zp,{id:e.isInternal?void 0:t,path:g,labelX:_,labelY:v,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})})}var um=lm({isInternal:!1}),dm=lm({isInternal:!0});um.displayName=`StraightEdge`,dm.displayName=`StraightEdgeInternal`;function fm(e){return(0,v.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o=q.Bottom,targetPosition:s=q.Top,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,x]=ou({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s,curvature:_?.curvature});return(0,H.jsx)(Zp,{id:e.isInternal?void 0:t,path:y,labelX:b,labelY:x,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:v})})}var pm=fm({isInternal:!1}),mm=fm({isInternal:!0});pm.displayName=`BezierEdge`,mm.displayName=`BezierEdgeInternal`;var hm={default:mm,straight:dm,step:cm,smoothstep:am,simplebezier:nm},gm={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},_m=(e,t,n)=>n===q.Left?e-t:n===q.Right?e+t:e,vm=(e,t,n)=>n===q.Top?e-t:n===q.Bottom?e+t:e,ym=`react-flow__edgeupdater`;function bm({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:a,onMouseOut:o,type:s}){return(0,H.jsx)(`circle`,{onMouseDown:i,onMouseEnter:a,onMouseOut:o,className:pr([ym,`${ym}-${s}`]),cx:_m(t,r,e),cy:vm(n,r,e),r,stroke:`transparent`,fill:`transparent`})}function xm({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:i,targetX:a,targetY:o,sourcePosition:s,targetPosition:c,onReconnect:l,onReconnectStart:u,onReconnectEnd:d,setReconnecting:f,setUpdateHover:p}){let m=Qd(),h=(e,t)=>{if(e.button!==0)return;let{autoPanOnConnect:r,domNode:i,connectionMode:a,connectionRadius:o,lib:s,onConnectStart:c,cancelConnection:p,nodeLookup:h,rfId:g,panBy:_,updateConnection:v}=m.getState(),y=t.type===`target`;od.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:o,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:h,isTarget:y,edgeUpdaterType:t.type,lib:s,flowId:g,cancelConnection:p,panBy:_,isValidConnection:(...e)=>m.getState().isValidConnection?.(...e)??!0,onConnect:e=>l?.(n,e),onConnectStart:(r,i)=>{f(!0),u?.(e,n,t.type),c?.(r,i)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,r)=>{f(!1),d?.(e,n,t.type,r)},updateConnection:v,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},g=e=>h(e,{nodeId:n.target,id:n.targetHandle??null,type:`target`}),_=e=>h(e,{nodeId:n.source,id:n.sourceHandle??null,type:`source`}),v=()=>p(!0),y=()=>p(!1);return(0,H.jsxs)(H.Fragment,{children:[(e===!0||e===`source`)&&(0,H.jsx)(bm,{position:s,centerX:r,centerY:i,radius:t,onMouseDown:g,onMouseEnter:v,onMouseOut:y,type:`source`}),(e===!0||e===`target`)&&(0,H.jsx)(bm,{position:c,centerX:a,centerY:o,radius:t,onMouseDown:_,onMouseEnter:v,onMouseOut:y,type:`target`})]})}function Sm({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:i,onDoubleClick:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,rfId:m,edgeTypes:h,noPanClassName:g,onError:_,disableKeyboardA11y:y}){let b=Zd(t=>t.edgeLookup.get(e)),x=Zd(e=>e.defaultEdgeOptions);b=x?{...x,...b}:b;let S=b.type||`default`,C=h?.[S]||hm[S];C===void 0&&(_?.(`011`,Xc.error011(S)),S=`default`,C=h?.default||hm.default);let w=!!(b.focusable||t&&b.focusable===void 0),T=d!==void 0&&(b.reconnectable||n&&b.reconnectable===void 0),E=!!(b.selectable||r&&b.selectable===void 0),D=(0,v.useRef)(null),[O,k]=(0,v.useState)(!1),[A,j]=(0,v.useState)(!1),M=Qd(),{zIndex:N,sourceX:P,sourceY:ee,targetX:F,targetY:I,sourcePosition:te,targetPosition:ne}=Zd((0,v.useCallback)(t=>{let n=t.nodeLookup.get(b.source),r=t.nodeLookup.get(b.target);if(!n||!r)return{zIndex:b.zIndex,...gm};let i=xu({id:e,sourceNode:n,targetNode:r,sourceHandle:b.sourceHandle||null,targetHandle:b.targetHandle||null,connectionMode:t.connectionMode,onError:_});return{zIndex:cu({selected:b.selected,zIndex:b.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode}),...i||gm}},[b.source,b.target,b.sourceHandle,b.targetHandle,b.selected,b.zIndex]),Kd),re=(0,v.useMemo)(()=>b.markerStart?`url('#${Tu(b.markerStart,m)}')`:void 0,[b.markerStart,m]),ie=(0,v.useMemo)(()=>b.markerEnd?`url('#${Tu(b.markerEnd,m)}')`:void 0,[b.markerEnd,m]);if(b.hidden||P===null||ee===null||F===null||I===null)return null;let L=t=>{let{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:a}=M.getState();E&&(M.setState({nodesSelectionActive:!1}),b.selected&&a?(r({nodes:[],edges:[b]}),D.current?.blur()):n([e])),i&&i(t,b)},ae=a?e=>{a(e,{...b})}:void 0,oe=o?e=>{o(e,{...b})}:void 0,se=s?e=>{s(e,{...b})}:void 0,ce=c?e=>{c(e,{...b})}:void 0,le=l?e=>{l(e,{...b})}:void 0;return(0,H.jsx)(`svg`,{style:{zIndex:N},children:(0,H.jsxs)(`g`,{className:pr([`react-flow__edge`,`react-flow__edge-${S}`,b.className,g,{selected:b.selected,animated:b.animated,inactive:!E&&!i,updating:O,selectable:E}]),onClick:L,onDoubleClick:ae,onContextMenu:oe,onMouseEnter:se,onMouseMove:ce,onMouseLeave:le,onKeyDown:w?t=>{if(!y&&Qc.includes(t.key)&&E){let{unselectNodesAndEdges:n,addSelectedEdges:r}=M.getState();t.key===`Escape`?(D.current?.blur(),n({edges:[b]})):r([e])}}:void 0,tabIndex:w?0:void 0,role:b.ariaRole??(w?`group`:`img`),"aria-roledescription":`edge`,"data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":b.ariaLabel===null?void 0:b.ariaLabel||`Edge from ${b.source} to ${b.target}`,"aria-describedby":w?`${nf}-${m}`:void 0,ref:D,...b.domAttributes,children:[!A&&(0,H.jsx)(C,{id:e,source:b.source,target:b.target,type:b.type,selected:b.selected,animated:b.animated,selectable:E,deletable:b.deletable??!0,label:b.label,labelStyle:b.labelStyle,labelShowBg:b.labelShowBg,labelBgStyle:b.labelBgStyle,labelBgPadding:b.labelBgPadding,labelBgBorderRadius:b.labelBgBorderRadius,sourceX:P,sourceY:ee,targetX:F,targetY:I,sourcePosition:te,targetPosition:ne,data:b.data,style:b.style,sourceHandleId:b.sourceHandle,targetHandleId:b.targetHandle,markerStart:re,markerEnd:ie,pathOptions:`pathOptions`in b?b.pathOptions:void 0,interactionWidth:b.interactionWidth}),T&&(0,H.jsx)(xm,{edge:b,isReconnectable:T,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,sourceX:P,sourceY:ee,targetX:F,targetY:I,sourcePosition:te,targetPosition:ne,setUpdateHover:k,setReconnecting:j})]})})}var Cm=(0,v.memo)(Sm),wm=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Tm({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:i,onReconnect:a,onEdgeContextMenu:o,onEdgeMouseEnter:s,onEdgeMouseMove:c,onEdgeMouseLeave:l,onEdgeClick:u,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,disableKeyboardA11y:h}){let{edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,onError:y}=Zd(wm,Kd),b=Vp(t);return(0,H.jsxs)(`div`,{className:`react-flow__edges`,children:[(0,H.jsx)(Jp,{defaultColor:e,rfId:n}),b.map(e=>(0,H.jsx)(Cm,{id:e,edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,noPanClassName:i,onReconnect:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,onClick:u,reconnectRadius:d,onDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,rfId:n,onError:y,edgeTypes:r,disableKeyboardA11y:h},e))]})}Tm.displayName=`EdgeRenderer`;var Em=(0,v.memo)(Tm),Dm=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Om({children:e}){return(0,H.jsx)(`div`,{className:`react-flow__viewport xyflow__viewport react-flow__container`,style:{transform:Zd(Dm)},children:e})}function km(e){let t=Jf(),n=(0,v.useRef)(!1);(0,v.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var Am=e=>e.panZoom?.syncViewport;function jm(e){let t=Zd(Am),n=Qd();return(0,v.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function Mm(e){return e.connection.inProgress?{...e.connection,to:Il(e.connection.to,e.transform)}:{...e.connection}}function Nm(e){return e?t=>e(Mm(t)):Mm}function Pm(e){return Zd(Nm(e),Kd)}var Fm=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Im({containerStyle:e,style:t,type:n,component:r}){let{nodesConnectable:i,width:a,height:o,isValid:s,inProgress:c}=Zd(Fm,Kd);return a&&i&&c?(0,H.jsx)(`svg`,{style:e,width:a,height:o,className:`react-flow__connectionline react-flow__container`,children:(0,H.jsx)(`g`,{className:pr([`react-flow__connection`,sl(s)]),children:(0,H.jsx)(Lm,{style:t,type:n,CustomComponent:r,isValid:s})})}):null}var Lm=({style:e,type:t=il.Bezier,CustomComponent:n,isValid:r})=>{let{inProgress:i,from:a,fromNode:o,fromHandle:s,fromPosition:c,to:l,toNode:u,toHandle:d,toPosition:f,pointer:p}=Pm();if(!i)return;if(n)return(0,H.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:o,fromHandle:s,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:c,toPosition:f,connectionStatus:sl(r),toNode:u,toHandle:d,pointer:p});let m=``,h={sourceX:a.x,sourceY:a.y,sourcePosition:c,targetX:l.x,targetY:l.y,targetPosition:f};switch(t){case il.Bezier:[m]=ou(h);break;case il.SimpleBezier:[m]=$p(h);break;case il.Step:[m]=yu({...h,borderRadius:0});break;case il.SmoothStep:[m]=yu(h);break;default:[m]=pu(h)}return(0,H.jsx)(`path`,{d:m,fill:`none`,className:`react-flow__connection-path`,style:e})};Lm.displayName=`ConnectionLine`;var Rm={};function zm(e=Rm){(0,v.useRef)(e),Qd(),(0,v.useEffect)(()=>{},[e])}function Bm(){Qd(),(0,v.useRef)(!1),(0,v.useEffect)(()=>{},[])}function Vm({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:i,onNodeDoubleClick:a,onEdgeDoubleClick:o,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:p,connectionLineType:m,connectionLineStyle:h,connectionLineComponent:g,connectionLineContainerStyle:_,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,multiSelectionKeyCode:x,panActivationKeyCode:S,zoomActivationKeyCode:C,deleteKeyCode:w,onlyRenderVisibleElements:T,elementsSelectable:E,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,preventScrolling:j,defaultMarkerColor:M,zoomOnScroll:N,zoomOnPinch:P,panOnScroll:ee,panOnScrollSpeed:F,panOnScrollMode:I,zoomOnDoubleClick:te,panOnDrag:ne,onPaneClick:re,onPaneMouseEnter:ie,onPaneMouseMove:L,onPaneMouseLeave:ae,onPaneScroll:oe,onPaneContextMenu:se,paneClickDistance:ce,nodeClickDistance:le,onEdgeContextMenu:ue,onEdgeMouseEnter:de,onEdgeMouseMove:fe,onEdgeMouseLeave:pe,reconnectRadius:me,onReconnect:he,onReconnectStart:ge,onReconnectEnd:_e,noDragClassName:ve,noWheelClassName:ye,noPanClassName:be,disableKeyboardA11y:xe,nodeExtent:Se,rfId:Ce,viewport:we,onViewportChange:Te}){return zm(e),zm(t),Bm(),km(n),jm(we),(0,H.jsx)(Ap,{onPaneClick:re,onPaneMouseEnter:ie,onPaneMouseMove:L,onPaneMouseLeave:ae,onPaneContextMenu:se,onPaneScroll:oe,paneClickDistance:ce,deleteKeyCode:w,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:x,panActivationKeyCode:S,zoomActivationKeyCode:C,elementsSelectable:E,zoomOnScroll:N,zoomOnPinch:P,zoomOnDoubleClick:te,panOnScroll:ee,panOnScrollSpeed:F,panOnScrollMode:I,panOnDrag:ne,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,onSelectionContextMenu:d,preventScrolling:j,noDragClassName:ve,noWheelClassName:ye,noPanClassName:be,disableKeyboardA11y:xe,onViewportChange:Te,isControlledViewport:!!we,children:(0,H.jsxs)(Om,{children:[(0,H.jsx)(Em,{edgeTypes:t,onEdgeClick:i,onEdgeDoubleClick:o,onReconnect:he,onReconnectStart:ge,onReconnectEnd:_e,onlyRenderVisibleElements:T,onEdgeContextMenu:ue,onEdgeMouseEnter:de,onEdgeMouseMove:fe,onEdgeMouseLeave:pe,reconnectRadius:me,defaultMarkerColor:M,noPanClassName:be,disableKeyboardA11y:xe,rfId:Ce}),(0,H.jsx)(Im,{style:h,type:m,component:g,containerStyle:_}),(0,H.jsx)(`div`,{className:`react-flow__edgelabel-renderer`}),(0,H.jsx)(Bp,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:a,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,nodeClickDistance:le,onlyRenderVisibleElements:T,noPanClassName:be,noDragClassName:ve,disableKeyboardA11y:xe,nodeExtent:Se,rfId:Ce}),(0,H.jsx)(`div`,{className:`react-flow__viewport-portal`})]})})}Vm.displayName=`GraphView`;var Hm=(0,v.memo)(Vm),Um=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c=.5,maxZoom:l=2,nodeOrigin:u,nodeExtent:d,zIndexMode:f=`basic`}={})=>{let p=new Map,m=new Map,h=new Map,g=new Map,_=r??t??[],v=n??e??[],y=u??[0,0],b=d??Zc;Wu(h,g,_);let x=Fu(v,p,m,{nodeOrigin:y,nodeExtent:b,zIndexMode:f}),S=[0,0,1];if(o&&i&&a){let{x:e,y:t,zoom:n}=Bl(pl(p,{filter:e=>!!((e.width||e.initialWidth)&&(e.height||e.initialHeight))}),i,a,c,l,s?.padding??.1);S=[e,t,n]}return{rfId:`1`,width:i??0,height:a??0,transform:S,nodes:v,nodesInitialized:x,nodeLookup:p,parentLookup:m,edges:_,edgeLookup:g,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:l,translateExtent:Zc,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:el.Strict,domNode:null,paneDragging:!1,noPanClassName:`nopan`,nodeOrigin:y,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:o??!1,fitViewOptions:s,fitViewResolver:null,connection:{...rl},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:``,autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:Pl,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:`react`,debug:!1,ariaLabelConfig:$c,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},Wm=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f})=>Gd((p,m)=>{async function h(){let{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:a,minZoom:o,maxZoom:s}=m();t&&(await _l({nodes:e,width:i,height:a,panZoom:t,minZoom:o,maxZoom:s},n),r?.resolve(!0),p({fitViewResolver:null}))}return{...Um({nodes:e,edges:t,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:e=>{let{nodeLookup:t,parentLookup:n,nodeOrigin:r,elevateNodesOnSelect:i,fitViewQueued:a,zIndexMode:o}=m(),s=Fu(e,t,n,{nodeOrigin:r,nodeExtent:d,elevateNodesOnSelect:i,checkEquality:!0,zIndexMode:o});a&&s?(h(),p({nodes:e,nodesInitialized:s,fitViewQueued:!1,fitViewOptions:void 0})):p({nodes:e,nodesInitialized:s})},setEdges:e=>{let{connectionLookup:t,edgeLookup:n}=m();Wu(t,n,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=m();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=m();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:a,nodeExtent:o,debug:s,fitViewQueued:c,zIndexMode:l}=m(),{changes:u,updatedInternals:d}=Vu(e,n,r,i,a,o,l);d&&(Mu(n,r,{nodeOrigin:a,nodeExtent:o,zIndexMode:l}),c?(h(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),u?.length>0&&(s&&console.log(`React Flow: trigger node changes`,u),t?.(u)))},updateNodePositions:(e,t=!1)=>{let n=[],r=[],{nodeLookup:i,triggerNodeChanges:a,connection:o,updateConnection:s,onNodesChangeMiddlewareMap:c}=m();for(let[a,c]of e){let e=i.get(a),l=!!(e?.expandParent&&e?.parentId&&c?.position),u={id:a,type:`position`,position:l?{x:Math.max(0,c.position.x),y:Math.max(0,c.position.y)}:c.position,dragging:t};if(e&&o.inProgress&&o.fromNode.id===e.id){let t=Cu(e,o.fromHandle,q.Left,!0);s({...o,from:t})}l&&e.parentId&&n.push({id:a,parentId:e.parentId,rect:{...c.internals.positionAbsolute,width:c.measured.width??0,height:c.measured.height??0}}),r.push(u)}if(n.length>0){let{parentLookup:e,nodeOrigin:t}=m(),a=Bu(n,i,e,t);r.push(...a)}for(let e of c.values())r=e(r);a(r)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:a}=m();e?.length&&(i&&n(Mf(e,r)),a&&console.log(`React Flow: trigger node changes`,e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:a}=m();e?.length&&(i&&n(Nf(e,r)),a&&console.log(`React Flow: trigger edge changes`,e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){i(e.map(e=>Pf(e,!0)));return}i(Ff(r,new Set([...e]),!0)),a(Ff(n))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){a(e.map(e=>Pf(e,!0)));return}a(Ff(n,new Set([...e]))),i(Ff(r,new Set,!0))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:a,triggerEdgeChanges:o}=m(),s=e||r,c=t||n,l=[];for(let e of s){if(!e.selected)continue;let t=i.get(e.id);t&&(t.selected=!1),l.push(Pf(e.id,!1))}let u=[];for(let e of c)e.selected&&u.push(Pf(e.id,!1));a(l),o(u)},setMinZoom:e=>{let{panZoom:t,maxZoom:n}=m();t?.setScaleExtent([e,n]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:n}=m();t?.setScaleExtent([n,e]),p({maxZoom:e})},setTranslateExtent:e=>{m().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r,elementsSelectable:i}=m();if(!i)return;let a=t.reduce((e,t)=>t.selected?[...e,Pf(t.id,!1)]:e,[]),o=e.reduce((e,t)=>t.selected?[...e,Pf(t.id,!1)]:e,[]);n(a),r(o)},setNodeExtent:e=>{let{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:a,nodeExtent:o,zIndexMode:s}=m();e[0][0]===o[0][0]&&e[0][1]===o[0][1]&&e[1][0]===o[1][0]&&e[1][1]===o[1][1]||(Fu(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:a,checkEquality:!1,zIndexMode:s}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:n,height:r,panZoom:i,translateExtent:a}=m();return Hu({delta:e,panZoom:i,transform:t,translateExtent:a,width:n,height:r})},setCenter:async(e,t,n)=>{let{width:r,height:i,maxZoom:a,panZoom:o}=m();if(!o)return Promise.resolve(!1);let s=n?.zoom===void 0?a:n.zoom;return await o.setViewport({x:r/2-e*s,y:i/2-t*s,zoom:s},{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{p({connection:{...rl}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...Um()})}},Object.is);function Gm({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:i,initialHeight:a,initialMinZoom:o,initialMaxZoom:s,initialFitViewOptions:c,fitView:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f,children:p}){let[m]=(0,v.useState)(()=>Wm({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:l,minZoom:o,maxZoom:s,fitViewOptions:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f}));return(0,H.jsx)(Yd,{value:m,children:(0,H.jsx)(Gf,{children:p})})}function Km({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:i,width:a,height:o,fitView:s,fitViewOptions:c,minZoom:l,maxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p}){return(0,v.useContext)(Jd)?(0,H.jsx)(H.Fragment,{children:e}):(0,H.jsx)(Gm,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:i,initialWidth:a,initialHeight:o,fitView:s,initialFitViewOptions:c,initialMinZoom:l,initialMaxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p,children:e})}var qm={width:`100%`,height:`100%`,overflow:`hidden`,position:`relative`,zIndex:0};function Jm({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:a,edgeTypes:o,onNodeClick:s,onEdgeClick:c,onInit:l,onMove:u,onMoveStart:d,onMoveEnd:f,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,onNodeMouseEnter:y,onNodeMouseMove:b,onNodeMouseLeave:x,onNodeContextMenu:S,onNodeDoubleClick:C,onNodeDragStart:w,onNodeDrag:T,onNodeDragStop:E,onNodesDelete:D,onEdgesDelete:O,onDelete:k,onSelectionChange:A,onSelectionDragStart:j,onSelectionDrag:M,onSelectionDragStop:N,onSelectionContextMenu:P,onSelectionStart:ee,onSelectionEnd:F,onBeforeDelete:I,connectionMode:te,connectionLineType:ne=il.Bezier,connectionLineStyle:re,connectionLineComponent:ie,connectionLineContainerStyle:L,deleteKeyCode:ae=`Backspace`,selectionKeyCode:oe=`Shift`,selectionOnDrag:se=!1,selectionMode:ce=nl.Full,panActivationKeyCode:le=`Space`,multiSelectionKeyCode:ue=Vl()?`Meta`:`Control`,zoomActivationKeyCode:de=Vl()?`Meta`:`Control`,snapToGrid:fe,snapGrid:pe,onlyRenderVisibleElements:me=!1,selectNodesOnDrag:he,nodesDraggable:ge,autoPanOnNodeFocus:_e,nodesConnectable:ve,nodesFocusable:ye,nodeOrigin:be=_f,edgesFocusable:xe,edgesReconnectable:Se,elementsSelectable:Ce=!0,defaultViewport:we=vf,minZoom:Te=.5,maxZoom:Ee=2,translateExtent:De=Zc,preventScrolling:Oe=!0,nodeExtent:ke,defaultMarkerColor:Ae=`#b1b1b7`,zoomOnScroll:je=!0,zoomOnPinch:Me=!0,panOnScroll:Ne=!1,panOnScrollSpeed:Pe=.5,panOnScrollMode:Fe=tl.Free,zoomOnDoubleClick:Ie=!0,panOnDrag:Le=!0,onPaneClick:Re,onPaneMouseEnter:ze,onPaneMouseMove:Be,onPaneMouseLeave:Ve,onPaneScroll:He,onPaneContextMenu:R,paneClickDistance:Ue=1,nodeClickDistance:z=0,children:We,onReconnect:Ge,onReconnectStart:Ke,onReconnectEnd:qe,onEdgeContextMenu:Je,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Xe,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qe,reconnectRadius:$e=10,onNodesChange:B,onEdgesChange:V,noDragClassName:et=`nodrag`,noWheelClassName:tt=`nowheel`,noPanClassName:nt=`nopan`,fitView:rt,fitViewOptions:it,connectOnClick:at,attributionPosition:ot,proOptions:st,defaultEdgeOptions:ct,elevateNodesOnSelect:lt=!0,elevateEdgesOnSelect:ut=!1,disableKeyboardA11y:dt=!1,autoPanOnConnect:ft,autoPanOnNodeDrag:pt,autoPanSpeed:mt,connectionRadius:ht,isValidConnection:U,onError:gt,style:_t,id:vt,nodeDragThreshold:yt,connectionDragThreshold:bt,viewport:xt,onViewportChange:St,width:Ct,height:wt,colorMode:Tt=`light`,debug:Et,onScroll:Dt,ariaLabelConfig:Ot,zIndexMode:kt=`basic`,...At},jt){let Mt=vt||`1`,Nt=wf(Tt),Pt=(0,v.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:`instant`}),Dt?.(e)},[Dt]);return(0,H.jsx)(`div`,{"data-testid":`rf__wrapper`,...At,onScroll:Pt,style:{..._t,...qm},ref:jt,className:pr([`react-flow`,i,Nt]),id:vt,role:`application`,children:(0,H.jsxs)(Km,{nodes:e,edges:t,width:Ct,height:wt,fitView:rt,fitViewOptions:it,minZoom:Te,maxZoom:Ee,nodeOrigin:be,nodeExtent:ke,zIndexMode:kt,children:[(0,H.jsx)(Hm,{onInit:l,onNodeClick:s,onEdgeClick:c,onNodeMouseEnter:y,onNodeMouseMove:b,onNodeMouseLeave:x,onNodeContextMenu:S,onNodeDoubleClick:C,nodeTypes:a,edgeTypes:o,connectionLineType:ne,connectionLineStyle:re,connectionLineComponent:ie,connectionLineContainerStyle:L,selectionKeyCode:oe,selectionOnDrag:se,selectionMode:ce,deleteKeyCode:ae,multiSelectionKeyCode:ue,panActivationKeyCode:le,zoomActivationKeyCode:de,onlyRenderVisibleElements:me,defaultViewport:we,translateExtent:De,minZoom:Te,maxZoom:Ee,preventScrolling:Oe,zoomOnScroll:je,zoomOnPinch:Me,zoomOnDoubleClick:Ie,panOnScroll:Ne,panOnScrollSpeed:Pe,panOnScrollMode:Fe,panOnDrag:Le,onPaneClick:Re,onPaneMouseEnter:ze,onPaneMouseMove:Be,onPaneMouseLeave:Ve,onPaneScroll:He,onPaneContextMenu:R,paneClickDistance:Ue,nodeClickDistance:z,onSelectionContextMenu:P,onSelectionStart:ee,onSelectionEnd:F,onReconnect:Ge,onReconnectStart:Ke,onReconnectEnd:qe,onEdgeContextMenu:Je,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Xe,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qe,reconnectRadius:$e,defaultMarkerColor:Ae,noDragClassName:et,noWheelClassName:tt,noPanClassName:nt,rfId:Mt,disableKeyboardA11y:dt,nodeExtent:ke,viewport:xt,onViewportChange:St}),(0,H.jsx)(Sf,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,nodesDraggable:ge,autoPanOnNodeFocus:_e,nodesConnectable:ve,nodesFocusable:ye,edgesFocusable:xe,edgesReconnectable:Se,elementsSelectable:Ce,elevateNodesOnSelect:lt,elevateEdgesOnSelect:ut,minZoom:Te,maxZoom:Ee,nodeExtent:ke,onNodesChange:B,onEdgesChange:V,snapToGrid:fe,snapGrid:pe,connectionMode:te,translateExtent:De,connectOnClick:at,defaultEdgeOptions:ct,fitView:rt,fitViewOptions:it,onNodesDelete:D,onEdgesDelete:O,onDelete:k,onNodeDragStart:w,onNodeDrag:T,onNodeDragStop:E,onSelectionDrag:M,onSelectionDragStart:j,onSelectionDragStop:N,onMove:u,onMoveStart:d,onMoveEnd:f,noPanClassName:nt,nodeOrigin:be,rfId:Mt,autoPanOnConnect:ft,autoPanOnNodeDrag:pt,autoPanSpeed:mt,onError:gt,connectionRadius:ht,isValidConnection:U,selectNodesOnDrag:he,nodeDragThreshold:yt,connectionDragThreshold:bt,onBeforeDelete:I,debug:Et,ariaLabelConfig:Ot,zIndexMode:kt}),(0,H.jsx)(gf,{onSelectionChange:A}),We,(0,H.jsx)(uf,{proOptions:st,position:ot}),(0,H.jsx)(cf,{rfId:Mt,disableKeyboardA11y:dt})]})})}var Ym=Bf(Jm),Xm=e=>e.domNode?.querySelector(`.react-flow__edgelabel-renderer`);function Zm({children:e}){let t=Zd(Xm);return t?(0,qd.createPortal)(e,t):null}function Qm(e){let[t,n]=(0,v.useState)(e);return[t,n,(0,v.useCallback)(e=>n(t=>Mf(e,t)),[])]}function $m(e){let[t,n]=(0,v.useState)(e);return[t,n,(0,v.useCallback)(e=>n(t=>Nf(e,t)),[])]}Xc.error014();function eh({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,H.jsx)(`path`,{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:pr([`react-flow__background-pattern`,n,r])})}function th({radius:e,className:t}){return(0,H.jsx)(`circle`,{cx:e,cy:e,r:e,className:pr([`react-flow__background-pattern`,`dots`,t])})}var nh;(function(e){e.Lines=`lines`,e.Dots=`dots`,e.Cross=`cross`})(nh||={});var rh={[nh.Dots]:1,[nh.Lines]:1,[nh.Cross]:6},ih=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function ah({id:e,variant:t=nh.Dots,gap:n=20,size:r,lineWidth:i=1,offset:a=0,color:o,bgColor:s,style:c,className:l,patternClassName:u}){let d=(0,v.useRef)(null),{transform:f,patternId:p}=Zd(ih,Kd),m=r||rh[t],h=t===nh.Dots,g=t===nh.Cross,_=Array.isArray(n)?n:[n,n],y=[_[0]*f[2]||1,_[1]*f[2]||1],b=m*f[2],x=Array.isArray(a)?a:[a,a],S=g?[b,b]:y,C=[x[0]*f[2]||1+S[0]/2,x[1]*f[2]||1+S[1]/2],w=`${p}${e||``}`;return(0,H.jsxs)(`svg`,{className:pr([`react-flow__background`,l]),style:{...c,...$f,"--xy-background-color-props":s,"--xy-background-pattern-color-props":o},ref:d,"data-testid":`rf__background`,children:[(0,H.jsx)(`pattern`,{id:w,x:f[0]%y[0],y:f[1]%y[1],width:y[0],height:y[1],patternUnits:`userSpaceOnUse`,patternTransform:`translate(-${C[0]},-${C[1]})`,children:h?(0,H.jsx)(th,{radius:b/2,className:u}):(0,H.jsx)(eh,{dimensions:S,lineWidth:i,variant:t,className:u})}),(0,H.jsx)(`rect`,{x:`0`,y:`0`,width:`100%`,height:`100%`,fill:`url(#${w})`})]})}ah.displayName=`Background`;var oh=(0,v.memo)(ah);function sh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 32`,children:(0,H.jsx)(`path`,{d:`M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z`})})}function ch(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 5`,children:(0,H.jsx)(`path`,{d:`M0 0h32v4.2H0z`})})}function lh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 30`,children:(0,H.jsx)(`path`,{d:`M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z`})})}function uh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,H.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z`})})}function dh(){return(0,H.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,H.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z`})})}function fh({children:e,className:t,...n}){return(0,H.jsx)(`button`,{type:`button`,className:pr([`react-flow__controls-button`,t]),...n,children:e})}var ph=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function mh({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:a,onZoomOut:o,onFitView:s,onInteractiveChange:c,className:l,children:u,position:d=`bottom-left`,orientation:f=`vertical`,"aria-label":p}){let m=Qd(),{isInteractive:h,minZoomReached:g,maxZoomReached:_,ariaLabelConfig:v}=Zd(ph,Kd),{zoomIn:y,zoomOut:b,fitView:x}=Jf();return(0,H.jsxs)(lf,{className:pr([`react-flow__controls`,f===`horizontal`?`horizontal`:`vertical`,l]),position:d,style:e,"data-testid":`rf__controls`,"aria-label":p??v[`controls.ariaLabel`],children:[t&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(fh,{onClick:()=>{y(),a?.()},className:`react-flow__controls-zoomin`,title:v[`controls.zoomIn.ariaLabel`],"aria-label":v[`controls.zoomIn.ariaLabel`],disabled:_,children:(0,H.jsx)(sh,{})}),(0,H.jsx)(fh,{onClick:()=>{b(),o?.()},className:`react-flow__controls-zoomout`,title:v[`controls.zoomOut.ariaLabel`],"aria-label":v[`controls.zoomOut.ariaLabel`],disabled:g,children:(0,H.jsx)(ch,{})})]}),n&&(0,H.jsx)(fh,{className:`react-flow__controls-fitview`,onClick:()=>{x(i),s?.()},title:v[`controls.fitView.ariaLabel`],"aria-label":v[`controls.fitView.ariaLabel`],children:(0,H.jsx)(lh,{})}),r&&(0,H.jsx)(fh,{className:`react-flow__controls-interactive`,onClick:()=>{m.setState({nodesDraggable:!h,nodesConnectable:!h,elementsSelectable:!h}),c?.(!h)},title:v[`controls.interactive.ariaLabel`],"aria-label":v[`controls.interactive.ariaLabel`],children:h?(0,H.jsx)(dh,{}):(0,H.jsx)(uh,{})}),u]})}mh.displayName=`Controls`;var hh=(0,v.memo)(mh);function gh({id:e,x:t,y:n,width:r,height:i,style:a,color:o,strokeColor:s,strokeWidth:c,className:l,borderRadius:u,shapeRendering:d,selected:f,onClick:p}){let{background:m,backgroundColor:h}=a||{},g=o||m||h;return(0,H.jsx)(`rect`,{className:pr([`react-flow__minimap-node`,{selected:f},l]),x:t,y:n,rx:u,ry:u,width:r,height:i,style:{fill:g,stroke:s,strokeWidth:c},shapeRendering:d,onClick:p?t=>p(t,e):void 0})}var _h=(0,v.memo)(gh),vh=e=>e.nodes.map(e=>e.id),yh=e=>e instanceof Function?e:()=>e;function bh({nodeStrokeColor:e,nodeColor:t,nodeClassName:n=``,nodeBorderRadius:r=5,nodeStrokeWidth:i,nodeComponent:a=_h,onClick:o}){let s=Zd(vh,Kd),c=yh(t),l=yh(e),u=yh(n),d=typeof window>`u`||window.chrome?`crispEdges`:`geometricPrecision`;return(0,H.jsx)(H.Fragment,{children:s.map(e=>(0,H.jsx)(Sh,{id:e,nodeColorFunc:c,nodeStrokeColorFunc:l,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:i,NodeComponent:a,onClick:o,shapeRendering:d},e))})}function xh({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:i,nodeStrokeWidth:a,shapeRendering:o,NodeComponent:s,onClick:c}){let{node:l,x:u,y:d,width:f,height:p}=Zd(t=>{let n=t.nodeLookup.get(e);if(!n)return{node:void 0,x:0,y:0,width:0,height:0};let r=n.internals.userNode,{x:i,y:a}=n.internals.positionAbsolute,{width:o,height:s}=Ul(r);return{node:r,x:i,y:a,width:o,height:s}},Kd);return!l||l.hidden||!Wl(l)?null:(0,H.jsx)(s,{x:u,y:d,width:f,height:p,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:i,strokeColor:n(l),strokeWidth:a,shapeRendering:o,onClick:c,id:l.id})}var Sh=(0,v.memo)(xh),Ch=(0,v.memo)(bh),wh=200,Th=150,Eh=e=>!e.hidden,Dh=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?Al(pl(e.nodeLookup,{filter:Eh}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},Oh=`react-flow__minimap-desc`;function kh({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:i=``,nodeBorderRadius:a=5,nodeStrokeWidth:o,nodeComponent:s,bgColor:c,maskColor:l,maskStrokeColor:u,maskStrokeWidth:d,position:f=`bottom-right`,onClick:p,onNodeClick:m,pannable:h=!1,zoomable:g=!1,ariaLabel:_,inversePan:y,zoomStep:b=1,offsetScale:x=5}){let S=Qd(),C=(0,v.useRef)(null),{boundingRect:w,viewBB:T,rfId:E,panZoom:D,translateExtent:O,flowWidth:k,flowHeight:A,ariaLabelConfig:j}=Zd(Dh,Kd),M=e?.width??wh,N=e?.height??Th,P=w.width/M,ee=w.height/N,F=Math.max(P,ee),I=F*M,te=F*N,ne=x*F,re=w.x-(I-w.width)/2-ne,ie=w.y-(te-w.height)/2-ne,L=I+ne*2,ae=te+ne*2,oe=`${Oh}-${E}`,se=(0,v.useRef)(0),ce=(0,v.useRef)();se.current=F,(0,v.useEffect)(()=>{if(C.current&&D)return ce.current=sd({domNode:C.current,panZoom:D,getTransform:()=>S.getState().transform,getViewScale:()=>se.current}),()=>{ce.current?.destroy()}},[D]),(0,v.useEffect)(()=>{ce.current?.update({translateExtent:O,width:k,height:A,inversePan:y,pannable:h,zoomStep:b,zoomable:g})},[h,g,y,b,O,k,A]);let le=p?e=>{let[t,n]=ce.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,ue=m?(0,v.useCallback)((e,t)=>{let n=S.getState().nodeLookup.get(t).internals.userNode;m(e,n)},[]):void 0,de=_??j[`minimap.ariaLabel`];return(0,H.jsx)(lf,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof c==`string`?c:void 0,"--xy-minimap-mask-background-color-props":typeof l==`string`?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof u==`string`?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof d==`number`?d*F:void 0,"--xy-minimap-node-background-color-props":typeof r==`string`?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n==`string`?n:void 0,"--xy-minimap-node-stroke-width-props":typeof o==`number`?o:void 0},className:pr([`react-flow__minimap`,t]),"data-testid":`rf__minimap`,children:(0,H.jsxs)(`svg`,{width:M,height:N,viewBox:`${re} ${ie} ${L} ${ae}`,className:`react-flow__minimap-svg`,role:`img`,"aria-labelledby":oe,ref:C,onClick:le,children:[de&&(0,H.jsx)(`title`,{id:oe,children:de}),(0,H.jsx)(Ch,{onClick:ue,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:i,nodeStrokeWidth:o,nodeComponent:s}),(0,H.jsx)(`path`,{className:`react-flow__minimap-mask`,d:`M${re-ne},${ie-ne}h${L+ne*2}v${ae+ne*2}h${-L-ne*2}z - M${T.x},${T.y}h${T.width}v${T.height}h${-T.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}kh.displayName=`MiniMap`;var Ah=(0,v.memo)(kh),jh=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,Mh={[Sd.Line]:`right`,[Sd.Handle]:`bottom-right`};function Nh({nodeId:e,position:t,variant:n=Sd.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let y=pp(),b=typeof e==`string`?e:y,x=Qd(),S=(0,v.useRef)(null),C=n===Sd.Handle,w=Zd((0,v.useCallback)(jh(C&&p),[C,p]),Kd),T=(0,v.useRef)(null),E=t??Mh[n];return(0,v.useEffect)(()=>{if(!(!S.current||!b))return T.current||=Nd({domNode:S.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=x.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=x.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=Bu([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...Gl({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};x.getState().triggerNodeChanges([n])}}),T.current.update({controlPosition:E,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{T.current?.destroy()}},[E,s,c,l,u,d,h,g,_,m]),(0,H.jsx)(`div`,{className:pr([`react-flow__resize-control`,`nodrag`,...E.split(`-`),n,r]),ref:S,style:{...i,scale:w,...o&&{[C?`backgroundColor`:`borderColor`]:o}},children:a})}(0,v.memo)(Nh);function Ph(e){return e.join(`.`)}function Fh(e,t){return`${Ph(e)}::${t}`}function Ih(e){let t=e.indexOf(`::`);if(t===-1)return{contextPath:[],name:e};let n=e.slice(0,t),r=e.slice(t+2);return{contextPath:n===``?[]:n.split(`.`).map(e=>Number(e)),name:r}}function Lh(e,t){return Fh(e,t)}function Rh(e){return e.includes(`::`)}function zh(e){let t=e.indexOf(`[`);return t<=0||!e.endsWith(`]`)?null:{group:e.slice(0,t),key:e.slice(t+1,-1)}}function Bh(e,t){if(t.length===0)return null;let n=e[t[0]];for(let e=1;ee.nodes),n=B(e=>e.subworkflowContexts),r=e?.iterationContextPath,i=e?.contextPath??[],a=e?.name,o=r?r.join(`.`):``;return(0,v.useMemo)(()=>{if(r&&r.length>0){let e=Bh(n,r);return e?{name:a??``,status:e.status,type:`workflow`,activity:[],error_message:e.workflowFailure?.message,error_type:e.workflowFailure?.error_type}:void 0}if(a)return i.length===0?t[a]:Bh(n,i)?.nodes[a]},[`${i.join(`.`)}::${a??``}`,o,t,n])}function Hh(){let e=B(e=>e.selectedNode),t=B(e=>e.nodes),n=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>{if(!e)return;let{contextPath:r,name:i}=Ih(e),a=(r.length===0?t:Bh(n,r)?.nodes)?.[i];if(a)return a;if(zh(i)){let e=r.length===0?n:Bh(n,r)?.children??[],t;for(let n=e.length-1;n>=0;n--)if(e[n].slotKey===i){t=e[n];break}if(t)return{name:i,status:t.status,type:`workflow`,activity:[],tokens:t.totalTokens||void 0,cost_usd:t.totalCost||void 0,error_message:t.workflowFailure?.message,error_type:t.workflowFailure?.error_type}}},[e,t,n])}function Uh(){let e=B(e=>e.viewContextPath),t=B(e=>e.groupProgress),n=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>e.length===0?t:Bh(n,e)?.groupProgress??t,[e,t,n])}function Wh(){let e=B(e=>e.viewContextPath),t=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>e.length===0?t:Bh(t,e)?.children??[],[e,t])}function Gh(){let e=B(e=>e.viewContextPath),t=B(e=>e.agents),n=B(e=>e.routes),r=B(e=>e.parallelGroups),i=B(e=>e.forEachGroups),a=B(e=>e.nodes),o=B(e=>e.groupProgress),s=B(e=>e.entryPoint),c=B(e=>e.subworkflowContexts);return(0,v.useMemo)(()=>{if(e.length===0)return{agents:t,routes:n,parallelGroups:r,forEachGroups:i,nodes:a,groupProgress:o,entryPoint:s,subworkflowContexts:c,parentAgent:null,basePath:[]};let l=Bh(c,e);return l?{agents:l.agents,routes:l.routes,parallelGroups:l.parallelGroups,forEachGroups:l.forEachGroups,nodes:l.nodes,groupProgress:l.groupProgress,entryPoint:l.entryPoint,subworkflowContexts:l.children,parentAgent:l.parentAgent,basePath:e}:{agents:t,routes:n,parallelGroups:r,forEachGroups:i,nodes:a,groupProgress:o,entryPoint:s,subworkflowContexts:c,parentAgent:null,basePath:[]}},[e,t,n,r,i,a,o,s,c])}var Kh=0;function qh(e,t=Date.now()){Kh=Math.max(Kh,t+e)}function Jh(e=Date.now()){return e{var n=`\0`,r=`\0`,i=``,a=class{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>void 0;_defaultEdgeLabelFn=()=>void 0;_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(e){e&&(this._isDirected=Object.hasOwn(e,`directed`)?e.directed:!0,this._isMultigraph=Object.hasOwn(e,`multigraph`)?e.multigraph:!1,this._isCompound=Object.hasOwn(e,`compound`)?e.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[r]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return this._defaultNodeLabelFn=e,typeof e!=`function`&&(this._defaultNodeLabelFn=()=>e),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var e=this;return this.nodes().filter(t=>Object.keys(e._in[t]).length===0)}sinks(){var e=this;return this.nodes().filter(t=>Object.keys(e._out[t]).length===0)}setNodes(e,t){var n=arguments,r=this;return e.forEach(function(e){n.length>1?r.setNode(e,t):r.setNode(e)}),this}setNode(e,t){return Object.hasOwn(this._nodes,e)?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]=r,this._children[e]={},this._children[r][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return Object.hasOwn(this._nodes,e)}removeNode(e){var t=this;if(Object.hasOwn(this._nodes,e)){var n=e=>t.removeEdge(t._edgeObjs[e]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(function(e){t.setParent(e)}),delete this._children[e]),Object.keys(this._in[e]).forEach(n),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(n),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw Error(`Cannot set parent in a non-compound graph`);if(t===void 0)t=r;else{t+=``;for(var n=t;n!==void 0;n=this.parent(n))if(n===e)throw Error(`Setting `+t+` as parent of `+e+` would create a cycle`);this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}parent(e){if(this._isCompound){var t=this._parent[e];if(t!==r)return t}}children(e=r){if(this._isCompound){var t=this._children[e];if(t)return Object.keys(t)}else if(e===r)return this.nodes();else if(this.hasNode(e))return[]}predecessors(e){var t=this._preds[e];if(t)return Object.keys(t)}successors(e){var t=this._sucs[e];if(t)return Object.keys(t)}neighbors(e){var t=this.predecessors(e);if(t){let r=new Set(t);for(var n of this.successors(e))r.add(n);return Array.from(r.values())}}isLeaf(e){return(this.isDirected()?this.successors(e):this.neighbors(e)).length===0}filterNodes(e){var t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph());var n=this;Object.entries(this._nodes).forEach(function([n,r]){e(n)&&t.setNode(n,r)}),Object.values(this._edgeObjs).forEach(function(e){t.hasNode(e.v)&&t.hasNode(e.w)&&t.setEdge(e,n.edge(e))});var r={};function i(e){var a=n.parent(e);return a===void 0||t.hasNode(a)?(r[e]=a,a):a in r?r[a]:i(a)}return this._isCompound&&t.nodes().forEach(e=>t.setParent(e,i(e))),t}setDefaultEdgeLabel(e){return this._defaultEdgeLabelFn=e,typeof e!=`function`&&(this._defaultEdgeLabelFn=()=>e),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,t){var n=this,r=arguments;return e.reduce(function(e,i){return r.length>1?n.setEdge(e,i,t):n.setEdge(e,i),i}),this}setEdge(){var e,t,n,r,i=!1,a=arguments[0];typeof a==`object`&&a&&`v`in a?(e=a.v,t=a.w,n=a.name,arguments.length===2&&(r=arguments[1],i=!0)):(e=a,t=arguments[1],n=arguments[3],arguments.length>2&&(r=arguments[2],i=!0)),e=``+e,t=``+t,n!==void 0&&(n=``+n);var s=c(this._isDirected,e,t,n);if(Object.hasOwn(this._edgeLabels,s))return i&&(this._edgeLabels[s]=r),this;if(n!==void 0&&!this._isMultigraph)throw Error(`Cannot set a named edge when isMultigraph = false`);this.setNode(e),this.setNode(t),this._edgeLabels[s]=i?r:this._defaultEdgeLabelFn(e,t,n);var u=l(this._isDirected,e,t,n);return e=u.v,t=u.w,Object.freeze(u),this._edgeObjs[s]=u,o(this._preds[t],e),o(this._sucs[e],t),this._in[t][s]=u,this._out[e][s]=u,this._edgeCount++,this}edge(e,t,n){var r=arguments.length===1?u(this._isDirected,arguments[0]):c(this._isDirected,e,t,n);return this._edgeLabels[r]}edgeAsObj(){let e=this.edge(...arguments);return typeof e==`object`?e:{label:e}}hasEdge(e,t,n){var r=arguments.length===1?u(this._isDirected,arguments[0]):c(this._isDirected,e,t,n);return Object.hasOwn(this._edgeLabels,r)}removeEdge(e,t,n){var r=arguments.length===1?u(this._isDirected,arguments[0]):c(this._isDirected,e,t,n),i=this._edgeObjs[r];return i&&(e=i.v,t=i.w,delete this._edgeLabels[r],delete this._edgeObjs[r],s(this._preds[t],e),s(this._sucs[e],t),delete this._in[t][r],delete this._out[e][r],this._edgeCount--),this}inEdges(e,t){var n=this._in[e];if(n){var r=Object.values(n);return t?r.filter(e=>e.v===t):r}}outEdges(e,t){var n=this._out[e];if(n){var r=Object.values(n);return t?r.filter(e=>e.w===t):r}}nodeEdges(e,t){var n=this.inEdges(e,t);if(n)return n.concat(this.outEdges(e,t))}};function o(e,t){e[t]?e[t]++:e[t]=1}function s(e,t){--e[t]||delete e[t]}function c(e,t,r,a){var o=``+t,s=``+r;if(!e&&o>s){var c=o;o=s,s=c}return o+i+s+i+(a===void 0?n:a)}function l(e,t,n,r){var i=``+t,a=``+n;if(!e&&i>a){var o=i;i=a,a=o}var s={v:i,w:a};return r&&(s.name=r),s}function u(e,t){return c(e,t.v,t.w,t.name)}t.exports=a})),Xh=o(((e,t)=>{t.exports=`2.2.4`})),Zh=o(((e,t)=>{t.exports={Graph:Yh(),version:Xh()}})),Qh=o(((e,t)=>{var n=Yh();t.exports={write:r,read:o};function r(e){var t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:i(e),edges:a(e)};return e.graph()!==void 0&&(t.value=structuredClone(e.graph())),t}function i(e){return e.nodes().map(function(t){var n=e.node(t),r=e.parent(t),i={v:t};return n!==void 0&&(i.value=n),r!==void 0&&(i.parent=r),i})}function a(e){return e.edges().map(function(t){var n=e.edge(t),r={v:t.v,w:t.w};return t.name!==void 0&&(r.name=t.name),n!==void 0&&(r.value=n),r})}function o(e){var t=new n(e.options).setGraph(e.value);return e.nodes.forEach(function(e){t.setNode(e.v,e.value),e.parent&&t.setParent(e.v,e.parent)}),e.edges.forEach(function(e){t.setEdge({v:e.v,w:e.w,name:e.name},e.value)}),t}})),$h=o(((e,t)=>{t.exports=n;function n(e){var t={},n=[],r;function i(n){Object.hasOwn(t,n)||(t[n]=!0,r.push(n),e.successors(n).forEach(i),e.predecessors(n).forEach(i))}return e.nodes().forEach(function(e){r=[],i(e),r.length&&n.push(r)}),n}})),eg=o(((e,t)=>{t.exports=class{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(e){return e.key})}has(e){return Object.hasOwn(this._keyIndices,e)}priority(e){var t=this._keyIndices[e];if(t!==void 0)return this._arr[t].priority}min(){if(this.size()===0)throw Error(`Queue underflow`);return this._arr[0].key}add(e,t){var n=this._keyIndices;if(e=String(e),!Object.hasOwn(n,e)){var r=this._arr,i=r.length;return n[e]=i,r.push({key:e,priority:t}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,t){var n=this._keyIndices[e];if(t>this._arr[n].priority)throw Error(`New priority is greater than current priority. Key: `+e+` Old: `+this._arr[n].priority+` New: `+t);this._arr[n].priority=t,this._decrease(n)}_heapify(e){var t=this._arr,n=2*e,r=n+1,i=e;n>1,!(t[r].priority{var n=eg();t.exports=i;var r=()=>1;function i(e,t,n,i){return a(e,String(t),n||r,i||function(t){return e.outEdges(t)})}function a(e,t,r,i){var a={},o=new n,s,c,l=function(e){var t=e.v===s?e.w:e.v,n=a[t],i=r(e),l=c.distance+i;if(i<0)throw Error(`dijkstra does not allow negative edge weights. Bad edge: `+e+` Weight: `+i);l0&&(s=o.removeMin(),c=a[s],c.distance!==1/0);)i(s).forEach(l);return a}})),ng=o(((e,t)=>{var n=tg();t.exports=r;function r(e,t,r){return e.nodes().reduce(function(i,a){return i[a]=n(e,a,t,r),i},{})}})),rg=o(((e,t)=>{t.exports=n;function n(e){var t=0,n=[],r={},i=[];function a(o){var s=r[o]={onStack:!0,lowlink:t,index:t++};if(n.push(o),e.successors(o).forEach(function(e){Object.hasOwn(r,e)?r[e].onStack&&(s.lowlink=Math.min(s.lowlink,r[e].index)):(a(e),s.lowlink=Math.min(s.lowlink,r[e].lowlink))}),s.lowlink===s.index){var c=[],l;do l=n.pop(),r[l].onStack=!1,c.push(l);while(o!==l);i.push(c)}}return e.nodes().forEach(function(e){Object.hasOwn(r,e)||a(e)}),i}})),ig=o(((e,t)=>{var n=rg();t.exports=r;function r(e){return n(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}})),ag=o(((e,t)=>{t.exports=r;var n=()=>1;function r(e,t,r){return i(e,t||n,r||function(t){return e.outEdges(t)})}function i(e,t,n){var r={},i=e.nodes();return i.forEach(function(e){r[e]={},r[e][e]={distance:0},i.forEach(function(t){e!==t&&(r[e][t]={distance:1/0})}),n(e).forEach(function(n){var i=n.v===e?n.w:n.v,a=t(n);r[e][i]={distance:a,predecessor:e}})}),i.forEach(function(e){var t=r[e];i.forEach(function(n){var a=r[n];i.forEach(function(n){var r=a[e],i=t[n],o=a[n],s=r.distance+i.distance;s{function n(e){var t={},n={},i=[];function a(o){if(Object.hasOwn(n,o))throw new r;Object.hasOwn(t,o)||(n[o]=!0,t[o]=!0,e.predecessors(o).forEach(a),delete n[o],i.push(o))}if(e.sinks().forEach(a),Object.keys(t).length!==e.nodeCount())throw new r;return i}var r=class extends Error{constructor(){super(...arguments)}};t.exports=n,n.CycleException=r})),sg=o(((e,t)=>{var n=og();t.exports=r;function r(e){try{n(e)}catch(e){if(e instanceof n.CycleException)return!1;throw e}return!0}})),cg=o(((e,t)=>{t.exports=n;function n(e,t,n){Array.isArray(t)||(t=[t]);var a=e.isDirected()?t=>e.successors(t):t=>e.neighbors(t),o=n===`post`?r:i,s=[],c={};return t.forEach(t=>{if(!e.hasNode(t))throw Error(`Graph does not have node: `+t);o(t,a,c,s)}),s}function r(e,t,n,r){for(var i=[[e,!1]];i.length>0;){var o=i.pop();o[1]?r.push(o[0]):Object.hasOwn(n,o[0])||(n[o[0]]=!0,i.push([o[0],!0]),a(t(o[0]),e=>i.push([e,!1])))}}function i(e,t,n,r){for(var i=[e];i.length>0;){var o=i.pop();Object.hasOwn(n,o)||(n[o]=!0,r.push(o),a(t(o),e=>i.push(e)))}}function a(e,t){for(var n=e.length;n--;)t(e[n],n,e);return e}})),lg=o(((e,t)=>{var n=cg();t.exports=r;function r(e,t){return n(e,t,`post`)}})),ug=o(((e,t)=>{var n=cg();t.exports=r;function r(e,t){return n(e,t,`pre`)}})),dg=o(((e,t)=>{var n=Yh(),r=eg();t.exports=i;function i(e,t){var i=new n,a={},o=new r,s;function c(e){var n=e.v===s?e.w:e.v,r=o.priority(n);if(r!==void 0){var i=t(e);i0;){if(s=o.removeMin(),Object.hasOwn(a,s))i.setEdge(s,a[s]);else if(l)throw Error(`Input graph is not connected: `+e);else l=!0;e.nodeEdges(s).forEach(c)}return i}})),fg=o(((e,t)=>{t.exports={components:$h(),dijkstra:tg(),dijkstraAll:ng(),findCycles:ig(),floydWarshall:ag(),isAcyclic:sg(),postorder:lg(),preorder:ug(),prim:dg(),tarjan:rg(),topsort:og()}})),pg=o(((e,t)=>{var n=Zh();t.exports={Graph:n.Graph,json:Qh(),alg:fg(),version:n.version}})),mg=o(((e,t)=>{var n=class{constructor(){let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return r(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&r(e),e._next=t._next,t._next._prev=e,t._next=e,e._prev=t}toString(){let e=[],t=this._sentinel,n=t._prev;for(;n!==t;)e.push(JSON.stringify(n,i)),n=n._prev;return`[`+e.join(`, `)+`]`}};function r(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function i(e,t){if(e!==`_next`&&e!==`_prev`)return t}t.exports=n})),hg=o(((e,t)=>{var n=pg().Graph,r=mg();t.exports=a;var i=()=>1;function a(e,t){if(e.nodeCount()<=1)return[];let n=c(e,t||i);return o(n.graph,n.buckets,n.zeroIdx).flatMap(t=>e.outEdges(t.v,t.w))}function o(e,t,n){let r=[],i=t[t.length-1],a=t[0],o;for(;e.nodeCount();){for(;o=a.dequeue();)s(e,t,n,o);for(;o=i.dequeue();)s(e,t,n,o);if(e.nodeCount()){for(let i=t.length-2;i>0;--i)if(o=t[i].dequeue(),o){r=r.concat(s(e,t,n,o,!0));break}}}return r}function s(e,t,n,r,i){let a=i?[]:void 0;return e.inEdges(r.v).forEach(r=>{let o=e.edge(r),s=e.node(r.v);i&&a.push({v:r.v,w:r.w}),s.out-=o,l(t,n,s)}),e.outEdges(r.v).forEach(r=>{let i=e.edge(r),a=r.w,o=e.node(a);o.in-=i,l(t,n,o)}),e.removeNode(r.v),a}function c(e,t){let i=new n,a=0,o=0;e.nodes().forEach(e=>{i.setNode(e,{v:e,in:0,out:0})}),e.edges().forEach(e=>{let n=i.edge(e.v,e.w)||0,r=t(e),s=n+r;i.setEdge(e.v,e.w,s),o=Math.max(o,i.node(e.v).out+=r),a=Math.max(a,i.node(e.w).in+=r)});let s=u(o+a+3).map(()=>new r),c=a+1;return i.nodes().forEach(e=>{l(s,c,i.node(e))}),{graph:i,buckets:s,zeroIdx:c}}function l(e,t,n){n.out?n.in?e[n.out-n.in+t].enqueue(n):e[e.length-1].enqueue(n):e[0].enqueue(n)}function u(e){let t=[];for(let n=0;n{var n=pg().Graph;t.exports={addBorderNode:f,addDummyNode:r,applyWithChunking:h,asNonCompoundGraph:a,buildLayerMatrix:l,intersectRect:c,mapValues:w,maxRank:g,normalizeRanks:u,notime:y,partition:_,pick:C,predecessorWeights:s,range:S,removeEmptyRanks:d,simplify:i,successorWeights:o,time:v,uniqueId:x,zipObject:T};function r(e,t,n,r){for(var i=r;e.hasNode(i);)i=x(r);return n.dummy=t,e.setNode(i,n),i}function i(e){let t=new n().setGraph(e.graph());return e.nodes().forEach(n=>t.setNode(n,e.node(n))),e.edges().forEach(n=>{let r=t.edge(n.v,n.w)||{weight:0,minlen:1},i=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)})}),t}function a(e){let t=new n({multigraph:e.isMultigraph()}).setGraph(e.graph());return e.nodes().forEach(n=>{e.children(n).length||t.setNode(n,e.node(n))}),e.edges().forEach(n=>{t.setEdge(n,e.edge(n))}),t}function o(e){let t=e.nodes().map(t=>{let n={};return e.outEdges(t).forEach(t=>{n[t.w]=(n[t.w]||0)+e.edge(t).weight}),n});return T(e.nodes(),t)}function s(e){let t=e.nodes().map(t=>{let n={};return e.inEdges(t).forEach(t=>{n[t.v]=(n[t.v]||0)+e.edge(t).weight}),n});return T(e.nodes(),t)}function c(e,t){let n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2;if(!i&&!a)throw Error(`Not possible to find intersection inside of the rectangle`);let c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=s*i/a,l=s):(i<0&&(o=-o),c=o,l=o*a/i),{x:n+c,y:r+l}}function l(e){let t=S(g(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),i=r.rank;i!==void 0&&(t[i][r.order]=n)}),t}function u(e){let t=e.nodes().map(t=>{let n=e.node(t).rank;return n===void 0?Number.MAX_VALUE:n}),n=h(Math.min,t);e.nodes().forEach(t=>{let r=e.node(t);Object.hasOwn(r,`rank`)&&(r.rank-=n)})}function d(e){let t=e.nodes().map(t=>e.node(t).rank),n=h(Math.min,t),r=[];e.nodes().forEach(t=>{let i=e.node(t).rank-n;r[i]||(r[i]=[]),r[i].push(t)});let i=0,a=e.graph().nodeRankFactor;Array.from(r).forEach((t,n)=>{t===void 0&&n%a!==0?--i:t!==void 0&&i&&t.forEach(t=>e.node(t).rank+=i)})}function f(e,t,n,i){let a={width:0,height:0};return arguments.length>=4&&(a.rank=n,a.order=i),r(e,`border`,a,t)}function p(e,t=m){let n=[];for(let r=0;rm){let n=p(t);return e.apply(null,n.map(t=>e.apply(null,t)))}else return e.apply(null,t)}function g(e){let t=e.nodes().map(t=>{let n=e.node(t).rank;return n===void 0?Number.MIN_VALUE:n});return h(Math.max,t)}function _(e,t){let n={lhs:[],rhs:[]};return e.forEach(e=>{t(e)?n.lhs.push(e):n.rhs.push(e)}),n}function v(e,t){let n=Date.now();try{return t()}finally{console.log(e+` time: `+(Date.now()-n)+`ms`)}}function y(e,t){return t()}var b=0;function x(e){return e+(``+ ++b)}function S(e,t,n=1){t??(t=e,e=0);let r=e=>ete[t]),Object.entries(e).reduce((e,[t,r])=>(e[t]=n(r,t),e),{})}function T(e,t){return e.reduce((e,n,r)=>(e[n]=t[r],e),{})}})),_g=o(((e,t)=>{var n=hg(),r=gg().uniqueId;t.exports={run:i,undo:o};function i(e){(e.graph().acyclicer===`greedy`?n(e,t(e)):a(e)).forEach(t=>{let n=e.edge(t);e.removeEdge(t),n.forwardName=t.name,n.reversed=!0,e.setEdge(t.w,t.v,n,r(`rev`))});function t(e){return t=>e.edge(t).weight}}function a(e){let t=[],n={},r={};function i(a){Object.hasOwn(r,a)||(r[a]=!0,n[a]=!0,e.outEdges(a).forEach(e=>{Object.hasOwn(n,e.w)?t.push(e):i(e.w)}),delete n[a])}return e.nodes().forEach(i),t}function o(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.reversed){e.removeEdge(t);let r=n.forwardName;delete n.reversed,delete n.forwardName,e.setEdge(t.w,t.v,n,r)}})}})),vg=o(((e,t)=>{var n=gg();t.exports={run:r,undo:a};function r(e){e.graph().dummyChains=[],e.edges().forEach(t=>i(e,t))}function i(e,t){let r=t.v,i=e.node(r).rank,a=t.w,o=e.node(a).rank,s=t.name,c=e.edge(t),l=c.labelRank;if(o===i+1)return;e.removeEdge(t);let u,d,f;for(f=0,++i;i{let n=e.node(t),r=n.edgeLabel,i;for(e.setEdge(n.edgeObj,r);n.dummy;)i=e.successors(t)[0],e.removeNode(t),r.points.push({x:n.x,y:n.y}),n.dummy===`edge-label`&&(r.x=n.x,r.y=n.y,r.width=n.width,r.height=n.height),t=i,n=e.node(t)})}})),yg=o(((e,t)=>{var{applyWithChunking:n}=gg();t.exports={longestPath:r,slack:i};function r(e){var t={};function r(i){var a=e.node(i);if(Object.hasOwn(t,i))return a.rank;t[i]=!0;let o=e.outEdges(i).map(t=>t==null?1/0:r(t.w)-e.edge(t).minlen);var s=n(Math.min,o);return s===1/0&&(s=0),a.rank=s}e.sources().forEach(r)}function i(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}})),bg=o(((e,t)=>{var n=pg().Graph,r=yg().slack;t.exports=i;function i(e){var t=new n({directed:!1}),i=e.nodes()[0],c=e.nodeCount();t.setNode(i,{});for(var l,u;a(t,e){var o=a.v,s=i===o?a.w:o;!e.hasNode(s)&&!r(t,a)&&(e.setNode(s,{}),e.setEdge(i,s,{}),n(s))})}return e.nodes().forEach(n),e.nodeCount()}function o(e,t){return t.edges().reduce((n,i)=>{let a=1/0;return e.hasNode(i.v)!==e.hasNode(i.w)&&(a=r(t,i)),at.node(e).rank+=n)}})),xg=o(((e,t)=>{var n=bg(),r=yg().slack,i=yg().longestPath,a=pg().alg.preorder,o=pg().alg.postorder,s=gg().simplify;t.exports=c,c.initLowLimValues=f,c.initCutValues=l,c.calcCutValue=d,c.leaveEdge=m,c.enterEdge=h,c.exchangeEdges=g;function c(e){e=s(e),i(e);var t=n(e);f(t),l(t,e);for(var r,a;r=m(t);)a=h(t,e,r),g(t,e,r,a)}function l(e,t){var n=o(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(n=>u(e,t,n))}function u(e,t,n){var r=e.node(n).parent;e.edge(n,r).cutvalue=d(e,t,n)}function d(e,t,n){var r=e.node(n).parent,i=!0,a=t.edge(n,r),o=0;return a||=(i=!1,t.edge(r,n)),o=a.weight,t.nodeEdges(n).forEach(a=>{var s=a.v===n,c=s?a.w:a.v;if(c!==r){var l=s===i,u=t.edge(a).weight;if(o+=l?u:-u,v(e,n,c)){var d=e.edge(n,c).cutvalue;o+=l?-d:d}}}),o}function f(e,t){arguments.length<2&&(t=e.nodes()[0]),p(e,{},1,t)}function p(e,t,n,r,i){var a=n,o=e.node(r);return t[r]=!0,e.neighbors(r).forEach(i=>{Object.hasOwn(t,i)||(n=p(e,t,n,i,r))}),o.low=a,o.lim=n++,i?o.parent=i:delete o.parent,n}function m(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function h(e,t,n){var i=n.v,a=n.w;t.hasEdge(i,a)||(i=n.w,a=n.v);var o=e.node(i),s=e.node(a),c=o,l=!1;return o.lim>s.lim&&(c=s,l=!0),t.edges().filter(t=>l===y(e,e.node(t.v),c)&&l!==y(e,e.node(t.w),c)).reduce((e,n)=>r(t,n)!t.node(e).parent));n=n.slice(1),n.forEach(n=>{var r=e.node(n).parent,i=t.edge(n,r),a=!1;i||(i=t.edge(r,n),a=!0),t.node(n).rank=t.node(r).rank+(a?i.minlen:-i.minlen)})}function v(e,t,n){return e.hasEdge(t,n)}function y(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}})),Sg=o(((e,t)=>{var n=yg().longestPath,r=bg(),i=xg();t.exports=a;function a(e){var t=e.graph().ranker;if(t instanceof Function)return t(e);switch(e.graph().ranker){case`network-simplex`:c(e);break;case`tight-tree`:s(e);break;case`longest-path`:o(e);break;case`none`:break;default:c(e)}}var o=n;function s(e){n(e),r(e)}function c(e){i(e)}})),Cg=o(((e,t)=>{t.exports=n;function n(e){let t=i(e);e.graph().dummyChains.forEach(n=>{let i=e.node(n),a=i.edgeObj,o=r(e,t,a.v,a.w),s=o.path,c=o.lca,l=0,u=s[l],d=!0;for(;n!==a.w;){if(i=e.node(n),d){for(;(u=s[l])!==c&&e.node(u).maxRanko||s>t[c].lim));for(l=c,c=r;(c=e.parent(c))!==l;)a.push(c);return{path:i.concat(a.reverse()),lca:l}}function i(e){let t={},n=0;function r(i){let a=n;e.children(i).forEach(r),t[i]={low:a,lim:n++}}return e.children().forEach(r),t}})),wg=o(((e,t)=>{var n=gg();t.exports={run:r,cleanup:s};function r(e){let t=n.addDummyNode(e,`root`,{},`_root`),r=a(e),s=Object.values(r),c=n.applyWithChunking(Math.max,s)-1,l=2*c+1;e.graph().nestingRoot=t,e.edges().forEach(t=>e.edge(t).minlen*=l);let u=o(e)+1;e.children().forEach(n=>i(e,t,l,u,c,r,n)),e.graph().nodeRankFactor=l}function i(e,t,r,a,o,s,c){let l=e.children(c);if(!l.length){c!==t&&e.setEdge(t,c,{weight:0,minlen:r});return}let u=n.addBorderNode(e,`_bt`),d=n.addBorderNode(e,`_bb`),f=e.node(c);e.setParent(u,c),f.borderTop=u,e.setParent(d,c),f.borderBottom=d,l.forEach(n=>{i(e,t,r,a,o,s,n);let l=e.node(n),f=l.borderTop?l.borderTop:n,p=l.borderBottom?l.borderBottom:n,m=l.borderTop?a:2*a,h=f===p?o-s[c]+1:1;e.setEdge(u,f,{weight:m,minlen:h,nestingEdge:!0}),e.setEdge(p,d,{weight:m,minlen:h,nestingEdge:!0})}),e.parent(c)||e.setEdge(t,u,{weight:0,minlen:o+s[c]})}function a(e){var t={};function n(r,i){var a=e.children(r);a&&a.length&&a.forEach(e=>n(e,i+1)),t[r]=i}return e.children().forEach(e=>n(e,1)),t}function o(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function s(e){var t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(t=>{e.edge(t).nestingEdge&&e.removeEdge(t)})}})),Tg=o(((e,t)=>{var n=gg();t.exports=r;function r(e){function t(n){let r=e.children(n),a=e.node(n);if(r.length&&r.forEach(t),Object.hasOwn(a,`minRank`)){a.borderLeft=[],a.borderRight=[];for(let t=a.minRank,r=a.maxRank+1;t{t.exports={adjust:n,undo:r};function n(e){let t=e.graph().rankdir.toLowerCase();(t===`lr`||t===`rl`)&&i(e)}function r(e){let t=e.graph().rankdir.toLowerCase();(t===`bt`||t===`rl`)&&o(e),(t===`lr`||t===`rl`)&&(c(e),i(e))}function i(e){e.nodes().forEach(t=>a(e.node(t))),e.edges().forEach(t=>a(e.edge(t)))}function a(e){let t=e.width;e.width=e.height,e.height=t}function o(e){e.nodes().forEach(t=>s(e.node(t))),e.edges().forEach(t=>{let n=e.edge(t);n.points.forEach(s),Object.hasOwn(n,`y`)&&s(n)})}function s(e){e.y=-e.y}function c(e){e.nodes().forEach(t=>l(e.node(t))),e.edges().forEach(t=>{let n=e.edge(t);n.points.forEach(l),Object.hasOwn(n,`x`)&&l(n)})}function l(e){let t=e.x;e.x=e.y,e.y=t}})),Dg=o(((e,t)=>{var n=gg();t.exports=r;function r(e){let t={},r=e.nodes().filter(t=>!e.children(t).length),i=r.map(t=>e.node(t).rank),a=n.applyWithChunking(Math.max,i),o=n.range(a+1).map(()=>[]);function s(n){t[n]||(t[n]=!0,o[e.node(n).rank].push(n),e.successors(n).forEach(s))}return r.sort((t,n)=>e.node(t).rank-e.node(n).rank).forEach(s),o}})),Og=o(((e,t)=>{var n=gg().zipObject;t.exports=r;function r(e,t){let n=0;for(let r=1;rt)),a=t.flatMap(t=>e.outEdges(t).map(t=>({pos:i[t.w],weight:e.edge(t).weight})).sort((e,t)=>e.pos-t.pos)),o=1;for(;o{let t=e.pos+o;c[t]+=e.weight;let n=0;for(;t>0;)t%2&&(n+=c[t+1]),t=t-1>>1,c[t]+=e.weight;l+=e.weight*n}),l}})),kg=o(((e,t)=>{t.exports=n;function n(e,t=[]){return t.map(t=>{let n=e.inEdges(t);if(n.length){let r=n.reduce((t,n)=>{let r=e.edge(n),i=e.node(n.v);return{sum:t.sum+r.weight*i.order,weight:t.weight+r.weight}},{sum:0,weight:0});return{v:t,barycenter:r.sum/r.weight,weight:r.weight}}else return{v:t}})}})),Ag=o(((e,t)=>{var n=gg();t.exports=r;function r(e,t){let n={};return e.forEach((e,t)=>{let r=n[e.v]={indegree:0,in:[],out:[],vs:[e.v],i:t};e.barycenter!==void 0&&(r.barycenter=e.barycenter,r.weight=e.weight)}),t.edges().forEach(e=>{let t=n[e.v],r=n[e.w];t!==void 0&&r!==void 0&&(r.indegree++,t.out.push(n[e.w]))}),i(Object.values(n).filter(e=>!e.indegree))}function i(e){let t=[];function r(e){return t=>{t.merged||(t.barycenter===void 0||e.barycenter===void 0||t.barycenter>=e.barycenter)&&a(e,t)}}function i(t){return n=>{n.in.push(t),--n.indegree===0&&e.push(n)}}for(;e.length;){let n=e.pop();t.push(n),n.in.reverse().forEach(r(n)),n.out.forEach(i(n))}return t.filter(e=>!e.merged).map(e=>n.pick(e,[`vs`,`i`,`barycenter`,`weight`]))}function a(e,t){let n=0,r=0;e.weight&&(n+=e.barycenter*e.weight,r+=e.weight),t.weight&&(n+=t.barycenter*t.weight,r+=t.weight),e.vs=t.vs.concat(e.vs),e.barycenter=n/r,e.weight=r,e.i=Math.min(t.i,e.i),t.merged=!0}})),jg=o(((e,t)=>{var n=gg();t.exports=r;function r(e,t){let r=n.partition(e,e=>Object.hasOwn(e,`barycenter`)),o=r.lhs,s=r.rhs.sort((e,t)=>t.i-e.i),c=[],l=0,u=0,d=0;o.sort(a(!!t)),d=i(c,s,d),o.forEach(e=>{d+=e.vs.length,c.push(e.vs),l+=e.barycenter*e.weight,u+=e.weight,d=i(c,s,d)});let f={vs:c.flat(!0)};return u&&(f.barycenter=l/u,f.weight=u),f}function i(e,t,n){let r;for(;t.length&&(r=t[t.length-1]).i<=n;)t.pop(),e.push(r.vs),n++;return n}function a(e){return(t,n)=>t.barycentern.barycenter?1:e?n.i-t.i:t.i-n.i}})),Mg=o(((e,t)=>{var n=kg(),r=Ag(),i=jg();t.exports=a;function a(e,t,c,l){let u=e.children(t),d=e.node(t),f=d?d.borderLeft:void 0,p=d?d.borderRight:void 0,m={};f&&(u=u.filter(e=>e!==f&&e!==p));let h=n(e,u);h.forEach(t=>{if(e.children(t.v).length){let n=a(e,t.v,c,l);m[t.v]=n,Object.hasOwn(n,`barycenter`)&&s(t,n)}});let g=r(h,c);o(g,m);let _=i(g,l);if(f&&(_.vs=[f,_.vs,p].flat(!0),e.predecessors(f).length)){let t=e.node(e.predecessors(f)[0]),n=e.node(e.predecessors(p)[0]);Object.hasOwn(_,`barycenter`)||(_.barycenter=0,_.weight=0),_.barycenter=(_.barycenter*_.weight+t.order+n.order)/(_.weight+2),_.weight+=2}return _}function o(e,t){e.forEach(e=>{e.vs=e.vs.flatMap(e=>t[e]?t[e].vs:e)})}function s(e,t){e.barycenter===void 0?(e.barycenter=t.barycenter,e.weight=t.weight):(e.barycenter=(e.barycenter*e.weight+t.barycenter*t.weight)/(e.weight+t.weight),e.weight+=t.weight)}})),Ng=o(((e,t)=>{var n=pg().Graph,r=gg();t.exports=i;function i(e,t,r,i){i||=e.nodes();let o=a(e),s=new n({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(t=>e.node(t));return i.forEach(n=>{let i=e.node(n),a=e.parent(n);(i.rank===t||i.minRank<=t&&t<=i.maxRank)&&(s.setNode(n),s.setParent(n,a||o),e[r](n).forEach(t=>{let r=t.v===n?t.w:t.v,i=s.edge(r,n),a=i===void 0?0:i.weight;s.setEdge(r,n,{weight:e.edge(t).weight+a})}),Object.hasOwn(i,`minRank`)&&s.setNode(n,{borderLeft:i.borderLeft[t],borderRight:i.borderRight[t]}))}),s}function a(e){for(var t;e.hasNode(t=r.uniqueId(`_root`)););return t}})),Pg=o(((e,t)=>{t.exports=n;function n(e,t,n){let r={},i;n.forEach(n=>{let a=e.parent(n),o,s;for(;a;){if(o=e.parent(a),o?(s=r[o],r[o]=a):(s=i,i=a),s&&s!==a){t.setEdge(s,a);return}a=o}})}})),Fg=o(((e,t)=>{var n=Dg(),r=Og(),i=Mg(),a=Ng(),o=Pg(),s=pg().Graph,c=gg();t.exports=l;function l(e,t){if(t&&typeof t.customOrder==`function`){t.customOrder(e,l);return}let i=c.maxRank(e),a=u(e,c.range(1,i+1),`inEdges`),o=u(e,c.range(i-1,-1,-1),`outEdges`),s=n(e);if(f(e,s),t&&t.disableOptimalOrderHeuristic)return;let p=1/0,m;for(let t=0,n=0;n<4;++t,++n){d(t%2?a:o,t%4>=2),s=c.buildLayerMatrix(e);let i=r(e,s);i{r.has(e)||r.set(e,[]),r.get(e).push(t)};for(let t of e.nodes()){let n=e.node(t);if(typeof n.rank==`number`&&i(n.rank,t),typeof n.minRank==`number`&&typeof n.maxRank==`number`)for(let e=n.minRank;e<=n.maxRank;e++)e!==n.rank&&i(e,t)}return t.map(function(t){return a(e,t,n,r.get(t)||[])})}function d(e,t){let n=new s;e.forEach(function(e){let r=e.graph().root,a=i(e,r,n,t);a.vs.forEach((t,n)=>e.node(t).order=n),o(e,n,a.vs)})}function f(e,t){Object.values(t).forEach(t=>t.forEach((t,n)=>e.node(t).order=n))}})),Ig=o(((e,t)=>{var n=pg().Graph,r=gg();t.exports={positionX:h,findType1Conflicts:i,findType2Conflicts:a,addConflict:s,hasConflict:c,verticalAlignment:l,horizontalCompaction:u,alignCoordinates:p,findSmallestWidthAlignment:f,balance:m};function i(e,t){let n={};function r(t,r){let i=0,a=0,c=t.length,l=r[r.length-1];return r.forEach((t,u)=>{let d=o(e,t),f=d?e.node(d).order:c;(d||t===l)&&(r.slice(a,u+1).forEach(t=>{e.predecessors(t).forEach(r=>{let a=e.node(r),o=a.order;(o{l=t[r],e.node(l).dummy&&e.predecessors(l).forEach(t=>{let r=e.node(t);r.dummy&&(r.orderc)&&s(n,t,l)})})}function a(t,n){let r=-1,a,o=0;return n.forEach((s,c)=>{if(e.node(s).dummy===`border`){let t=e.predecessors(s);t.length&&(a=e.node(t[0]).order,i(n,o,c,r,a),o=c,r=a)}i(n,o,n.length,a,t.length)}),n}return t.length&&t.reduce(a),n}function o(e,t){if(e.node(t).dummy)return e.predecessors(t).find(t=>e.node(t).dummy)}function s(e,t,n){if(t>n){let e=t;t=n,n=e}let r=e[t];r||(e[t]=r={}),r[n]=!0}function c(e,t,n){if(t>n){let e=t;t=n,n=e}return!!e[t]&&Object.hasOwn(e[t],n)}function l(e,t,n,r){let i={},a={},o={};return t.forEach(e=>{e.forEach((e,t)=>{i[e]=e,a[e]=e,o[e]=t})}),t.forEach(e=>{let t=-1;e.forEach(e=>{let s=r(e);if(s.length){s=s.sort((e,t)=>o[e]-o[t]);let r=(s.length-1)/2;for(let l=Math.floor(r),u=Math.ceil(r);l<=u;++l){let r=s[l];a[e]===e&&tMath.max(e,a[t.v]+o.edge(t)),0)}function u(t){let n=o.outEdges(t).reduce((e,t)=>Math.min(e,a[t.w]-o.edge(t)),1/0),r=e.node(t);n!==1/0&&r.borderType!==s&&(a[t]=Math.max(a[t],n))}return c(l,o.predecessors.bind(o)),c(u,o.successors.bind(o)),Object.keys(r).forEach(e=>a[e]=a[n[e]]),a}function d(e,t,r,i){let a=new n,o=e.graph(),s=g(o.nodesep,o.edgesep,i);return t.forEach(t=>{let n;t.forEach(t=>{let i=r[t];if(a.setNode(i),n){var o=r[n],c=a.edge(o,i);a.setEdge(o,i,Math.max(s(e,t,n),c||0))}n=t})}),a}function f(e,t){return Object.values(t).reduce((t,n)=>{let r=-1/0,i=1/0;Object.entries(n).forEach(([t,n])=>{let a=_(e,t)/2;r=Math.max(n+a,r),i=Math.min(n-a,i)});let a=r-i;return a{[`l`,`r`].forEach(o=>{let s=n+o,c=e[s];if(c===t)return;let l=Object.values(c),u=i-r.applyWithChunking(Math.min,l);o!==`l`&&(u=a-r.applyWithChunking(Math.max,l)),u&&(e[s]=r.mapValues(c,e=>e+u))})})}function m(e,t){return r.mapValues(e.ul,(n,r)=>{if(t)return e[t.toLowerCase()][r];{let t=Object.values(e).map(e=>e[r]).sort((e,t)=>e-t);return(t[1]+t[2])/2}})}function h(e){let t=r.buildLayerMatrix(e),n=Object.assign(i(e,t),a(e,t)),o={},s;return[`u`,`d`].forEach(i=>{s=i===`u`?t:Object.values(t).reverse(),[`l`,`r`].forEach(t=>{t===`r`&&(s=s.map(e=>Object.values(e).reverse()));let a=(i===`u`?e.predecessors:e.successors).bind(e),c=l(e,s,n,a),d=u(e,s,c.root,c.align,t===`r`);t===`r`&&(d=r.mapValues(d,e=>-e)),o[i+t]=d})}),p(o,f(e,o)),m(o,e.graph().align)}function g(e,t,n){return(r,i,a)=>{let o=r.node(i),s=r.node(a),c=0,l;if(c+=o.width/2,Object.hasOwn(o,`labelpos`))switch(o.labelpos.toLowerCase()){case`l`:l=-o.width/2;break;case`r`:l=o.width/2;break}if(l&&(c+=n?l:-l),l=0,c+=(o.dummy?t:e)/2,c+=(s.dummy?t:e)/2,c+=s.width/2,Object.hasOwn(s,`labelpos`))switch(s.labelpos.toLowerCase()){case`l`:l=s.width/2;break;case`r`:l=-s.width/2;break}return l&&(c+=n?l:-l),l=0,c}}function _(e,t){return e.node(t).width}})),Lg=o(((e,t)=>{var n=gg(),r=Ig().positionX;t.exports=i;function i(e){e=n.asNonCompoundGraph(e),a(e),Object.entries(r(e)).forEach(([t,n])=>e.node(t).x=n)}function a(e){let t=n.buildLayerMatrix(e),r=e.graph().ranksep,i=0;t.forEach(t=>{let n=t.reduce((t,n)=>{let r=e.node(n).height;return t>r?t:r},0);t.forEach(t=>e.node(t).y=i+n/2),i+=n+r})}})),Rg=o(((e,t)=>{var n=_g(),r=vg(),i=Sg(),a=gg().normalizeRanks,o=Cg(),s=gg().removeEmptyRanks,c=wg(),l=Tg(),u=Eg(),d=Fg(),f=Lg(),p=gg(),m=pg().Graph;t.exports=h;function h(e,t){let n=t&&t.debugTiming?p.time:p.notime;n(`layout`,()=>{let r=n(` buildLayoutGraph`,()=>E(e));n(` runLayout`,()=>g(r,n,t)),n(` updateInputGraph`,()=>_(e,r))})}function g(e,t,m){t(` makeSpaceForEdgeLabels`,()=>D(e)),t(` removeSelfEdges`,()=>F(e)),t(` acyclic`,()=>n.run(e)),t(` nestingGraph.run`,()=>c.run(e)),t(` rank`,()=>i(p.asNonCompoundGraph(e))),t(` injectEdgeLabelProxies`,()=>O(e)),t(` removeEmptyRanks`,()=>s(e)),t(` nestingGraph.cleanup`,()=>c.cleanup(e)),t(` normalizeRanks`,()=>a(e)),t(` assignRankMinMax`,()=>k(e)),t(` removeEdgeLabelProxies`,()=>A(e)),t(` normalize.run`,()=>r.run(e)),t(` parentDummyChains`,()=>o(e)),t(` addBorderSegments`,()=>l(e)),t(` order`,()=>d(e,m)),t(` insertSelfEdges`,()=>I(e)),t(` adjustCoordinateSystem`,()=>u.adjust(e)),t(` position`,()=>f(e)),t(` positionSelfEdges`,()=>te(e)),t(` removeBorderNodes`,()=>ee(e)),t(` normalize.undo`,()=>r.undo(e)),t(` fixupEdgeLabelCoords`,()=>N(e)),t(` undoCoordinateSystem`,()=>u.undo(e)),t(` translateGraph`,()=>j(e)),t(` assignNodeIntersects`,()=>M(e)),t(` reversePoints`,()=>P(e)),t(` acyclic.undo`,()=>n.undo(e))}function _(e,t){e.nodes().forEach(n=>{let r=e.node(n),i=t.node(n);r&&(r.x=i.x,r.y=i.y,r.rank=i.rank,t.children(n).length&&(r.width=i.width,r.height=i.height))}),e.edges().forEach(n=>{let r=e.edge(n),i=t.edge(n);r.points=i.points,Object.hasOwn(i,`x`)&&(r.x=i.x,r.y=i.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var v=[`nodesep`,`edgesep`,`ranksep`,`marginx`,`marginy`],y={ranksep:50,edgesep:20,nodesep:50,rankdir:`tb`},b=[`acyclicer`,`ranker`,`rankdir`,`align`],x=[`width`,`height`,`rank`],S={width:0,height:0},C=[`minlen`,`weight`,`width`,`height`,`labeloffset`],w={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:`r`},T=[`labelpos`];function E(e){let t=new m({multigraph:!0,compound:!0}),n=re(e.graph());return t.setGraph(Object.assign({},y,ne(n,v),p.pick(n,b))),e.nodes().forEach(n=>{let r=ne(re(e.node(n)),x);Object.keys(S).forEach(e=>{r[e]===void 0&&(r[e]=S[e])}),t.setNode(n,r),t.setParent(n,e.parent(n))}),e.edges().forEach(n=>{let r=re(e.edge(n));t.setEdge(n,Object.assign({},w,ne(r,C),p.pick(r,T)))}),t}function D(e){let t=e.graph();t.ranksep/=2,e.edges().forEach(n=>{let r=e.edge(n);r.minlen*=2,r.labelpos.toLowerCase()!==`c`&&(t.rankdir===`TB`||t.rankdir===`BT`?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function O(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let n=e.node(t.v),r={rank:(e.node(t.w).rank-n.rank)/2+n.rank,e:t};p.addDummyNode(e,`edge-proxy`,r,`_ep`)}})}function k(e){let t=0;e.nodes().forEach(n=>{let r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=Math.max(t,r.maxRank))}),e.graph().maxRank=t}function A(e){e.nodes().forEach(t=>{let n=e.node(t);n.dummy===`edge-proxy`&&(e.edge(n.e).labelRank=n.rank,e.removeNode(t))})}function j(e){let t=1/0,n=0,r=1/0,i=0,a=e.graph(),o=a.marginx||0,s=a.marginy||0;function c(e){let a=e.x,o=e.y,s=e.width,c=e.height;t=Math.min(t,a-s/2),n=Math.max(n,a+s/2),r=Math.min(r,o-c/2),i=Math.max(i,o+c/2)}e.nodes().forEach(t=>c(e.node(t))),e.edges().forEach(t=>{let n=e.edge(t);Object.hasOwn(n,`x`)&&c(n)}),t-=o,r-=s,e.nodes().forEach(n=>{let i=e.node(n);i.x-=t,i.y-=r}),e.edges().forEach(n=>{let i=e.edge(n);i.points.forEach(e=>{e.x-=t,e.y-=r}),Object.hasOwn(i,`x`)&&(i.x-=t),Object.hasOwn(i,`y`)&&(i.y-=r)}),a.width=n-t+o,a.height=i-r+s}function M(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),i=e.node(t.w),a,o;n.points?(a=n.points[0],o=n.points[n.points.length-1]):(n.points=[],a=i,o=r),n.points.unshift(p.intersectRect(r,a)),n.points.push(p.intersectRect(i,o))})}function N(e){e.edges().forEach(t=>{let n=e.edge(t);if(Object.hasOwn(n,`x`))switch((n.labelpos===`l`||n.labelpos===`r`)&&(n.width-=n.labeloffset),n.labelpos){case`l`:n.x-=n.width/2+n.labeloffset;break;case`r`:n.x+=n.width/2+n.labeloffset;break}})}function P(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function ee(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),i=e.node(n.borderBottom),a=e.node(n.borderLeft[n.borderLeft.length-1]),o=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(o.x-a.x),n.height=Math.abs(i.y-r.y),n.x=a.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy===`border`&&e.removeNode(t)})}function F(e){e.edges().forEach(t=>{if(t.v===t.w){var n=e.node(t.v);n.selfEdges||=[],n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function I(e){p.buildLayerMatrix(e).forEach(t=>{var n=0;t.forEach((t,r)=>{var i=e.node(t);i.order=r+n,(i.selfEdges||[]).forEach(t=>{p.addDummyNode(e,`selfedge`,{width:t.label.width,height:t.label.height,rank:i.rank,order:r+ ++n,e:t.e,label:t.label},`_se`)}),delete i.selfEdges})})}function te(e){e.nodes().forEach(t=>{var n=e.node(t);if(n.dummy===`selfedge`){var r=e.node(n.e.v),i=r.x+r.width/2,a=r.y,o=n.x-i,s=r.height/2;e.setEdge(n.e,n.label),e.removeNode(t),n.label.points=[{x:i+2*o/3,y:a-s},{x:i+5*o/6,y:a-s},{x:i+o,y:a},{x:i+5*o/6,y:a+s},{x:i+2*o/3,y:a+s}],n.label.x=n.x,n.label.y=n.y}})}function ne(e,t){return p.mapValues(p.pick(e,t),Number)}function re(e){var t={};return e&&Object.entries(e).forEach(([e,n])=>{typeof e==`string`&&(e=e.toLowerCase()),t[e]=n}),t}})),zg=o(((e,t)=>{var n=gg(),r=pg().Graph;t.exports={debugOrdering:i};function i(e){let t=n.buildLayerMatrix(e),i=new r({compound:!0,multigraph:!0}).setGraph({});return e.nodes().forEach(t=>{i.setNode(t,{label:t}),i.setParent(t,`layer`+e.node(t).rank)}),e.edges().forEach(e=>i.setEdge(e.v,e.w,{},e.name)),t.forEach((e,t)=>{let n=`layer`+t;i.setNode(n,{rank:`same`}),e.reduce((e,t)=>(i.setEdge(e,t,{style:`invis`}),t))}),i}})),Bg=o(((e,t)=>{t.exports=`1.1.8`})),Vg=l(o(((e,t)=>{t.exports={graphlib:pg(),layout:Rg(),debug:zg(),util:{time:gg().time,notime:gg().notime},version:Bg()}}))(),1),Hg=200,Ug=56,Wg=20,Gg=40,Kg=20,qg=12,Jg=16,Yg=46,Xg=16,Zg=Hg,Qg=14;function $g(e){return{agents:e.agents,routes:e.routes,parallelGroups:e.parallelGroups,forEachGroups:e.forEachGroups,nodes:e.nodes,groupProgress:e.groupProgress,entryPoint:e.entryPoint,parentAgent:e.parentAgent,children:e.children}}function e_(e,t,n){let{nodes:r,edges:i}=a_(e,t,n);return{nodes:r,edges:i}}function t_(e,t,n){let r=[],i=(e,t,n)=>{for(let a of e){if((a.type||`agent`)!==`workflow`)continue;let e=-1;for(let n=t.length-1;n>=0;n--)if(t[n].slotKey===a.name){e=n;break}if(e<0)continue;let o=t[e];o.agents.length!==0&&(r.push(Ph([...n,e])),i(o.agents,o.children,[...n,e]))}let a=new Set;for(let e of t){let t=zh(e.slotKey);!t||a.has(t.group)||(a.add(t.group),r.push(Lh(n,t.group)))}};return i(e,t,n),r}function n_(e,t){let n=[],r=e,i=[];for(let e of t){let t=r[e];if(!t)break;let a=zh(t.slotKey);a&&n.push(Lh(i,a.group)),i.push(e),n.push(Ph(i)),r=t.children}return n}function r_(e,t){let n=[];for(let r=0;r0,m=p&&r.has(u),h={label:f?f.key:c.slotKey,name:c.slotKey,contextPath:t,type:`workflow`,status:c.status||`pending`,canExpand:p,expanded:m,childContextKey:u,childName:c.workflowName||void 0,iterationContextPath:e,isForEachIteration:!0};if(m){let t=a_($g(c),e,r,!0),l=t.width+Jg*2,u=t.height+Yg+Xg;i.push({id:d,type:`workflowNode`,position:{x:Jg,y:o},parentId:n,extent:`parent`,data:h,style:{width:l,height:u}});for(let e of t.nodes)e.parentId||(e.parentId=d,e.extent=`parent`,e.position={x:e.position.x+Jg,y:e.position.y+Yg}),i.push(e);for(let e of t.edges)a.push(e);o+=u+Qg,s=Math.max(s,l)}else i.push({id:d,type:`workflowNode`,position:{x:Jg,y:o},parentId:n,extent:`parent`,data:h}),o+=70}return{nodes:i,edges:a,width:s+Jg*2,height:(e.length>0?o-Qg:Yg)+Xg}}function a_(e,t,n,r=!1){let i=[],a=[],o=new Set,s=new Set,c=e.parentAgent!=null,l=e=>Fh(t,e),u=[],d=[],f=[],p=new Map;for(let t of e.parallelGroups)for(let e of t.agents)s.add(e),p.set(e,t.name);for(let n of e.parallelGroups){let r=e.nodes[n.name],a=n.agents.length,s=Gg+a*Ug+(a-1)*qg+Kg;i.push({id:l(n.name),type:`groupNode`,position:{x:0,y:0},data:{label:n.name,name:n.name,contextPath:t,type:`parallel_group`,status:r?.status||`pending`,groupName:n.name,progress:e.groupProgress[n.name]},style:{width:240,height:s}});for(let r=0;r0,u=Lh(t,r.name);if(c&&n.has(u)){let o=i_(s,t,u,n);i.push({id:l(r.name),type:`groupNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:`for_each_group`,status:a?.status||`pending`,groupName:r.name,progress:e.groupProgress[r.name],expanded:!0,canExpand:!0,groupExpansionKey:u},style:{width:o.width,height:o.height}});for(let e of o.nodes)d.push(e);for(let e of o.edges)f.push(e)}else i.push({id:l(r.name),type:`groupNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:`for_each_group`,status:a?.status||`pending`,groupName:r.name,progress:e.groupProgress[r.name],expanded:!1,canExpand:c,groupExpansionKey:c?u:void 0}});o.add(r.name)}for(let r of e.agents){if(o.has(r.name)||s.has(r.name))continue;let a=r.type||`agent`,c=e.nodes[r.name],d=`agentNode`;if(a===`script`?d=`scriptNode`:a===`set`?d=`setNode`:a===`human_gate`||a===`questions`?d=`gateNode`:a===`workflow`?d=`workflowNode`:a===`wait`?d=`waitNode`:a===`terminate`&&(d=`terminateNode`),a===`workflow`){let s=-1;for(let t=e.children.length-1;t>=0;t--)if(e.children[t].slotKey===r.name){s=t;break}let d=s>=0?e.children[s]:void 0,f=s>=0?Ph([...t,s]):void 0,p=!!d&&d.agents.length>0;if(p&&f!=null&&n.has(f)&&d){let e=a_($g(d),[...t,s],n,!0),o=e.width+Jg*2,p=e.height+Yg+Xg;i.push({id:l(r.name),type:`workflowNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:a,status:c?.status||`pending`,expanded:!0,canExpand:!0,childContextKey:f,childName:d.workflowName||void 0},style:{width:o,height:p}}),u.push({containerId:l(r.name),sub:e})}else i.push({id:l(r.name),type:`workflowNode`,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:a,status:c?.status||`pending`,expanded:!1,canExpand:p,childContextKey:f,childName:d?.workflowName||void 0}});o.add(r.name);continue}i.push({id:l(r.name),type:d,position:{x:0,y:0},data:{label:r.name,name:r.name,contextPath:t,type:a,status:c?.status||`pending`}}),o.add(r.name)}let m=!1;for(let t of e.routes)t.to===`$end`&&(m=!0);if(m){let n=e.nodes.$end;i.push({id:l(`$end`),type:c?`egressNode`:`endNode`,position:{x:0,y:0},data:{label:`$end`,name:`$end`,contextPath:t,type:c?`egress`:`end`,status:n?.status||`pending`,...c&&!r?{parentAgent:e.parentAgent??void 0}:{}}})}if(e.entryPoint){let n=e.nodes.$start;i.push({id:l(`$start`),type:c?`ingressNode`:`startNode`,position:{x:0,y:0},data:{label:`$start`,name:`$start`,contextPath:t,type:c?`ingress`:`start`,status:n?.status||`pending`,...c&&!r?{parentAgent:e.parentAgent??void 0}:{}}}),a.push({id:`${l(`$start`)}->@entry`,source:l(`$start`),target:l(e.entryPoint),type:`animatedEdge`,data:{},animated:!1})}let h=new Set(i.map(e=>e.id)),g=new Map;for(let e of i)e.parentId&&g.set(e.id,e.parentId);let _=new Map;for(let t of e.routes){let e=g.get(l(t.from))??l(t.from),n=g.get(l(t.to))??l(t.to);if(!h.has(e)||!h.has(n)||e===n)continue;let r=`${e}->${n}`,i=_.get(r);if(i){i.when!==t.when&&(a[i.idx].data={when:void 0});continue}let o=a.length;_.set(r,{when:t.when,idx:o});let s=`${r}${t.when?`[${t.when}]`:``}`;a.push({id:s,source:e,target:n,type:`animatedEdge`,data:{when:t.when},animated:!1})}let{width:v,height:y}=c_(i,a,o_(i,a,l(`$start`)));for(let{containerId:e,sub:t}of u){for(let n of t.nodes)n.parentId||(n.parentId=e,n.extent=`parent`,n.position={x:n.position.x+Jg,y:n.position.y+Yg}),i.push(n);for(let e of t.edges)a.push(e)}for(let e of d)i.push(e);for(let e of f)a.push(e);return{nodes:i,edges:a,width:v,height:y}}function o_(e,t,n){let r=new Set(e.filter(e=>!e.parentId).map(e=>e.id)),i=new Map;for(let e of t)!r.has(e.source)||!r.has(e.target)||(i.has(e.source)||i.set(e.source,[]),i.get(e.source).push({target:e.target,edgeId:e.id}));for(let e of i.values())e.sort((e,t)=>e.targett.target));let a=new Set,o=new Set,s=new Set,c=e=>{s.add(e),o.add(e);for(let{target:t,edgeId:n}of i.get(e)??[])o.has(t)?a.add(n):s.has(t)||c(t);o.delete(e)};r.has(n)&&c(n);for(let e of[...i.keys()].sort())s.has(e)||c(e);return a}function s_(e){let t=e.style?.width,n=e.style?.height;return typeof t==`number`&&typeof n==`number`?{w:t,h:n}:{w:Hg,h:Ug}}function c_(e,t,n){let r=new Vg.default.graphlib.Graph;r.setDefaultEdgeLabel(()=>({})),r.setGraph({rankdir:`TB`,nodesep:50,ranksep:70,marginx:30,marginy:30});for(let t of e){if(t.parentId)continue;let{w:e,h:n}=s_(t);r.setNode(t.id,{width:e,height:n})}for(let e of t)!r.hasNode(e.source)||!r.hasNode(e.target)||(n.has(e.id)?r.setEdge(e.target,e.source):r.setEdge(e.source,e.target));Vg.default.layout(r);let i=1/0,a=1/0,o=-1/0,s=-1/0;for(let t of e){if(t.parentId)continue;let e=r.node(t.id);if(!e)continue;let{w:n,h:c}=s_(t),l=e.x-n/2,u=e.y-c/2;t.position={x:l,y:u},i=Math.min(i,l),a=Math.min(a,u),o=Math.max(o,l+n),s=Math.max(s,u+c)}if(!Number.isFinite(i))return{width:Hg,height:Ug};for(let t of e)t.parentId||(t.position={x:t.position.x-i,y:t.position.y-a});return{width:o-i,height:s-a}}var l_=400;function u_(){let e=new URLSearchParams(window.location.search);return{subworkflowPath:e.get(`subworkflow`),agent:e.get(`agent`)}}function d_(e,t){let n=[],r=e;for(let e of t){let t=-1;for(let n=r.length-1;n>=0;n--)if(r[n].slotKey===e){t=n;break}if(t===-1){for(let n=r.length-1;n>=0;n--)if(r[n].parentAgent===e){t=n;break}}if(t===-1)return{path:n,failedSegment:e};n.push(t),r=r[t].children}return{path:n,failedSegment:null}}function f_(e,t){let n=e,r=null;for(let e of t){if(r=n[e]??null,!r)return null;n=r.children}return r}function p_(e,t,n=[]){let r=[];for(let i=0;ie.name===t)&&r.push({path:o,ctx:a}),a.children.length>0&&r.push(...p_(a.children,t,o))}return r}function m_(e){return e.length===0?null:[...e].sort((e,t)=>{let n=+(e.ctx.status===`running`),r=+(t.ctx.status===`running`);if(n!==r)return r-n;if(e.path.length!==t.path.length)return t.path.length-e.path.length;for(let n=0;n{if(n.current||!s)return;let e=null,c=null,l=null,u=null,d=(e,t)=>{let n=B.getState(),r=n.subworkflowContexts;e.length>0&&!f_(r,e)&&console.warn(`[use-deep-link] reveal target path is not fully materialized; expanding only the resolved prefix`,e),n.expandContexts(n_(r,e)),B.setState({viewContextPath:[],selectedNode:t})},f=e=>{let t=0,n=()=>{l=null;let a=i(e)?.measured;a?.width&&a?.height?(qh(l_),r({nodes:[{id:e}],padding:.5,duration:l_})):t++<40?l=requestAnimationFrame(n):(console.warn(`[use-deep-link] node "${e}" was not measured in time; fitting the whole graph instead`),qh(l_),r({padding:.2,duration:l_}))};l=requestAnimationFrame(n)},p=()=>{if(n.current)return;n.current=!0,e&&clearTimeout(e),c&&clearTimeout(c),u&&u();let r=B.getState();if(r.agents.length===0){t({message:`Workflow state did not load.`});return}let i=[];if(a){let e=a.split(`/`).filter(Boolean),n=d_(r.subworkflowContexts,e);if(n.failedSegment){let r=e.slice(0,n.path.length).join(`/`);d(n.path,null),t({message:`Subworkflow "${n.failedSegment}" not found${r?` (resolved: ${r})`:``}. It may not have started yet.`});return}i=n.path}if(o){if((i.length===0?r.agents:f_(r.subworkflowContexts,i)?.agents??[]).some(e=>e.name===o)){let e=Fh(i,o);d(i,e),f(e);return}let e=p_(r.subworkflowContexts,o);if(e.length===0){let e=a||`root workflow`;d(i,null),t({message:`Agent "${o}" not found in ${e}.`});return}if(a){let n=e.slice(0,5).map(e=>h_(r.subworkflowContexts,e.path)).join(`, `),s=e.length>5?`, and ${e.length-5} more`:``;d(i,null),t({message:`Agent "${o}" not found in ${a}. Found in: ${n}${s}`});return}let n=m_(e),s=Fh(n.path,o);d(n.path,s),f(s);return}if(d(i,null),i.length>0){let e=f_(r.subworkflowContexts,i);e&&f(Fh(i.slice(0,-1),e.slotKey))}},m=()=>{try{p()}catch(e){console.warn(`[use-deep-link] failed to apply deep-link target`,e),t({message:`Could not resolve the deep-link target.`})}},h=()=>{let e=B.getState();if(e.agents.length===0)return!1;if(e.workflowStatus!==`running`&&e.workflowStatus!==`pending`)return!0;if(a){let t=a.split(`/`).filter(Boolean),{failedSegment:n}=d_(e.subworkflowContexts,t);if(n)return!1}return!(o&&!a&&!e.agents.some(e=>e.name===o)&&p_(e.subworkflowContexts,o).length===0)},g=()=>{e&&clearTimeout(e),e=setTimeout(()=>{n.current||h()&&m()},200)};return u=B.subscribe(g),c=setTimeout(()=>{n.current||m()},5e3),g(),()=>{e&&clearTimeout(e),c&&clearTimeout(c),l!=null&&cancelAnimationFrame(l),u&&u()}},[s,a,o,r,i]),e}function __(e){let t=new Map;for(let n of e)t.set(n.id,n);let n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,a=r,o={x:0,y:0};for(;a&&!i.has(a.id);){i.add(a.id),e.push(a);let r=a.parentId;if(r===void 0)break;let s=n.get(r);if(s){o=s;break}a=t.get(r)}for(let t=e.length-1;t>=0;t--){let r=e[t];o={x:o.x+r.position.x,y:o.y+r.position.y},n.set(r.id,o)}}return n}function v_(e,t){return e?.data?.childContextKey===t||e?.data?.groupExpansionKey===t}function y_(e,t=__(e.prevNodes)){let{prevNodes:n,nextNodes:r,anchorKeyHint:i,viewport:a,paneSize:o}=e,s=new Map;for(let e of n)s.set(e.id,e);let c=r.filter(e=>s.has(e.id));if(c.length===0)return null;if(i!==null){let e=c.find(e=>v_(e,i)||v_(s.get(e.id),i));if(e)return e.id}if(o.width<=0||o.height<=0)return null;let l={x:(-a.x+o.width/2)/a.zoom,y:(-a.y+o.height/2)/a.zoom},u=null,d=1/0;for(let e of c){let n=t.get(e.id);if(!n)continue;let r=n.x-l.x,i=n.y-l.y,a=r*r+i*i;(a1||n===null)return{hint:null,stickyRebuilds:0};let s=r+1;return{hint:s>2?null:n,stickyRebuilds:s}}var X={pending:`#6b7280`,running:`#3b82f6`,completed:`#22c55e`,failed:`#ef4444`,paused:`#f59e0b`,idle:`#6b7280`,waiting:`#a855f7`};function S_({data:e,children:t}){let[n,r]=(0,v.useState)(!1),i=(0,v.useRef)(null),a=(0,v.useCallback)(()=>{i.current=setTimeout(()=>r(!0),200)},[]),o=(0,v.useCallback)(()=>{i.current&&clearTimeout(i.current),r(!1)},[]),s=X[e.status]||X.pending;return(0,H.jsxs)(`div`,{className:`relative`,onMouseEnter:a,onMouseLeave:o,children:[t,n&&(0,H.jsxs)(`div`,{className:U(`absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-2`,`bg-[var(--surface-raised)] border border-[var(--border)] shadow-lg`,`rounded-lg px-3 py-2 max-w-[260px] pointer-events-none`,`animate-[tooltip-in_150ms_ease-out]`),children:[(0,H.jsx)(`div`,{className:`absolute top-full left-1/2 -translate-x-1/2 w-0 h-0 border-x-[6px] border-x-transparent border-t-[6px] border-t-[var(--border)]`}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5 text-[11px]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`w-2 h-2 rounded-full flex-shrink-0`,style:{backgroundColor:s}}),(0,H.jsx)(`span`,{className:`font-medium text-[var(--text)] capitalize`,children:e.status}),e.iteration!=null&&e.iteration>1&&(0,H.jsxs)(`span`,{className:`text-[var(--text-muted)] ml-auto`,children:[`iter `,e.iteration]})]}),(0,H.jsx)(`div`,{className:`h-px bg-[var(--border)]`}),(0,H.jsxs)(`div`,{className:`grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5`,children:[e.elapsed!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Elapsed`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] font-mono`,children:gt(e.elapsed)})]}),e.model&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Model`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] truncate`,children:e.model})]}),e.tokens!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Tokens`}),(0,H.jsxs)(`span`,{className:`text-[var(--text)] font-mono`,children:[_t(e.tokens),e.inputTokens!=null&&e.outputTokens!=null&&(0,H.jsxs)(`span`,{className:`text-[var(--text-muted)]`,children:[` `,`(`,_t(e.inputTokens),`↑ `,_t(e.outputTokens),`↓)`]})]})]}),e.costUsd!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Cost`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] font-mono`,children:vt(e.costUsd)})]}),e.exitCode!=null&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Exit code`}),(0,H.jsx)(`span`,{className:U(`font-mono`,e.exitCode===0?`text-[var(--completed)]`:`text-[var(--failed)]`),children:e.exitCode})]}),e.selectedOption&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Selected`}),(0,H.jsx)(`span`,{className:`text-[var(--text)] truncate`,children:e.selectedOption})]}),e.terminationStatus&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)]`,children:`Termination`}),(0,H.jsx)(`span`,{className:U(`font-mono capitalize`,e.terminationStatus===`success`?`text-[var(--completed)]`:`text-[var(--failed)]`),children:e.terminationStatus})]})]}),e.reason&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`h-px bg-[var(--border)]`}),(0,H.jsxs)(`div`,{className:U(`leading-tight break-words`,e.terminationStatus===`failed`?`text-red-400`:`text-[var(--text)]`),children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] mr-1`,children:`Reason:`}),e.reason.slice(0,160),e.reason.length>160?`...`:``]})]}),e.errorMessage&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`h-px bg-[var(--border)]`}),(0,H.jsxs)(`div`,{className:`text-red-400 leading-tight`,children:[e.errorType&&(0,H.jsxs)(`span`,{className:`font-medium`,children:[e.errorType,`: `]}),(0,H.jsxs)(`span`,{className:`break-words`,children:[e.errorMessage.slice(0,120),e.errorMessage.length>120?`...`:``]})]})]})]})]})]})}var C_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Vh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.model,c=r?.tokens,l=r?.input_tokens,u=r?.output_tokens,d=r?.cost_usd,f=r?.iteration,p=r?.error_type,m=r?.error_message,h=r?.context_pct,g=r?.provider_tier,_=r?.provider_name,v=w_(r?.startedAt,i),y=T_(i),b=(()=>{if(i===`failed`&&m)return{text:m.length>40?m.slice(0,37)+`...`:m,className:`text-red-400`};if(i===`running`)return{text:v,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return o!=null&&e.push(gt(o)),c!=null&&e.push(`${_t(c)} tok`),d!=null&&e.push(vt(d)),{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(S_,{data:{status:i,elapsed:o,model:s,tokens:c,inputTokens:l,outputTokens:u,costUsd:d,iteration:f,errorType:p,errorMessage:m},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,y),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(k,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),f!=null&&f>1&&(0,H.jsxs)(`span`,{className:`flex-shrink-0 inline-flex items-center justify-center px-1.5 py-0.5 rounded-full text-[9px] font-bold leading-none`,style:{backgroundColor:`${a}25`,color:a},children:[`x`,f]}),g===`experimental`&&(0,H.jsx)(`span`,{className:`flex-shrink-0 inline-flex items-center justify-center px-1.5 py-0.5 rounded-full text-[9px] font-bold leading-none uppercase tracking-wide`,style:{backgroundColor:`rgba(245, 158, 11, 0.18)`,color:`#f59e0b`},title:`Experimental provider: ${_??`unknown`}`,children:`exp`})]}),b.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,b.className),children:b.text})]}),h!=null&&(0,H.jsx)(`div`,{className:`absolute bottom-0 left-0 right-0 h-[2px] rounded-b-lg overflow-hidden`,style:{backgroundColor:`rgba(255,255,255,0.06)`},children:(0,H.jsx)(`div`,{className:U(`h-full transition-all duration-500`,h>=90?`animate-[context-pulse_2s_ease-in-out_infinite]`:``),style:{width:`${Math.min(h,100)}%`,backgroundColor:h>=90?`#ef4444`:h>=70?`#f59e0b`:`#22c55e`}})})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function w_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(gt((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(gt((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function T_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var E_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Vh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.exit_code,c=r?.error_type,l=r?.error_message,u=D_(r?.startedAt,i),d=O_(i),f=(()=>{if(i===`failed`&&l)return{text:l.length>40?l.slice(0,37)+`...`:l,className:`text-red-400`};if(i===`running`)return{text:u,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return o!=null&&e.push(gt(o)),s!=null&&e.push(`exit ${s}`),{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(S_,{data:{status:i,elapsed:o,exitCode:s,errorType:c,errorMessage:l},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,d),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(Ee,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),f.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,f.className),children:f.text})]})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function D_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(gt((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(gt((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function O_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var k_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Vh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.set_output_keys,c=r?.set_value_repr,l=r?.error_type,u=r?.error_message,d=A_(r?.startedAt,i),f=j_(i),p=(()=>{if(i===`failed`&&u)return{text:u.length>40?u.slice(0,37)+`...`:u,className:`text-red-400`};if(i===`running`)return{text:d,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];if(o!=null&&e.push(gt(o)),s&&s.length>0)e.push(`${s.length} key${s.length===1?``:`s`}`);else if(c){let t=c.length>24?c.slice(0,21)+`…`:c;e.push(t)}return{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(S_,{data:{status:i,elapsed:o,errorType:l,errorMessage:u},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,f),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(Oe,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),p.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,p.className),children:p.text})]})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function A_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(gt((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(gt((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function j_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var M_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Vh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.selected_option,s=N_(i);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(S_,{data:{status:i,selectedOption:o},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 border-dashed bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`waiting`&&`shadow-[0_0_12px_var(--waiting-muted)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,s),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`waiting`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(Se,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),i===`waiting`&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--waiting)] truncate leading-tight`,children:`Awaiting input...`}),i===`completed`&&o&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] truncate leading-tight`,children:o})]})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function N_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`||e===`waiting`?r(`node-activate`):(n===`running`||n===`waiting`)&&e===`completed`&&r(`node-complete`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var P_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=n.type===`for_each_group`?ye:ce,i=n.progress,a=Vh(n)?.status||n.status||`pending`,o=X[a]||X.pending,s=F_(a),c=B(e=>e.toggleContextExpanded),l=n.expanded===!0,u=n.canExpand===!0,d=n.groupExpansionKey,f=e=>{e.stopPropagation(),d!=null&&c(d)},p=i?`${i.completed+i.failed}/${i.total}${i.failed>0?` (${i.failed} failed)`:``}`:null,m=i&&i.total>0?(i.completed+i.failed)/i.total*100:0,h=i!=null&&i.failed>0;return l?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(`div`,{className:U(`w-full h-full rounded-xl border-2 border-dashed bg-[var(--surface)]/40 transition-all duration-300 animate-[subflow-expand-in_200ms_ease-out]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,a===`running`&&`shadow-[0_0_16px_var(--running-glow)]`,s),style:{borderColor:o,minHeight:`100%`},children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-2`,children:[(0,H.jsx)(`button`,{onClick:f,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Collapse for-each iterations`,children:(0,H.jsx)(j,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(r,{className:`w-3.5 h-3.5 flex-shrink-0`,style:{color:o}}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)] truncate`,children:n.label}),p&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] font-mono flex-shrink-0`,children:p})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsxs)(`div`,{className:U(`flex flex-col gap-1 px-4 py-3 rounded-xl border-2 border-dashed bg-[var(--surface)]/80 min-w-[180px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,a===`running`&&`shadow-[0_0_16px_var(--running-glow)]`,s),style:{borderColor:o,minHeight:`100%`},children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[u&&(0,H.jsx)(`button`,{onClick:f,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0 -ml-1`,title:`Expand for-each iterations inline`,children:(0,H.jsx)(M,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(r,{className:`w-3.5 h-3.5`,style:{color:o}}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text-secondary)]`,children:n.label})]}),p&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] font-mono`,children:p}),i&&i.total>0&&a===`running`&&(0,H.jsx)(`div`,{className:`w-full h-1 rounded-full bg-[var(--border)] overflow-hidden mt-0.5`,children:(0,H.jsx)(`div`,{className:`h-full rounded-full transition-all duration-500 ease-out`,style:{width:`${m}%`,backgroundColor:h?`var(--failed)`:`var(--completed)`}})})]}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function F_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var I_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Vh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.elapsed,s=r?.error_message,c=B(e=>e.toggleContextExpanded),l=n.expanded===!0,u=n.canExpand===!0,d=n.childContextKey,f=n.childName,p=e=>{e.stopPropagation(),d!=null&&c(d)};if(l)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(`div`,{className:U(`w-full h-full rounded-xl border-2 border-dashed bg-[var(--surface)]/40 transition-all duration-300 animate-[subflow-expand-in_200ms_ease-out]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_16px_var(--running-glow)]`),style:{borderColor:a,minHeight:`100%`},children:(0,H.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-2`,children:[(0,H.jsx)(`button`,{onClick:p,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Collapse subworkflow`,children:(0,H.jsx)(j,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(ue,{className:`w-3.5 h-3.5 flex-shrink-0`,style:{color:a}}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)] truncate`,children:n.label}),f&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] truncate`,children:[`· `,f]})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]});let m=(()=>{if(i===`failed`&&s)return{text:s.length>35?s.slice(0,32)+`...`:s,className:`text-red-400`};if(i===`running`)return{text:f||`Running subworkflow…`,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return f&&e.push(f),o!=null&&e.push(`${o.toFixed(1)}s`),{text:e.join(` · `)||`Done`,className:`text-[var(--text-muted)]`}}return{text:f||null,className:`text-[var(--text-muted)]`}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(S_,{data:{status:i,elapsed:o,errorType:void 0,errorMessage:s,iteration:void 0},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[240px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`),style:{borderColor:a,borderStyle:`dashed`},children:[u?(0,H.jsx)(`button`,{onClick:p,className:`nodrag flex items-center justify-center w-5 h-5 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Expand subworkflow inline (double-click to focus)`,children:(0,H.jsx)(M,{className:`w-3.5 h-3.5`})}):(0,H.jsx)(`div`,{className:`flex items-center justify-center w-5 h-5 flex-shrink-0 text-[var(--text-muted)] opacity-25`,title:`Subworkflow structure not yet known (will be expandable once it starts)`,"aria-hidden":`true`,children:(0,H.jsx)(M,{className:`w-3.5 h-3.5`})}),(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(ue,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label})}),m.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,m.className),children:m.text})]})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})}),L_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Vh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.duration_seconds??r?.requested_seconds,s=r?.waited_seconds,c=r?.elapsed,l=r?.interrupted,u=r?.error_type,d=r?.error_message,f=R_(r?.startedAt,i),p=z_(i),m=(()=>{if(i===`failed`&&d)return{text:d.length>40?d.slice(0,37)+`...`:d,className:`text-red-400`};if(i===`running`)return{text:`${f}${typeof o==`number`?` / ${gt(o)}`:``}`,className:`text-[var(--text-muted)]`};if(i===`completed`){let e=[];return s==null?c!=null&&e.push(gt(c)):e.push(gt(s)),l&&e.push(`interrupted`),{text:e.join(` · `)||null,className:`text-[var(--text-muted)]`}}return i===`pending`&&typeof o==`number`?{text:gt(o),className:`text-[var(--text-muted)]`}:{text:null,className:``}})();return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(S_,{data:{status:i,elapsed:s??c,errorType:u,errorMessage:d},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[220px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`running`&&`shadow-[0_0_12px_var(--running-glow)]`,p),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,i===`running`&&`animate-pulse`),style:{backgroundColor:`${a}20`},children:(0,H.jsx)(te,{className:`w-3.5 h-3.5`,style:{color:a}})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),m.text&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight`,m.className),children:m.text})]})]})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})});function R_(e,t){let n=B(e=>e.replayMode),r=B(e=>e.lastEventTime),[i,a]=(0,v.useState)(`0.0s`),o=(0,v.useRef)(null);return(0,v.useEffect)(()=>{if(t===`running`){if(n){o.current&&clearInterval(o.current);let t=e??r??0;a(gt((r??t)-t));return}let t=e==null?Date.now():e*1e3,i=()=>{a(gt((Date.now()-t)/1e3))};return i(),o.current=setInterval(i,1e3),()=>{o.current&&clearInterval(o.current)}}else o.current&&clearInterval(o.current)},[t,e,n,r]),i}function z_(e){let t=(0,v.useRef)(e),[n,r]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let n=t.current;if(t.current=e,n===e)return;e===`running`?r(`node-activate`):n===`running`&&(e===`completed`||e===`failed`)&&r(e===`completed`?`node-complete`:`node-fail`);let i=setTimeout(()=>r(``),400);return()=>clearTimeout(i)},[e]),n}var B_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=Vh(n),i=r?.status||n.status||`pending`,a=X[i]||X.pending,o=r?.termination_reason,s=r?.termination_status,c=r?.error_message,l=r?.error_type,u=o||c,d=i===`failed`?`text-red-400`:i===`completed`?`text-green-400`:`text-[var(--text-muted)]`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(S_,{data:{status:i,reason:o,terminationStatus:s,errorType:l,errorMessage:c},children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-3 py-1.5 rounded-lg border-2 bg-[var(--node-bg)] min-w-[140px] max-w-[260px] transition-all duration-300`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i===`completed`&&`shadow-[0_0_12px_var(--completed-muted)]`,i===`failed`&&`shadow-[0_0_12px_var(--failed-muted)]`),style:{borderColor:a},children:[(0,H.jsx)(`div`,{className:`flex items-center justify-center w-6 h-6 rounded-md flex-shrink-0`,style:{backgroundColor:`${a}20`},children:(0,H.jsx)(ge,{className:`w-3.5 h-3.5`,style:{color:a},fill:i===`completed`||i===`failed`?a:`transparent`,fillOpacity:.2})}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:n.label}),(0,H.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-[var(--text-muted)] truncate leading-tight`,children:[`terminate`,s?` · ${s}`:``]}),u&&(0,H.jsx)(`span`,{className:U(`text-[10px] truncate leading-tight mt-0.5`,d),title:u,children:u.length>50?u.slice(0,47)+`...`:u})]})]})})]})}),V_=(0,v.memo)(function({data:e,selected:t}){let n=e.status||`pending`,r=n===`completed`,i=n===`failed`,a=!r&&!i,o=r?X.completed:i?X.failed:X.pending;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 transition-all duration-300`,r?`bg-[var(--completed)] shadow-[0_0_16px_var(--completed-muted)]`:i?`bg-[var(--failed)] shadow-[0_0_16px_var(--failed-muted)]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`),style:{borderColor:o},children:r?(0,H.jsx)(A,{className:`w-5 h-5 text-white`,strokeWidth:3}):i?(0,H.jsx)(Te,{className:`w-3.5 h-3.5 text-white`,fill:`white`}):(0,H.jsx)(A,{className:`w-5 h-5`,strokeWidth:2.5,style:{color:a?X.pending:o}})})]})}),H_=(0,v.memo)(function({data:e,selected:t}){let n=e.status||`pending`,r=X[n]||X.pending,i=n===`running`||n===`completed`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 transition-all duration-300`,i?`bg-[var(--completed)]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i&&`shadow-[0_0_12px_var(--completed-muted)]`),style:{borderColor:r},children:(0,H.jsx)(ve,{className:`w-4 h-4 ml-0.5`,style:{color:i?`white`:r}})}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})}),U_=`#a78bfa`,W_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=n.status||`pending`,i=r===`running`||r===`completed`,a=i?U_:X[r]||U_,o=n.parentAgent,s=B(e=>e.navigateUp);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-1`,children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 border-dashed transition-all duration-300 cursor-pointer`,i?`bg-[#a78bfa]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`,i&&`shadow-[0_0_12px_rgba(167,139,250,0.4)]`),style:{borderColor:a},onDoubleClick:e=>{e.stopPropagation(),s()},children:(0,H.jsx)(E,{className:`w-4 h-4`,style:{color:i?`white`:a}})}),o&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] whitespace-nowrap`,children:[`from `,(0,H.jsx)(`span`,{className:`font-medium text-[var(--text)]`,children:o})]})]}),(0,H.jsx)(_p,{type:`source`,position:q.Bottom,className:`!bg-[var(--border)] !border-none !w-2 !h-2`})]})}),G_=`#a78bfa`,K_=(0,v.memo)(function({data:e,selected:t}){let n=e,r=n.status||`pending`,i=r===`completed`,a=r===`failed`,o=i?G_:a?X.failed:G_,s=n.parentAgent,c=B(e=>e.navigateUp);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_p,{type:`target`,position:q.Top,className:`!bg-[var(--border)] !border-none !w-2 !h-2`}),(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-1`,children:[(0,H.jsx)(`div`,{className:U(`flex items-center justify-center w-11 h-11 rounded-full border-2 border-dashed transition-all duration-300 cursor-pointer`,i?`bg-[#a78bfa] shadow-[0_0_12px_rgba(167,139,250,0.4)]`:a?`bg-[var(--failed)] shadow-[0_0_16px_var(--failed-muted)]`:`bg-[var(--node-bg)]`,t&&`ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]`),style:{borderColor:o},onDoubleClick:e=>{e.stopPropagation(),c()},children:(0,H.jsx)(D,{className:`w-4 h-4`,style:{color:i||a?`white`:o}})}),s&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] whitespace-nowrap`,children:[`return to `,(0,H.jsx)(`span`,{className:`font-medium text-[var(--text)]`,children:s})]})]})]})}),q_=(0,v.memo)(function({id:e,sourceX:t,sourceY:n,targetX:r,targetY:i,sourcePosition:a,targetPosition:o,data:s}){let[c,l,u]=ou({sourceX:t,sourceY:n,targetX:r,targetY:i,sourcePosition:a,targetPosition:o}),d=s?.when,f=s?.highlightState,p=!!d,m=f===`taken`,h=f===`highlighted`,g=f===`failed`,_=`var(--edge-color)`,v=2,y;return g?(_=`var(--failed)`,v=3):m?(_=`var(--edge-taken)`,v=3):h&&(_=`var(--edge-active)`,v=3),p&&!m&&!h&&!g&&(y=`6 3`),(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Zp,{id:e,path:c,style:{stroke:_,strokeWidth:v,strokeDasharray:y,transition:`stroke 0.3s ease, stroke-width 0.3s ease`},markerEnd:`url(#arrow-${g?`failed`:m?`taken`:h?`active`:`default`})`}),p&&(0,H.jsx)(Zm,{children:(0,H.jsx)(`div`,{className:`nodrag nopan`,style:{position:`absolute`,transform:`translate(-50%, -50%) translate(${l}px,${u}px)`,pointerEvents:`all`},children:(0,H.jsx)(`span`,{className:`inline-block px-1.5 py-0.5 rounded-full text-[9px] font-mono leading-tight max-w-[140px] truncate`,style:{backgroundColor:g?`var(--failed)`:m?`var(--edge-taken)`:`var(--surface)`,color:g||m?`var(--bg)`:`var(--text-muted)`,border:`1px solid ${g?`var(--failed)`:m?`var(--edge-taken)`:`var(--border)`}`},title:d,children:d})})}),m&&(0,H.jsx)(`circle`,{r:`3`,fill:`var(--edge-taken)`,children:(0,H.jsx)(`animateMotion`,{dur:`1s`,repeatCount:`indefinite`,path:c})}),g&&(0,H.jsx)(`circle`,{r:`3`,fill:`var(--failed)`,opacity:`0.8`,children:(0,H.jsx)(`animateMotion`,{dur:`1.5s`,repeatCount:`indefinite`,path:c})})]})});function J_(){let e=B(e=>e.workflowStatus),t=B(e=>e.workflowFailure),n=B(e=>e.workflowFailedAgent),r=B(e=>e.workflowTermination),i=B(e=>e.selectNode);if(e!==`failed`||!t)return null;if(t.stopped_by_user){let e=t.checkpoint_path?.split(`/`).pop();return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-slate-900/90 border border-slate-500/40 shadow-lg shadow-slate-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(Te,{className:`w-4 h-4 text-slate-300 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-slate-200`,children:`Workflow Stopped`}),t.checkpoint_path?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`span`,{className:`text-[11px] text-slate-300/80 truncate`,title:t.checkpoint_path,children:[`Checkpoint saved: `,e]}),(0,H.jsx)(`span`,{className:`text-[10px] text-slate-400/70 truncate`,children:`Resume from the CLI with: conductor resume`})]}):t.checkpoint_unavailable_reason?(0,H.jsxs)(`span`,{className:`text-[11px] text-amber-300/80 truncate`,title:t.checkpoint_unavailable_reason,children:[`No checkpoint could be saved — `,t.checkpoint_unavailable_reason]}):(0,H.jsx)(`span`,{className:`text-[11px] text-slate-400/70 truncate`,children:`Saving checkpoint…`})]}),n&&(0,H.jsxs)(`button`,{onClick:()=>i(Fh([],n)),className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium text-slate-200 bg-slate-500/20 hover:bg-slate-500/30 transition-colors flex-shrink-0 ml-1`,children:[(0,H.jsx)(L,{className:`w-3 h-3`}),`View`]})]})})}let a=r?.is_explicit&&r.status===`failed`,o=a?r.termination_reason||t.message||`Workflow terminated`:t.message||t.error_type||`Unknown error`,s=a?`Workflow Terminated`:`Workflow Failed`,c=t.error_type===`TimeoutError`;return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-red-950/90 border border-red-500/40 shadow-lg shadow-red-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(De,{className:`w-4 h-4 text-red-400 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-red-300`,children:s}),(0,H.jsx)(`span`,{className:`text-[11px] text-red-400/80 truncate`,children:o}),a&&r?.terminated_by&&(0,H.jsxs)(`span`,{className:`text-[10px] text-red-400/60 truncate`,children:[`Terminated by: `,r.terminated_by]}),c&&t.current_agent&&(0,H.jsxs)(`span`,{className:`text-[10px] text-red-400/60 truncate`,children:[`Timed out on agent: `,t.current_agent]}),t.checkpoint_path&&(0,H.jsxs)(`span`,{className:`text-[10px] text-red-400/50 truncate`,title:t.checkpoint_path,children:[`Checkpoint: `,t.checkpoint_path.split(`/`).pop()]})]}),n&&(0,H.jsxs)(`button`,{onClick:()=>i(Fh([],n)),className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium text-red-300 bg-red-500/20 hover:bg-red-500/30 transition-colors flex-shrink-0 ml-1`,children:[(0,H.jsx)(L,{className:`w-3 h-3`}),`View`]})]})})}function Y_(){let[e,t]=(0,v.useState)(!1),n=B(e=>e.workflowStatus),r=B(e=>e.workflowTermination),i=B(e=>e.totalCost),a=B(e=>e.totalTokens),o=B(e=>e.agentsCompleted),s=B(e=>e.agentsTotal),c=xt();if(n!==`completed`||e)return null;let l=r?.is_explicit&&r.status===`success`;return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-3 px-4 py-2 rounded-lg`,`bg-green-950/90 border border-green-500/40 shadow-lg shadow-green-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(F,{className:`w-4 h-4 text-green-400 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-green-300`,children:l?`Workflow Terminated`:`Completed`}),l&&r?.termination_reason&&(0,H.jsx)(`span`,{className:`text-[11px] text-green-400/80 truncate`,children:r.termination_reason}),l&&r?.terminated_by&&(0,H.jsxs)(`span`,{className:`text-[10px] text-green-400/60 truncate`,children:[`Terminated by: `,r.terminated_by]})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3 text-[11px] text-green-400/80 font-mono flex-shrink-0 ml-auto`,children:[(0,H.jsx)(`span`,{children:c}),s>0&&(0,H.jsxs)(`span`,{children:[o,`/`,s,` agents`]}),a>0&&(0,H.jsxs)(`span`,{children:[_t(a),` tok`]}),i>0&&(0,H.jsx)(`span`,{children:vt(i)})]}),(0,H.jsx)(`button`,{onClick:()=>t(!0),className:`p-0.5 rounded text-green-500/60 hover:text-green-300 transition-colors flex-shrink-0 ml-1`,children:(0,H.jsx)(je,{className:`w-3.5 h-3.5`})})]})})}var X_=6e4;function Z_({wsStatus:e,wsDisconnectedSince:t,workflowStatus:n,replayMode:r,now:i=Date.now(),thresholdMs:a=X_}){return r||n!==`running`||e===`connected`||t==null?!1:i-t>=a}function Q_(){let e=B(e=>e.wsStatus),t=B(e=>e.wsDisconnectedSince),n=B(e=>e.workflowStatus),r=B(e=>e.replayMode),[i,a]=(0,v.useState)(()=>Date.now());return(0,v.useEffect)(()=>{if(t==null||e===`connected`)return;let n=()=>a(Date.now());n();let r=setInterval(n,1e3);return()=>clearInterval(r)},[t,e]),{stuck:Z_({wsStatus:e,wsDisconnectedSince:t,workflowStatus:n,replayMode:r,now:i}),elapsedMs:t==null?0:Math.max(0,i-t)}}function $_(){let{stuck:e,elapsedMs:t}=Q_(),n=B(e=>e.bgStderrLog),r=B(e=>e.bgStdoutLog),i=B(e=>e.systemLogFile),a=B(e=>e.wsAuthFailed);if(!e)return null;let o=n?`Check the captured logs: ${n}${r?` (and ${r})`:``}`:i?`Check the event log: ${i}`:"Check the terminal where `conductor run` was launched, or re-run with --log-file to capture one.",s=a?`The dashboard may have been rejected by its own authentication check (an invalid or expired token, or a Host/Origin mismatch) -- try reloading the page. If that doesn’t help, the Conductor process may have crashed.`:`Reconnecting for `+gt(t/1e3)+` with no success. The Conductor process may have crashed.`;return(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-amber-950/90 border border-amber-500/40 shadow-lg shadow-amber-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(De,{className:`w-4 h-4 text-amber-400 flex-shrink-0`}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium text-amber-300`,children:`Connection lost — workflow may have stopped responding`}),(0,H.jsx)(`span`,{className:`text-[11px] text-amber-400/80 truncate`,children:s}),(0,H.jsx)(`span`,{className:`text-[10px] text-amber-400/60 truncate`,title:n??i??void 0,children:o})]})]})})}var ev=5e3;function tv(){let e=B(e=>e.wsSendFailed),t=B(e=>e.setWsSendFailed),[n,r]=(0,v.useState)(!1);return(0,v.useEffect)(()=>{if(!e)return;r(!0);let n=setTimeout(()=>{r(!1),t(!1)},ev);return()=>clearTimeout(n)},[e,t]),n?(0,H.jsx)(`div`,{className:`absolute top-14 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:U(`flex items-center gap-2 px-4 py-2 rounded-lg`,`bg-red-950/90 border border-red-500/40 shadow-lg shadow-red-500/10`,`backdrop-blur-sm max-w-[560px]`),children:[(0,H.jsx)(De,{className:`w-4 h-4 text-red-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-red-300`,children:`Not connected — your response was not sent. Reconnecting…`})]})}):null}var nv={agentNode:C_,scriptNode:E_,setNode:k_,gateNode:M_,groupNode:P_,workflowNode:I_,waitNode:L_,terminateNode:B_,endNode:V_,startNode:H_,ingressNode:W_,egressNode:K_},rv={animatedEdge:q_},iv={type:`animatedEdge`},av=300,ov=50;function sv(e){qh(av),e({padding:.2,duration:av})}function cv(){return(0,H.jsx)(`svg`,{style:{position:`absolute`,width:0,height:0},children:(0,H.jsxs)(`defs`,{children:[(0,H.jsx)(`marker`,{id:`arrow-default`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--edge-color)`})}),(0,H.jsx)(`marker`,{id:`arrow-active`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--edge-active)`})}),(0,H.jsx)(`marker`,{id:`arrow-taken`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--edge-taken)`})}),(0,H.jsx)(`marker`,{id:`arrow-failed`,viewBox:`0 0 10 10`,refX:`8`,refY:`5`,markerWidth:`8`,markerHeight:`8`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:`var(--failed)`})})]})})}function lv(e,t){if(t.length===0)return null;let n=e[t[0]];for(let e=1;ee.viewContextPath),n=B(e=>e.selectNode),r=B(e=>e.selectedNode),i=B(e=>e.workflowStatus),a=B(e=>e.wsStatus),o=B(e=>e.workflowFailedAgent),s=B(e=>e.navigateIntoSubworkflow),{agents:c,routes:l,parallelGroups:u,forEachGroups:d,nodes:f,groupProgress:p,entryPoint:m,subworkflowContexts:h,parentAgent:g,basePath:_}=e,y=B(e=>e.expandedContexts),b=B(e=>e.nodes),x=B(e=>e.groupProgress),S=B(e=>e.subworkflowContexts),C=B(e=>e.highlightedEdges),[w,T,E]=Qm([]),[D,O,k]=$m([]),A=(0,v.useRef)(``),{getViewport:j,setViewport:M}=Jf(),N=(0,v.useRef)(null),P=(0,v.useRef)([]),ee=(0,v.useRef)({hint:null,stickyRebuilds:0}),F=(0,v.useRef)(new Set),I=(0,v.useRef)(null),te=JSON.stringify(t),ne=(0,v.useMemo)(()=>{let e=[`${te}#${c.map(e=>e.name).join(`,`)}`];for(let t of[...y].sort()){if(Rh(t)){let{contextPath:n,name:r}=Ih(t),i=n.length===0?null:lv(S,n),a=(n.length===0?S:i?.children??[]).filter(e=>{let t=zh(e.slotKey);return t!=null&&t.group===r}).map(e=>`${e.slotKey}:${e.entryPoint??``}:${e.agents.map(e=>e.name).join(`,`)}`);e.push(`${t}=>${a.join(`|`)}`);continue}let n=lv(S,t.split(`.`).filter(Boolean).map(Number));e.push(`${t}:${n?.entryPoint??``}:${n?.agents.map(e=>e.name).join(`,`)??``}`)}return e.join(`||`)},[te,c,y,S]);(0,v.useEffect)(()=>{if(c.length===0){A.current!==ne&&(A.current=ne,P.current=[],F.current=new Set(y),I.current=te,ee.current={hint:null,stickyRebuilds:0},T([]),O([]));return}if(A.current===ne)return;A.current=ne;let e=I.current!==te;I.current=te;let t=F.current;F.current=new Set(y),ee.current=x_({previousKeys:t,currentKeys:y,currentHint:ee.current.hint,stickyRebuilds:ee.current.stickyRebuilds,contextSwitched:e});let{nodes:n,edges:r}=e_({agents:c,routes:l,parallelGroups:u,forEachGroups:d,nodes:f,groupProgress:p,entryPoint:m,parentAgent:g,children:h},_,y),i=P.current;if(P.current=n,T(n),O(r),e||i.length===0||Jh())return;let a=N.current?.getBoundingClientRect(),o=b_({prevNodes:i,nextNodes:n,anchorKeyHint:ee.current.hint,viewport:j(),paneSize:{width:a?.width??0,height:a?.height??0}});o&&M(o)},[ne,c,l,u,d,f,p,m,g,h,_,y,te,j,M,T,O]),(0,v.useEffect)(()=>{T(e=>e.map(e=>{let t=e.data,n=t.iterationContextPath;if(n&&n.length>0){let r=lv(S,n)?.status;return!r||r===t.status?e:{...e,data:{...t,status:r}}}let r=t.contextPath??[],i=r.length===0?null:lv(S,r),a=r.length===0?b:i?.nodes,o=r.length===0?x:i?.groupProgress,s=t.name??e.id,c=a?a[s]:void 0;if(!c)return e;let l=t,u=!1,d=c.status||`pending`;if(d!==t.status&&(l={...l,status:d},u=!0),t.groupName&&o&&o[t.groupName]){let e=o[t.groupName],n=l.progress;e&&(!n||n.completed!==e.completed||n.failed!==e.failed)&&(l={...l,progress:e},u=!0)}return u?{...e,data:l}:e}))},[b,x,S,T]),(0,v.useEffect)(()=>{O(e=>e.map(e=>{let{contextPath:t,name:n}=Ih(e.source),r=Ih(e.target).name,i=t.length===0?null:lv(S,t),a=(t.length===0?C:i?.highlightedEdges??[]).find(e=>e.from===n&&e.to===r)?.state;return e.data?.highlightState===a?e:{...e,data:{...e.data,highlightState:a}}}))},[C,S,O]);let re=(0,v.useCallback)((e,t)=>{t.type===`groupNode`&&t.data.type!==`for_each_group`||n(t.id)},[n]),ie=(0,v.useCallback)((e,n)=>{let r=n.data;if(r.type!==`workflow`||(r.contextPath??[]).join(`.`)!==t.join(`.`))return;let i=r.name;i&&h.some(e=>e.slotKey===i||e.parentAgent===i)&&s(i)},[h,s,t]),L=(0,v.useCallback)(()=>{n(null)},[n]),ae=(0,v.useCallback)(e=>X[e.data?.status||`pending`]??X.pending??`#6b7280`,[]);(0,v.useEffect)(()=>{T(e=>e.map(e=>({...e,selected:e.id===r})))},[r,T]),(0,v.useEffect)(()=>{i===`failed`&&o&&n(Fh([],o))},[i,o,n]);let oe=i===`pending`&&c.length===0,se=(()=>{switch(a){case`connecting`:return`Connecting to workflow…`;case`reconnecting`:return`Reconnecting…`;case`disconnected`:return`Connection lost. Retrying…`;default:return`Waiting for workflow…`}})();return(0,H.jsxs)(`div`,{ref:N,className:`w-full h-full relative`,children:[(0,H.jsx)(cv,{}),(0,H.jsx)(J_,{}),(0,H.jsx)(Y_,{}),(0,H.jsx)($_,{}),(0,H.jsx)(tv,{}),oe&&(0,H.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center pointer-events-none`,children:[(0,H.jsxs)(`div`,{className:`relative mb-3`,children:[(0,H.jsx)(Me,{className:`w-8 h-8 text-[var(--accent)] opacity-20`}),(0,H.jsx)(fe,{className:`w-8 h-8 text-[var(--text-muted)] animate-spin absolute inset-0 opacity-40`})]}),(0,H.jsx)(`p`,{className:`text-sm text-[var(--text-muted)] animate-pulse`,children:se})]}),(0,H.jsxs)(Ym,{nodes:w,edges:D,onNodesChange:E,onEdgesChange:k,onNodeClick:re,onNodeDoubleClick:ie,onPaneClick:L,nodeTypes:nv,edgeTypes:rv,defaultEdgeOptions:iv,fitView:!0,fitViewOptions:{padding:.2},minZoom:.2,maxZoom:2,proOptions:{hideAttribution:!0},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,children:[(0,H.jsx)(oh,{variant:nh.Dots,gap:20,size:1,color:`var(--border-subtle)`}),(0,H.jsx)(Ah,{nodeColor:ae,maskColor:`var(--minimap-mask)`,style:{background:`var(--minimap-bg)`},pannable:!0,zoomable:!0}),(0,H.jsxs)(hh,{showInteractive:!1,children:[(0,H.jsx)(pv,{}),(0,H.jsx)(fv,{})]}),(0,H.jsx)(mv,{}),(0,H.jsx)(hv,{viewPathKey:te}),(0,H.jsx)(gv,{})]})]})}function fv(){let{fitView:e}=Jf();return(0,H.jsx)(`button`,{onClick:(0,v.useCallback)(()=>{sv(e)},[e]),className:`react-flow__controls-button`,title:`Fit view (F)`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,H.jsx)(pe,{className:`w-3.5 h-3.5`})})}function pv(){let{agents:e,subworkflowContexts:t,basePath:n}=Gh(),r=B(e=>e.expandedContexts),i=B(e=>e.expandContexts),a=B(e=>e.collapseContexts),o=(0,v.useMemo)(()=>t_(e,t,n),[e,t,n]),s=(0,v.useMemo)(()=>o.some(e=>r.has(e)),[o,r]),c=(0,v.useCallback)(()=>{o.length!==0&&(s?a(o):i(o))},[o,s,a,i]);if((0,v.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.key===`e`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&c()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]),o.length===0)return null;let l=s?`Collapse all subworkflows`:`Expand all subworkflows`;return(0,H.jsx)(`button`,{onClick:c,className:`react-flow__controls-button`,title:`${l} (E)`,"aria-label":l,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:s?(0,H.jsx)(P,{className:`w-3.5 h-3.5`}):(0,H.jsx)(ee,{className:`w-3.5 h-3.5`})})}function mv(){let{fitView:e}=Jf();return(0,v.useEffect)(()=>{let t=t=>{let n=t.target?.tagName;n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.key===`f`&&!t.ctrlKey&&!t.metaKey&&!t.altKey&&sv(e)};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]),null}function hv({viewPathKey:e}){let{fitView:t}=Jf(),n=(0,v.useRef)(e);return(0,v.useEffect)(()=>{n.current!==e&&(n.current=e,qh(350),setTimeout(()=>sv(t),ov))},[e,t]),null}function gv(){let e=g_();return e?(0,H.jsx)(`div`,{className:`absolute top-3 left-1/2 -translate-x-1/2 z-20 animate-[banner-in_200ms_ease-out]`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2 rounded-lg bg-amber-950/90 border border-amber-500/40 shadow-lg shadow-amber-500/10 backdrop-blur-sm max-w-[560px]`,children:[(0,H.jsx)(`span`,{className:`text-xs text-amber-300`,children:`⚠`}),(0,H.jsx)(`span`,{className:`text-[11px] text-amber-400/80`,children:e.message}),(0,H.jsx)(`a`,{href:window.location.pathname,className:`px-2 py-0.5 rounded text-[10px] font-medium text-amber-300 bg-amber-500/20 hover:bg-amber-500/30 transition-colors flex-shrink-0 ml-1`,children:`Root`})]})}):null}function _v({items:e}){let t=e.filter(e=>e.value!=null&&e.value!==``);return t.length===0?null:(0,H.jsx)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 text-xs`,children:t.map(({label:e,value:t})=>(0,H.jsxs)(`div`,{className:`contents`,children:[(0,H.jsx)(`dt`,{className:`text-[var(--text-muted)] whitespace-nowrap`,children:e}),(0,H.jsx)(`dd`,{className:`text-[var(--text)] break-words`,children:typeof t==`object`?JSON.stringify(t):String(t)})]},e))})}function vv(e){let t=[];return e.elapsed!=null&&t.push({label:`Elapsed`,value:gt(e.elapsed)}),e.model&&t.push({label:`Model`,value:e.model}),e.reasoning_effort&&t.push({label:`Reasoning`,value:e.reasoning_effort}),e.tokens!=null&&t.push({label:`Tokens`,value:_t(e.tokens)}),e.input_tokens!=null&&e.output_tokens!=null&&t.push({label:`In / Out`,value:`${_t(e.input_tokens)} / ${_t(e.output_tokens)}`}),e.cost_usd!=null&&t.push({label:`Cost`,value:vt(e.cost_usd)}),e.context_window_used!=null&&e.context_window_max!=null&&t.push({label:`Context`,value:bt(e.context_window_used,e.context_window_max)}),e.iteration!=null&&t.push({label:`Iteration`,value:e.iteration}),e.error_type&&t.push({label:`Error`,value:e.error_type}),e.error_message&&t.push({label:`Message`,value:e.error_message}),t}function yv({output:e,title:t=`Output`,defaultExpanded:n=!0,maxHeight:r=`300px`}){let[i,a]=(0,v.useState)(n),[o,s]=(0,v.useState)(!1),c=yt(e);if(!c)return null;let l=typeof e==`object`&&!!e;return(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsxs)(`button`,{onClick:()=>a(!i),className:`flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--text-muted)] hover:text-[var(--text)] transition-colors font-semibold`,children:[i?(0,H.jsx)(j,{className:`w-3 h-3`}):(0,H.jsx)(M,{className:`w-3 h-3`}),t]}),i&&(0,H.jsx)(`button`,{onClick:async()=>{await navigator.clipboard.writeText(c),s(!0),setTimeout(()=>s(!1),2e3)},className:`flex items-center gap-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,title:`Copy to clipboard`,children:o?(0,H.jsx)(A,{className:`w-3 h-3 text-[var(--completed)]`}):(0,H.jsx)(re,{className:`w-3 h-3`})})]}),i&&(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md p-3 font-mono text-[11px] leading-relaxed text-[var(--text)] overflow-auto whitespace-pre-wrap break-words`,style:{maxHeight:r},children:l?(0,H.jsx)(bv,{text:c}):c})]})}function bv({text:e}){let t=e.split(/("(?:[^"\\]|\\.)*")/g);return(0,H.jsx)(H.Fragment,{children:t.map((e,n)=>{if(n%2==1){let r=t.slice(n+1).join(``);return(0,H.jsx)(`span`,{className:/^\s*:/.test(r)?`text-blue-400`:`text-green-400`,children:e},n)}return(0,H.jsx)(`span`,{dangerouslySetInnerHTML:{__html:e.replace(/\b(true|false|null)\b|(-?\d+\.?\d*(?:e[+-]?\d+)?)/gi,(e,t,n)=>t?`${e}`:n?`${e}`:e)}},n)})})}function xv({activity:e,defaultExpanded:t=!0}){let[n,r]=(0,v.useState)(t),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{i.current&&n&&(i.current.scrollTop=i.current.scrollHeight)},[e.length,n]),e.length===0?null:(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsxs)(`button`,{onClick:()=>r(!n),className:`flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--text-muted)] hover:text-[var(--text)] transition-colors font-semibold`,children:[n?(0,H.jsx)(j,{className:`w-3 h-3`}):(0,H.jsx)(M,{className:`w-3 h-3`}),`Activity (`,e.length,`)`]}),n&&(0,H.jsx)(`div`,{ref:i,className:`max-h-[400px] overflow-y-auto space-y-0.5`,children:e.map((e,t)=>(0,H.jsx)(Sv,{entry:e},t))})]})}function Sv({entry:e}){return(0,H.jsxs)(`div`,{className:U(`py-1.5 px-2 rounded text-[11px] leading-relaxed border-b border-[var(--border-subtle)] last:border-b-0`),children:[(0,H.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,H.jsx)(`span`,{className:`w-4 text-center flex-shrink-0`,children:e.icon}),(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] uppercase text-[9px] font-semibold tracking-wider w-12 flex-shrink-0 pt-px`,children:e.label}),(0,H.jsx)(`span`,{className:U(`break-words`,{reasoning:`text-indigo-400/70`,"tool-start":`text-blue-400`,"tool-complete":`text-green-400`,turn:`text-amber-400`,message:`text-[var(--text)]`,"parse-recovery":`text-yellow-400`,"compaction-error":`text-yellow-400`}[e.type]||`text-[var(--text)]`),children:typeof e.text==`object`?JSON.stringify(e.text):e.text})]}),e.detail&&(0,H.jsx)(`div`,{className:`mt-1 ml-[4.25rem] px-2 py-1 bg-[var(--bg)] rounded text-[10px] font-mono text-[var(--text-muted)] whitespace-pre-wrap break-words max-h-24 overflow-y-auto`,children:typeof e.detail==`object`?JSON.stringify(e.detail,null,2):e.detail})]})}var Cv={running:{label:`Validating…`,color:`#3b82f6`},passed:{label:`Passed`,color:`#22c55e`},failed:{label:`Failed`,color:`#f59e0b`},error:{label:`Validator error (treated as pass)`,color:`#f59e0b`}};function wv({node:e}){let t=e.validator_state;if(!t)return null;let n=Cv[t]??{label:`Validating…`,color:`#3b82f6`},r=e.validator_issues??[],i=(t===`failed`||t===`error`)&&r.length>0;return(0,H.jsxs)(`div`,{className:`border border-[var(--border)] rounded-lg overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-[var(--bg)]`,children:[(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)]`,children:`Validation`}),(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ml-auto`,style:{backgroundColor:`${n.color}20`,color:n.color},children:n.label})]}),(0,H.jsxs)(`div`,{className:`px-3 py-3 space-y-2 border-t border-[var(--border)]`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-[var(--text-muted)]`,children:[e.validator_model&&(0,H.jsxs)(`span`,{children:[`model: `,e.validator_model]}),e.validator_cost_usd!=null&&(0,H.jsxs)(`span`,{children:[`cost: $`,e.validator_cost_usd.toFixed(4)]}),e.validator_attempts!=null&&e.validator_attempts>1&&(0,H.jsxs)(`span`,{children:[`runs: `,e.validator_attempts]})]}),i&&(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]`,children:`Issues`}),(0,H.jsx)(`ul`,{className:`space-y-1`,children:r.map((e,t)=>(0,H.jsxs)(`li`,{className:`text-xs text-[var(--text)] flex gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] flex-shrink-0`,children:`•`}),(0,H.jsx)(`span`,{children:e})]},t))})]}),e.validator_will_retry&&(0,H.jsx)(`div`,{className:`text-[10px] text-[var(--text-muted)] italic`,children:`Primary agent re-run once with this feedback appended.`})]})]})}function Tv({node:e}){let t=e.status,n=X[t]||X.pending,r=e.iterationHistory&&e.iterationHistory.length>0;return(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Agent`})]}),(0,H.jsx)(wv,{node:e}),r?(0,H.jsx)(Ev,{label:`Iteration ${e.iteration??`?`} (current)`,defaultExpanded:!0,status:t,snapshot:{iteration:e.iteration??0,prompt:e.prompt,output:e.output,elapsed:e.elapsed,model:e.model,reasoning_effort:e.reasoning_effort,tokens:e.tokens,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cost_usd:e.cost_usd,activity:e.activity,error_type:e.error_type,error_message:e.error_message}}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_v,{items:vv(e)}),e.prompt&&(0,H.jsx)(yv,{output:e.prompt,title:`Input / Prompt`,defaultExpanded:!0}),(0,H.jsx)(xv,{activity:e.activity,defaultExpanded:t!==`completed`}),e.output!=null&&(0,H.jsx)(yv,{output:e.output,title:`Output`})]}),r&&[...e.iterationHistory].reverse().map(e=>(0,H.jsx)(Ev,{label:`Iteration ${e.iteration}`,defaultExpanded:!1,status:t,snapshot:e},e.iteration))]})}function Ev({label:e,defaultExpanded:t,snapshot:n,status:r}){let[i,a]=(0,v.useState)(t);return(0,H.jsxs)(`div`,{className:`border border-[var(--border)] rounded-lg overflow-hidden`,children:[(0,H.jsxs)(`button`,{onClick:()=>a(!i),className:`flex items-center gap-2 w-full px-3 py-2 bg-[var(--bg)] hover:bg-[var(--node-bg)] transition-colors text-left`,children:[i?(0,H.jsx)(j,{className:`w-3.5 h-3.5 text-[var(--text-muted)] flex-shrink-0`}):(0,H.jsx)(M,{className:`w-3.5 h-3.5 text-[var(--text-muted)] flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text)]`,children:e}),n.elapsed!=null&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] ml-auto`,children:Dv(n.elapsed)})]}),i&&(0,H.jsxs)(`div`,{className:`px-3 py-3 space-y-3 border-t border-[var(--border)]`,children:[(0,H.jsx)(_v,{items:vv(n)}),n.prompt&&(0,H.jsx)(yv,{output:n.prompt,title:`Input / Prompt`,defaultExpanded:!1}),(0,H.jsx)(xv,{activity:n.activity,defaultExpanded:t&&r!==`completed`}),n.output!=null&&(0,H.jsx)(yv,{output:n.output,title:`Output`,defaultExpanded:!0}),n.error_type&&(0,H.jsxs)(`div`,{className:`text-xs text-red-400`,children:[(0,H.jsx)(`span`,{className:`font-semibold`,children:n.error_type}),n.error_message&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`— `,n.error_message]})]})]})]})}function Dv(e){return e<1?`${(e*1e3).toFixed(0)}ms`:e<60?`${e.toFixed(1)}s`:`${Math.floor(e/60)}m ${(e%60).toFixed(0)}s`}function Ov({node:e}){let t=e.status,n=X[t]||X.pending,r=[];e.elapsed!=null&&r.push({label:`Elapsed`,value:gt(e.elapsed)}),e.exit_code!=null&&r.push({label:`Exit Code`,value:e.exit_code}),e.error_type&&r.push({label:`Error`,value:e.error_type}),e.error_message&&r.push({label:`Message`,value:e.error_message});let i=``;return e.stdout&&(i+=e.stdout),e.stderr&&(i+=(i?` - ---- stderr --- -`:``)+e.stderr),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Script`})]}),(0,H.jsx)(_v,{items:r}),i&&(0,H.jsx)(yv,{output:i,title:`Output`})]})}function kv({node:e}){let t=e.status,n=X[t]||X.pending,r=e.set_output_type,i=e.set_output_keys,a=e.set_value_repr,o=i?.length??0,s=[];return e.elapsed!=null&&s.push({label:`Elapsed`,value:gt(e.elapsed)}),r&&s.push({label:`Output Type`,value:r}),o>0?s.push({label:`Bindings`,value:i.join(`, `)}):t===`completed`&&s.push({label:`Bindings`,value:`scalar`}),e.error_type&&s.push({label:`Error`,value:e.error_type}),e.error_message&&s.push({label:`Message`,value:e.error_message}),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Set`})]}),(0,H.jsx)(_v,{items:s}),a&&(0,H.jsx)(yv,{output:a,title:`Value preview`})]})}function Av(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var jv=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Mv=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Nv={};function Pv(e,t){return((t||Nv).jsx?Mv:jv).test(e)}var Fv=/[ \t\n\f\r]/g;function Iv(e){return typeof e==`object`?e.type===`text`?Lv(e.value):!1:Lv(e)}function Lv(e){return e.replace(Fv,``)===``}var Rv=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Rv.prototype.normal={},Rv.prototype.property={},Rv.prototype.space=void 0;function zv(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Rv(n,r,t)}function Bv(e){return e.toLowerCase()}var Vv=class{constructor(e,t){this.attribute=t,this.property=e}};Vv.prototype.attribute=``,Vv.prototype.booleanish=!1,Vv.prototype.boolean=!1,Vv.prototype.commaOrSpaceSeparated=!1,Vv.prototype.commaSeparated=!1,Vv.prototype.defined=!1,Vv.prototype.mustUseProperty=!1,Vv.prototype.number=!1,Vv.prototype.overloadedBoolean=!1,Vv.prototype.property=``,Vv.prototype.spaceSeparated=!1,Vv.prototype.space=void 0;var Hv=s({boolean:()=>Z,booleanish:()=>Wv,commaOrSpaceSeparated:()=>Jv,commaSeparated:()=>qv,number:()=>Q,overloadedBoolean:()=>Gv,spaceSeparated:()=>Kv}),Uv=0,Z=Yv(),Wv=Yv(),Gv=Yv(),Q=Yv(),Kv=Yv(),qv=Yv(),Jv=Yv();function Yv(){return 2**++Uv}var Xv=Object.keys(Hv),Zv=class extends Vv{constructor(e,t,n,r){let i=-1;if(super(e,t),Qv(this,`space`,r),typeof n==`number`)for(;++i4&&n.slice(0,4)===`data`&&dy.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(uy,my);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!uy.test(e)){let n=e.replace(ly,py);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=Zv}return new i(r,t)}function py(e){return`-`+e.toLowerCase()}function my(e){return e.charAt(1).toUpperCase()}var hy=zv([ey,ry,ay,oy,sy],`html`),gy=zv([ey,iy,ay,oy,sy],`svg`);function _y(e){return e.join(` `).trim()}var vy=o(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g,u=` -`,d=`/`,f=`*`,p=``,m=`comment`,h=`declaration`;function g(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,g=1;function v(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(u);g=~n?e.length-n:g+e.length}function y(){var e={line:l,column:g};return function(t){return t.position=new b(e),C(),t}}function b(e){this.start=e,this.end={line:l,column:g},this.source=t.source}b.prototype.content=e;function x(n){var r=Error(t.source+`:`+l+`:`+g+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=g,r.source=e,!t.silent)throw r}function S(t){var n=t.exec(e);if(n){var r=n[0];return v(r),e=e.slice(r.length),n}}function C(){S(i)}function w(e){var t;for(e||=[];t=T();)t!==!1&&e.push(t);return e}function T(){var t=y();if(!(d!=e.charAt(0)||f!=e.charAt(1))){for(var n=2;p!=e.charAt(n)&&(f!=e.charAt(n)||d!=e.charAt(n+1));)++n;if(n+=2,p===e.charAt(n-1))return x(`End of comment missing`);var r=e.slice(2,n-2);return g+=2,v(r),e=e.slice(n),g+=2,t({type:m,comment:r})}}function E(){var e=y(),t=S(a);if(t){if(T(),!S(o))return x(`property missing ':'`);var r=S(s),i=e({type:h,property:_(t[0].replace(n,p)),value:r?_(r[0].replace(n,p)):p});return S(c),i}}function D(){var e=[];w(e);for(var t;t=E();)t!==!1&&(e.push(t),w(e));return e}return C(),D()}function _(e){return e?e.replace(l,p):p}t.exports=g})),yy=o((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var n=t(vy());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),by=o((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),xy=o(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(yy()),r=by();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),Sy=wy(`end`),Cy=wy(`start`);function wy(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function Ty(e){let t=Cy(e),n=Sy(e);if(t&&n)return{start:t,end:n}}function Ey(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?Oy(e.position):`start`in e||`end`in e?Oy(e):`line`in e||`column`in e?Dy(e):``}function Dy(e){return ky(e&&e.line)+`:`+ky(e&&e.column)}function Oy(e){return Dy(e&&e.start)+`-`+Dy(e&&e.end)}function ky(e){return e&&typeof e==`number`?e:1}var Ay=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=Ey(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};Ay.prototype.file=``,Ay.prototype.name=``,Ay.prototype.reason=``,Ay.prototype.message=``,Ay.prototype.stack=``,Ay.prototype.column=void 0,Ay.prototype.line=void 0,Ay.prototype.ancestors=void 0,Ay.prototype.cause=void 0,Ay.prototype.fatal=void 0,Ay.prototype.place=void 0,Ay.prototype.ruleId=void 0,Ay.prototype.source=void 0;var jy=l(xy(),1),My={}.hasOwnProperty,Ny=new Map,Py=/[A-Z]/g,Fy=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),Iy=new Set([`td`,`th`]);function Ly(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=Jy(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=qy(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?gy:hy,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=Ry(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function Ry(e,t,n){if(t.type===`element`)return zy(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return By(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return Hy(e,t,n);if(t.type===`mdxjsEsm`)return Vy(e,t);if(t.type===`root`)return Uy(e,t,n);if(t.type===`text`)return Wy(e,t)}function zy(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=gy,e.schema=i),e.ancestors.push(t);let a=eb(e,t.tagName,!1),o=Yy(e,t),s=Zy(e,t);return Fy.has(t.tagName)&&(s=s.filter(function(e){return typeof e==`string`?!Iv(e):!0})),Gy(e,o,a,t),Ky(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function By(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}tb(e,t.position)}function Vy(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);tb(e,t.position)}function Hy(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=gy,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:eb(e,t.name,!0),o=Xy(e,t),s=Zy(e,t);return Gy(e,o,a,t),Ky(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Uy(e,t,n){let r={};return Ky(r,Zy(e,t)),e.create(t,e.Fragment,r,n)}function Wy(e,t){return t.value}function Gy(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Ky(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function qy(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function Jy(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=Cy(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function Yy(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&My.call(t.properties,i)){let a=Qy(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&Iy.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function Xy(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`)if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else tb(e,t.position);else{let i=r.name,a;if(r.value&&typeof r.value==`object`)if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else tb(e,t.position);else a=r.value===null?!0:r.value;n[i]=a}return n}function Zy(e,t){let n=[],r=-1,i=e.passKeys?new Map:Ny;for(;++ri?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a0?(pb(e,e.length,0,t),e):t}var hb={}.hasOwnProperty;function gb(e){let t={},n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function bb(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var xb=Mb(/[A-Za-z]/),Sb=Mb(/[\dA-Za-z]/),Cb=Mb(/[#-'*+\--9=?A-Z^-~]/);function wb(e){return e!==null&&(e<32||e===127)}var Tb=Mb(/\d/),Eb=Mb(/[\dA-Fa-f]/),Db=Mb(/[!-/:-@[-`{-~]/);function $(e){return e!==null&&e<-2}function Ob(e){return e!==null&&(e<0||e===32)}function kb(e){return e===-2||e===-1||e===32}var Ab=Mb(/\p{P}|\p{S}/u),jb=Mb(/\s/);function Mb(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Nb(e){let t=[],n=-1,r=0,i=0;for(;++n55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function Pb(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return kb(r)?(e.enter(n),s(r)):t(r)}function s(r){return kb(r)&&a++o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;er;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function Bb(e,t,n){return Pb(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function Vb(e){if(e===null||Ob(e)||jb(e))return 1;if(Ab(e))return 2}function Hb(e,t,n){let r=[],i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};Kb(d,-c),Kb(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=mb(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=mb(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=mb(l,Hb(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=mb(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=mb(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,pb(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n0&&kb(t)?Pb(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||$(t)?e.check(ax,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||$(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),kb(t)?Pb(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),kb(t)?Pb(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||$(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function cx(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var lx={name:`codeIndented`,tokenize:dx},ux={partial:!0,tokenize:fx};function dx(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),Pb(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):$(t)?e.attempt(ux,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||$(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function fx(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):Pb(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):$(e)?i(e):n(e)}}var px={name:`codeText`,previous:hx,resolve:mx,tokenize:gx};function mx(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&vx(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),vx(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),vx(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function Ex(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||wb(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||$(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||Ob(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):$(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||$(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!kb(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function Ox(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),Pb(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||$(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function kx(e,t){let n;return r;function r(i){return $(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):kb(i)?Pb(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var Ax={name:`definition`,tokenize:Mx},jx={partial:!0,tokenize:Nx};function Mx(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return Dx.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=bb(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return Ob(t)?kx(e,l)(t):l(t)}function l(t){return Ex(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(jx,d,d)(t)}function d(t){return kb(t)?Pb(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||$(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function Nx(e,t,n){return r;function r(t){return Ob(t)?kx(e,i)(t):n(t)}function i(t){return Ox(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return kb(t)?Pb(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||$(e)?t(e):n(e)}}var Px={name:`hardBreakEscape`,tokenize:Fx};function Fx(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return $(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var Ix={name:`headingAtx`,resolve:Lx,tokenize:Rx};function Lx(e,t){let n=e.length-2,r=3,i,a;return e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},pb(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function Rx(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||Ob(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||$(n)?(e.exit(`atxHeading`),t(n)):kb(n)?Pb(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||Ob(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var zx=`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`.split(`.`),Bx=[`pre`,`script`,`style`,`textarea`],Vx={concrete:!0,name:`htmlFlow`,resolveTo:Wx,tokenize:Gx},Hx={partial:!0,tokenize:qx},Ux={partial:!0,tokenize:Kx};function Wx(e){let t=e.length;for(;t--&&!(e[t][0]===`enter`&&e[t][1].type===`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Gx(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:F):xb(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):xb(a)?(e.consume(a),i=4,r.interrupt?t:F):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:F):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return xb(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||Ob(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&Bx.includes(l)?(i=1,r.interrupt?t(s):O(s)):zx.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||Sb(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return kb(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||xb(t)?(e.consume(t),b):kb(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||Sb(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):kb(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):kb(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||$(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||Ob(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||kb(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||$(t)?O(t):kb(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),M):t===60&&i===1?(e.consume(t),N):t===62&&i===4?(e.consume(t),I):t===63&&i===3?(e.consume(t),F):t===93&&i===5?(e.consume(t),ee):$(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(Hx,te,k)(t)):t===null||$(t)?(e.exit(`htmlFlowData`),k(t)):(e.consume(t),O)}function k(t){return e.check(Ux,A,te)(t)}function A(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),j}function j(t){return t===null||$(t)?k(t):(e.enter(`htmlFlowData`),O(t))}function M(t){return t===45?(e.consume(t),F):O(t)}function N(t){return t===47?(e.consume(t),o=``,P):O(t)}function P(t){if(t===62){let n=o.toLowerCase();return Bx.includes(n)?(e.consume(t),I):O(t)}return xb(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),P):O(t)}function ee(t){return t===93?(e.consume(t),F):O(t)}function F(t){return t===62?(e.consume(t),I):t===45&&i===2?(e.consume(t),F):O(t)}function I(t){return t===null||$(t)?(e.exit(`htmlFlowData`),te(t)):(e.consume(t),I)}function te(n){return e.exit(`htmlFlow`),t(n)}}function Kx(e,t,n){let r=this;return i;function i(t){return $(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function qx(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(Yb,t,n)}}var Jx={name:`htmlText`,tokenize:Yx};function Yx(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):xb(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):xb(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):$(t)?(o=d,N(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?M(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):$(t)?(o=h,N(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?M(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?M(t):$(t)?(o=v,N(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):$(t)?(o=y,N(t)):(e.consume(t),y)}function b(e){return e===62?M(e):y(e)}function x(t){return xb(t)?(e.consume(t),S):n(t)}function S(t){return t===45||Sb(t)?(e.consume(t),S):C(t)}function C(t){return $(t)?(o=C,N(t)):kb(t)?(e.consume(t),C):M(t)}function w(t){return t===45||Sb(t)?(e.consume(t),w):t===47||t===62||Ob(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),M):t===58||t===95||xb(t)?(e.consume(t),E):$(t)?(o=T,N(t)):kb(t)?(e.consume(t),T):M(t)}function E(t){return t===45||t===46||t===58||t===95||Sb(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):$(t)?(o=D,N(t)):kb(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,k):$(t)?(o=O,N(t)):kb(t)?(e.consume(t),O):(e.consume(t),A)}function k(t){return t===i?(e.consume(t),i=void 0,j):t===null?n(t):$(t)?(o=k,N(t)):(e.consume(t),k)}function A(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||Ob(t)?T(t):(e.consume(t),A)}function j(e){return e===47||e===62||Ob(e)?T(e):n(e)}function M(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function N(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),P}function P(t){return kb(t)?Pb(e,ee,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):ee(t)}function ee(t){return e.enter(`htmlTextData`),o(t)}}var Xx={name:`labelEnd`,resolveAll:eS,resolveTo:tS,tokenize:nS},Zx={tokenize:rS},Qx={tokenize:iS},$x={tokenize:aS};function eS(e){let t=-1,n=[];for(;++t=3&&(a===null||$(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),kb(t)?Pb(e,s,`whitespace`)(t):s(t))}}var mS={continuation:{tokenize:vS},exit:bS,name:`list`,tokenize:_S},hS={partial:!0,tokenize:xS},gS={partial:!0,tokenize:yS};function _S(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:Tb(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(fS,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return Tb(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(Yb,r.interrupt?n:u,e.attempt(hS,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return kb(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function vS(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(Yb,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Pb(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!kb(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(gS,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,Pb(e,e.attempt(mS,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function yS(e,t,n){let r=this;return Pb(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function bS(e){e.exit(this.containerState.type)}function xS(e,t,n){let r=this;return Pb(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!kb(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var SS={name:`setextUnderline`,resolveTo:CS,tokenize:wS};function CS(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function wS(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),kb(t)?Pb(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||$(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var TS={tokenize:ES};function ES(e){let t=this,n=e.attempt(Yb,r,e.attempt(this.parser.constructs.flowInitial,i,Pb(e,e.attempt(this.parser.constructs.flow,i,e.attempt(xx,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var DS={resolveAll:jS()},OS=AS(`string`),kS=AS(`text`);function AS(e){return{resolveAll:jS(e===`text`?MS:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++iVS,contentInitial:()=>FS,disable:()=>HS,document:()=>PS,flow:()=>LS,flowInitial:()=>IS,insideSpan:()=>BS,string:()=>RS,text:()=>zS}),PS={42:mS,43:mS,45:mS,48:mS,49:mS,50:mS,51:mS,52:mS,53:mS,54:mS,55:mS,56:mS,57:mS,62:Zb},FS={91:Ax},IS={[-2]:lx,[-1]:lx,32:lx},LS={35:Ix,42:fS,45:[SS,fS],60:Vx,61:SS,95:fS,96:ox,126:ox},RS={38:rx,92:tx},zS={[-5]:uS,[-4]:uS,[-3]:uS,33:oS,38:rx,42:Ub,60:[qb,Jx],91:cS,92:[Px,tx],93:Xx,95:Ub,96:px},BS={null:[Ub,DS]},VS={null:[42,95]},HS={null:[]};function US(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=mb(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=Hb(a,l.events,l),l.events):[]}function f(e,t){return GS(p(e),t)}function p(e){return WS(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function GS(e,t){let n=-1,r=[],i;for(;++n0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||aC).call(a,void 0,e[0])}for(r.position={start:nC(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:nC(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d0&&(r.className=[`language-`+i[0]]);let a={type:`element`,tagName:`code`,properties:r,children:[{type:`text`,value:n}]};return t.meta&&(a.data={meta:t.meta}),e.patch(t,a),a=e.applyData(t,a),a={type:`element`,tagName:`pre`,properties:{},children:[a]},e.patch(t,a),a}function uC(e,t){let n={type:`element`,tagName:`del`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function dC(e,t){let n={type:`element`,tagName:`em`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function fC(e,t){let n=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,r=String(t.identifier).toUpperCase(),i=Nb(r.toLowerCase()),a=e.footnoteOrder.indexOf(r),o,s=e.footnoteCounts.get(r);s===void 0?(s=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=a+1,s+=1,e.footnoteCounts.set(r,s);let c={type:`element`,tagName:`a`,properties:{href:`#`+n+`fn-`+i,id:n+`fnref-`+i+(s>1?`-`+s:``),dataFootnoteRef:!0,ariaDescribedBy:[`footnote-label`]},children:[{type:`text`,value:String(o)}]};e.patch(t,c);let l={type:`element`,tagName:`sup`,properties:{},children:[c]};return e.patch(t,l),e.applyData(t,l)}function pC(e,t){let n={type:`element`,tagName:`h`+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function mC(e,t){if(e.options.allowDangerousHtml){let n={type:`raw`,value:t.value};return e.patch(t,n),e.applyData(t,n)}}function hC(e,t){let n=t.referenceType,r=`]`;if(n===`collapsed`?r+=`[]`:n===`full`&&(r+=`[`+(t.label||t.identifier)+`]`),t.type===`imageReference`)return[{type:`text`,value:`![`+t.alt+r}];let i=e.all(t),a=i[0];a&&a.type===`text`?a.value=`[`+a.value:i.unshift({type:`text`,value:`[`});let o=i[i.length-1];return o&&o.type===`text`?o.value+=r:i.push({type:`text`,value:r}),i}function gC(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return hC(e,t);let i={src:Nb(r.url||``),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`img`,properties:i,children:[]};return e.patch(t,a),e.applyData(t,a)}function _C(e,t){let n={src:Nb(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`img`,properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function vC(e,t){let n={type:`text`,value:t.value.replace(/\r?\n|\r/g,` `)};e.patch(t,n);let r={type:`element`,tagName:`code`,properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function yC(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return hC(e,t);let i={href:Nb(r.url||``)};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`a`,properties:i,children:e.all(t)};return e.patch(t,a),e.applyData(t,a)}function bC(e,t){let n={href:Nb(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`a`,properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function xC(e,t,n){let r=e.all(t),i=n?SC(n):CC(t),a={},o=[];if(typeof t.checked==`boolean`){let e=r[0],n;e&&e.type===`element`&&e.tagName===`p`?n=e:(n={type:`element`,tagName:`p`,properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:`text`,value:` `}),n.children.unshift({type:`element`,tagName:`input`,properties:{type:`checkbox`,checked:t.checked,disabled:!0},children:[]}),a.className=[`task-list-item`]}let s=-1;for(;++s1}function wC(e,t){let n={},r=e.all(t),i=-1;for(typeof t.start==`number`&&t.start!==1&&(n.start=t.start);++i0){let r={type:`element`,tagName:`tbody`,properties:{},children:e.wrap(n,!0)},a=Cy(t.children[1]),o=Sy(t.children[t.children.length-1]);a&&o&&(r.position={start:a,end:o}),i.push(r)}let a={type:`element`,tagName:`table`,properties:{},children:e.wrap(i,!0)};return e.patch(t,a),e.applyData(t,a)}function kC(e,t,n){let r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?`th`:`td`,a=n&&n.type===`table`?n.align:void 0,o=a?a.length:t.children.length,s=-1,c=[];for(;++s0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return a.push(PC(t.slice(i),i>0,!1)),a.join(``)}function PC(e,t,n){let r=0,i=e.length;if(t){let t=e.codePointAt(r);for(;t===jC||t===MC;)r++,t=e.codePointAt(r)}if(n){let t=e.codePointAt(i-1);for(;t===jC||t===MC;)i--,t=e.codePointAt(i-1)}return i>r?e.slice(r,i):``}function FC(e,t){let n={type:`text`,value:NC(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function IC(e,t){let n={type:`element`,tagName:`hr`,properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}var LC={blockquote:sC,break:cC,code:lC,delete:uC,emphasis:dC,footnoteReference:fC,heading:pC,html:mC,imageReference:gC,image:_C,inlineCode:vC,linkReference:yC,link:bC,listItem:xC,list:wC,paragraph:TC,root:EC,strong:DC,table:OC,tableCell:AC,tableRow:kC,text:FC,thematicBreak:IC,toml:RC,yaml:RC,definition:RC,footnoteDefinition:RC};function RC(){}var zC=typeof self==`object`?self:globalThis,BC=(e,t)=>{let n=(t,n)=>(e.set(n,t),t),r=i=>{if(e.has(i))return e.get(i);let[a,o]=t[i];switch(a){case 0:case-1:return n(o,i);case 1:{let e=n([],i);for(let t of o)e.push(r(t));return e}case 2:{let e=n({},i);for(let[t,n]of o)e[r(t)]=r(n);return e}case 3:return n(new Date(o),i);case 4:{let{source:e,flags:t}=o;return n(new RegExp(e,t),i)}case 5:{let e=n(new Map,i);for(let[t,n]of o)e.set(r(t),r(n));return e}case 6:{let e=n(new Set,i);for(let t of o)e.add(r(t));return e}case 7:{let{name:e,message:t}=o;return n(new zC[e](t),i)}case 8:return n(BigInt(o),i);case`BigInt`:return n(Object(BigInt(o)),i);case`ArrayBuffer`:return n(new Uint8Array(o).buffer,o);case`DataView`:{let{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}}return n(new zC[a](o),i)};return r},VC=e=>BC(new Map,e)(0),HC=``,{toString:UC}={},{keys:WC}=Object,GC=e=>{let t=typeof e;if(t!==`object`||!e)return[0,t];let n=UC.call(e).slice(8,-1);switch(n){case`Array`:return[1,HC];case`Object`:return[2,HC];case`Date`:return[3,HC];case`RegExp`:return[4,HC];case`Map`:return[5,HC];case`Set`:return[6,HC];case`DataView`:return[1,n]}return n.includes(`Array`)?[1,n]:n.includes(`Error`)?[7,n]:[2,n]},KC=([e,t])=>e===0&&(t===`function`||t===`symbol`),qC=(e,t,n,r)=>{let i=(e,t)=>{let i=r.push(e)-1;return n.set(t,i),i},a=r=>{if(n.has(r))return n.get(r);let[o,s]=GC(r);switch(o){case 0:{let t=r;switch(s){case`bigint`:o=8,t=r.toString();break;case`function`:case`symbol`:if(e)throw TypeError(`unable to serialize `+s);t=null;break;case`undefined`:return i([-1],r)}return i([o,t],r)}case 1:{if(s){let e=r;return s===`DataView`?e=new Uint8Array(r.buffer):s===`ArrayBuffer`&&(e=new Uint8Array(r)),i([s,[...e]],r)}let e=[],t=i([o,e],r);for(let t of r)e.push(a(t));return t}case 2:{if(s)switch(s){case`BigInt`:return i([s,r.toString()],r);case`Boolean`:case`Number`:case`String`:return i([s,r.valueOf()],r)}if(t&&`toJSON`in r)return a(r.toJSON());let n=[],c=i([o,n],r);for(let t of WC(r))(e||!KC(GC(r[t])))&&n.push([a(t),a(r[t])]);return c}case 3:return i([o,r.toISOString()],r);case 4:{let{source:e,flags:t}=r;return i([o,{source:e,flags:t}],r)}case 5:{let t=[],n=i([o,t],r);for(let[n,i]of r)(e||!(KC(GC(n))||KC(GC(i))))&&t.push([a(n),a(i)]);return n}case 6:{let t=[],n=i([o,t],r);for(let n of r)(e||!KC(GC(n)))&&t.push(a(n));return n}}let{message:c}=r;return i([o,{name:s,message:c}],r)};return a},JC=(e,{json:t,lossy:n}={})=>{let r=[];return qC(!(t||n),!!t,new Map,r)(e),r},YC=typeof structuredClone==`function`?(e,t)=>t&&(`json`in t||`lossy`in t)?VC(JC(e,t)):structuredClone(e):(e,t)=>VC(JC(e,t));function XC(e,t){let n=[{type:`text`,value:`↩`}];return t>1&&n.push({type:`element`,tagName:`sup`,properties:{},children:[{type:`text`,value:String(t)}]}),n}function ZC(e,t){return`Back to reference `+(e+1)+(t>1?`-`+t:``)}function QC(e){let t=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,n=e.options.footnoteBackContent||XC,r=e.options.footnoteBackLabel||ZC,i=e.options.footnoteLabel||`Footnotes`,a=e.options.footnoteLabelTagName||`h2`,o=e.options.footnoteLabelProperties||{className:[`sr-only`]},s=[],c=-1;for(;++c0&&d.push({type:`text`,value:` `});let e=typeof n==`string`?n:n(c,u);typeof e==`string`&&(e={type:`text`,value:e}),d.push({type:`element`,tagName:`a`,properties:{href:`#`+t+`fnref-`+l+(u>1?`-`+u:``),dataFootnoteBackref:``,ariaLabel:typeof r==`string`?r:r(c,u),className:[`data-footnote-backref`]},children:Array.isArray(e)?e:[e]})}let p=a[a.length-1];if(p&&p.type===`element`&&p.tagName===`p`){let e=p.children[p.children.length-1];e&&e.type===`text`?e.value+=` `:p.children.push({type:`text`,value:` `}),p.children.push(...d)}else a.push(...d);let m={type:`element`,tagName:`li`,properties:{id:t+`fn-`+l},children:e.wrap(a,!0)};e.patch(i,m),s.push(m)}if(s.length!==0)return{type:`element`,tagName:`section`,properties:{dataFootnotes:!0,className:[`footnotes`]},children:[{type:`element`,tagName:a,properties:{...YC(o),id:`footnote-label`},children:[{type:`text`,value:i}]},{type:`text`,value:` -`},{type:`element`,tagName:`ol`,properties:{},children:e.wrap(s,!0)},{type:`text`,value:` -`}]}}var $C=(function(e){if(e==null)return iw;if(typeof e==`function`)return rw(e);if(typeof e==`object`)return Array.isArray(e)?ew(e):tw(e);if(typeof e==`string`)return nw(e);throw Error(`Expected function, string, or object as test`)});function ew(e){let t=[],n=-1;for(;++n`:``))+`)`})}return u;function u(){let l=sw,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=lw(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d0&&n.push({type:`text`,value:` -`}),n}function vw(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function yw(e,t){let n=pw(e,t),r=n.one(e,void 0),i=QC(n),a=Array.isArray(r)?{type:`root`,children:r}:r||{type:`root`,children:[]};return i&&(`children`in a,a.children.push({type:`text`,value:` -`},i)),a}function bw(e,t){return e&&`run`in e?async function(n,r){let i=yw(n,{file:r,...t});await e.run(i,r)}:function(n,r){return yw(n,{file:r,...e||t})}}function xw(e){if(e)throw e}var Sw=o(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});ft.length,o;r&&t.push(i);try{o=e.apply(this,t)}catch(e){let t=e;if(r&&n)throw t;return i(t)}r||(o&&o.then&&typeof o.then==`function`?o.then(a,i):o instanceof Error?i(o):a(o))}function i(e,...r){n||(n=!0,t(e,...r))}function a(e){i(null,e)}}var Ew={basename:Dw,dirname:Ow,extname:kw,join:Aw,sep:`/`};function Dw(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);Nw(e);let n=0,r=-1,i=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else r<0&&(a=!0,r=i+1);return r<0?``:e.slice(n,r)}if(t===e)return``;let o=-1,s=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else o<0&&(a=!0,o=i+1),s>-1&&(e.codePointAt(i)===t.codePointAt(s--)?s<0&&(r=i):(s=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Ow(e){if(Nw(e),e.length===0)return`.`;let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||=!0;return t<0?e.codePointAt(0)===47?`/`:`.`:t===1&&e.codePointAt(0)===47?`//`:e.slice(0,t)}function kw(e){Nw(e);let t=e.length,n=-1,r=0,i=-1,a=0,o;for(;t--;){let s=e.codePointAt(t);if(s===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),s===46?i<0?i=t:a!==1&&(a=1):i>-1&&(a=-1)}return i<0||n<0||a===0||a===1&&i===n-1&&i===r+1?``:e.slice(i,n)}function Aw(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+=`/`),t?`/`+n:n}function Mw(e,t){let n=``,r=0,i=-1,a=0,o=-1,s,c;for(;++o<=e.length;){if(o2){if(c=n.lastIndexOf(`/`),c!==n.length-1){c<0?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=o,a=0;continue}}else if(n.length>0){n=``,r=0,i=o,a=0;continue}}t&&(n=n.length>0?n+`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1;i=o,a=0}else s===46&&a>-1?a++:a=-1}return n}function Nw(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}var Pw={cwd:Fw};function Fw(){return`/`}function Iw(e){return!!(typeof e==`object`&&e&&`href`in e&&e.href&&`protocol`in e&&e.protocol&&e.auth===void 0)}function Lw(e){if(typeof e==`string`)e=new URL(e);else if(!Iw(e)){let t=TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code=`ERR_INVALID_ARG_TYPE`,t}if(e.protocol!==`file:`){let e=TypeError(`The URL must be of scheme file`);throw e.code=`ERR_INVALID_URL_SCHEME`,e}return Rw(e)}function Rw(e){if(e.hostname!==``){let e=TypeError(`File URL host must be "localhost" or empty on darwin`);throw e.code=`ERR_INVALID_FILE_URL_HOST`,e}let t=e.pathname,n=-1;for(;++n0){let[r,...a]=t,o=n[i][1];Cw(o)&&Cw(r)&&(r=(0,Kw.default)(!0,o,r)),n[i]=[e,r,...a]}}}}().freeze();function Yw(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `parser`")}function Xw(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `compiler`")}function Zw(e,t){if(t)throw Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Qw(e){if(!Cw(e)||typeof e.type!=`string`)throw TypeError("Expected node, got `"+e+"`")}function $w(e,t,n){if(!n)throw Error("`"+e+"` finished async. Use `"+t+"` instead")}function eT(e){return tT(e)?e:new Bw(e)}function tT(e){return!!(e&&typeof e==`object`&&`message`in e&&`messages`in e)}function nT(e){return typeof e==`string`||rT(e)}function rT(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var iT=[],aT={allowDangerousHtml:!0},oT=/^(https?|ircs?|mailto|xmpp)$/i,sT=[{from:`astPlugins`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowDangerousHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowNode`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowElement`},{from:`allowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowedElements`},{from:`className`,id:`remove-classname`},{from:`disallowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`disallowedElements`},{from:`escapeHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`includeElementIndex`,id:`#remove-includeelementindex`},{from:`includeNodeIndex`,id:`change-includenodeindex-to-includeelementindex`},{from:`linkTarget`,id:`remove-linktarget`},{from:`plugins`,id:`change-plugins-to-remarkplugins`,to:`remarkPlugins`},{from:`rawSourcePos`,id:`#remove-rawsourcepos`},{from:`renderers`,id:`change-renderers-to-components`,to:`components`},{from:`source`,id:`change-source-to-children`,to:`children`},{from:`sourcePos`,id:`#remove-sourcepos`},{from:`transformImageUri`,id:`#add-urltransform`,to:`urlTransform`},{from:`transformLinkUri`,id:`#add-urltransform`,to:`urlTransform`}];function cT(e){let t=lT(e),n=uT(e);return dT(t.runSync(t.parse(n),n),e)}function lT(e){let t=e.rehypePlugins||iT,n=e.remarkPlugins||iT,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...aT}:aT;return Jw().use(oC).use(n).use(bw,r).use(t)}function uT(e){let t=e.children||``,n=new Bw;return typeof t==`string`?n.value=t:``+t,n}function dT(e,t){let n=t.allowedElements,r=t.allowElement,i=t.components,a=t.disallowedElements,o=t.skipHtml,s=t.unwrapDisallowed,c=t.urlTransform||fT;for(let e of sT)Object.hasOwn(t,e.from)&&``+e.from+(e.to?"use `"+e.to+"` instead":`remove it`)+e.id;return uw(e,l),Ly(e,{Fragment:H.Fragment,components:i,ignoreInvalidStyle:!0,jsx:H.jsx,jsxs:H.jsxs,passKeys:!0,passNode:!0});function l(e,t,i){if(e.type===`raw`&&i&&typeof t==`number`)return o?i.children.splice(t,1):i.children[t]={type:`text`,value:e.value},t;if(e.type===`element`){let t;for(t in ab)if(Object.hasOwn(ab,t)&&Object.hasOwn(e.properties,t)){let n=e.properties[t],r=ab[t];(r===null||r.includes(e.tagName))&&(e.properties[t]=c(String(n||``),t,e))}}if(e.type===`element`){let o=n?!n.includes(e.tagName):a?a.includes(e.tagName):!1;if(!o&&r&&typeof t==`number`&&(o=!r(e,t,i)),o&&i&&typeof t==`number`)return s&&e.children?i.children.splice(t,1,...e.children):i.children.splice(t,1),t}}}function fT(e){let t=e.indexOf(`:`),n=e.indexOf(`?`),r=e.indexOf(`#`),i=e.indexOf(`/`);return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||oT.test(e.slice(0,t))?e:``}function pT(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function mT(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function hT(e,t,n){let r=$C((n||{}).ignore||[]),i=gT(t),a=-1;for(;++a0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=pT(e,`(`),a=pT(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function PT(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||jb(n)||Ab(n))&&(!t||n!==47)}WT.peek=UT;function FT(){this.buffer()}function IT(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function LT(){this.buffer()}function RT(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function zT(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=bb(this.sliceSerialize(e)).toLowerCase(),n.label=t}function BT(e){this.exit(e)}function VT(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=bb(this.sliceSerialize(e)).toLowerCase(),n.label=t}function HT(e){this.exit(e)}function UT(){return`[`}function WT(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function GT(){return{enter:{gfmFootnoteCallString:FT,gfmFootnoteCall:IT,gfmFootnoteDefinitionLabelString:LT,gfmFootnoteDefinition:RT},exit:{gfmFootnoteCallString:zT,gfmFootnoteCall:BT,gfmFootnoteDefinitionLabelString:VT,gfmFootnoteDefinition:HT}}}function KT(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:WT},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?` -`:` `)+r.indentLines(r.containerFlow(e,a.current()),t?JT:qT))),s(),o}}function qT(e,t,n){return t===0?e:JT(e,t,n)}function JT(e,t,n){return(n?``:` `)+e}var YT=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];eE.peek=tE;function XT(){return{canContainEols:[`delete`],enter:{strikethrough:QT},exit:{strikethrough:$T}}}function ZT(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:YT}],handlers:{delete:eE}}}function QT(e){this.enter({type:`delete`,children:[]},e)}function $T(e){this.exit(e)}function eE(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function tE(){return`~`}function nE(e){return e.length}function rE(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||nE,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++ul&&(l=e[u].length);++ac[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++dc[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u `),a.shift(2);let o=n.indentLines(n.containerFlow(e,a.current()),sE);return i(),o}function sE(e,t,n){return`>`+(n?``:` `)+e}function cE(e,t){return lE(e,t.inConstruct,!0)&&!lE(e,t.notInConstruct,!1)}function lE(e,t,n){if(typeof t==`string`&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++ro&&(o=a):a=1,i=r+t.length,r=n.indexOf(t,i);return o}function fE(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function pE(e){let t=e.options.fence||"`";if(t!=="`"&&t!==`~`)throw Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function mE(e,t,n,r){let i=pE(n),a=e.value||``,o=i==="`"?`GraveAccent`:`Tilde`;if(fE(e,n)){let e=n.enter(`codeIndented`),t=n.indentLines(a,hE);return e(),t}let s=n.createTracker(r),c=i.repeat(Math.max(dE(a,i)+1,3)),l=n.enter(`codeFenced`),u=s.move(c);if(e.lang){let t=n.enter(`codeFencedLang${o}`);u+=s.move(n.safe(e.lang,{before:u,after:` `,encode:["`"],...s.current()})),t()}if(e.lang&&e.meta){let t=n.enter(`codeFencedMeta${o}`);u+=s.move(` `),u+=s.move(n.safe(e.meta,{before:u,after:` -`,encode:["`"],...s.current()})),t()}return u+=s.move(` -`),a&&(u+=s.move(a+` -`)),u+=s.move(c),l(),u}function hE(e,t,n){return(n?``:` `)+e}function gE(e){let t=e.options.quote||`"`;if(t!==`"`&&t!==`'`)throw Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function _E(e,t,n,r){let i=gE(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`definition`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`[`);return l+=c.move(n.safe(n.associationId(e),{before:l,after:`]`,...c.current()})),l+=c.move(`]: `),s(),!e.url||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:` -`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),o(),l}function vE(e){let t=e.options.emphasis||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function yE(e){return`&#x`+e.toString(16).toUpperCase()+`;`}function bE(e,t,n){let r=Vb(e),i=Vb(t);return r===void 0?i===void 0?n===`_`?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}xE.peek=SE;function xE(e,t,n,r){let i=vE(n),a=n.enter(`emphasis`),o=n.createTracker(r),s=o.move(i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=bE(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=yE(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=bE(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+yE(d));let p=o.move(i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function SE(e,t,n){return n.options.emphasis||`*`}function CE(e,t){let n=!1;return uw(e,function(e){if(`value`in e&&/\r?\n|\r/.test(e.value)||e.type===`break`)return n=!0,!1}),!!((!e.depth||e.depth<3)&&sb(e)&&(t.options.setext||n))}function wE(e,t,n,r){let i=Math.max(Math.min(6,e.depth||1),1),a=n.createTracker(r);if(CE(e,n)){let t=n.enter(`headingSetext`),r=n.enter(`phrasing`),o=n.containerPhrasing(e,{...a.current(),before:` -`,after:` -`});return r(),t(),o+` -`+(i===1?`=`:`-`).repeat(o.length-(Math.max(o.lastIndexOf(`\r`),o.lastIndexOf(` -`))+1))}let o=`#`.repeat(i),s=n.enter(`headingAtx`),c=n.enter(`phrasing`);a.move(o+` `);let l=n.containerPhrasing(e,{before:`# `,after:` -`,...a.current()});return/^[\t ]/.test(l)&&(l=yE(l.charCodeAt(0))+l.slice(1)),l=l?o+` `+l:o,n.options.closeAtx&&(l+=` `+o),c(),s(),l}TE.peek=EE;function TE(e){return e.value||``}function EE(){return`<`}DE.peek=OE;function DE(e,t,n,r){let i=gE(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`image`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`![`);return l+=c.move(n.safe(e.alt,{before:l,after:`]`,...c.current()})),l+=c.move(`](`),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),l+=c.move(`)`),o(),l}function OE(){return`!`}kE.peek=AE;function kE(e,t,n,r){let i=e.referenceType,a=n.enter(`imageReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`![`),l=n.safe(e.alt,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function AE(){return`!`}jE.peek=ME;function jE(e,t,n){let r=e.value||``,i="`",a=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=` `+r+` `);++a\u007F]/.test(e.url))}PE.peek=FE;function PE(e,t,n,r){let i=gE(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.createTracker(r),s,c;if(NE(e,n)){let t=n.stack;n.stack=[],s=n.enter(`autolink`);let r=o.move(`<`);return r+=o.move(n.containerPhrasing(e,{before:r,after:`>`,...o.current()})),r+=o.move(`>`),s(),n.stack=t,r}s=n.enter(`link`),c=n.enter(`label`);let l=o.move(`[`);return l+=o.move(n.containerPhrasing(e,{before:l,after:`](`,...o.current()})),l+=o.move(`](`),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter(`destinationLiteral`),l+=o.move(`<`),l+=o.move(n.safe(e.url,{before:l,after:`>`,...o.current()})),l+=o.move(`>`)):(c=n.enter(`destinationRaw`),l+=o.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...o.current()}))),c(),e.title&&(c=n.enter(`title${a}`),l+=o.move(` `+i),l+=o.move(n.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(`)`),s(),l}function FE(e,t,n){return NE(e,n)?`<`:`[`}IE.peek=LE;function IE(e,t,n,r){let i=e.referenceType,a=n.enter(`linkReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`[`),l=n.containerPhrasing(e,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function LE(){return`[`}function RE(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function zE(e){let t=RE(e),n=e.options.bulletOther;if(!n)return t===`*`?`-`:`*`;if(n!==`*`&&n!==`+`&&n!==`-`)throw Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function BE(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function VE(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function HE(e,t,n,r){let i=n.enter(`list`),a=n.bulletCurrent,o=e.ordered?BE(n):RE(n),s=e.ordered?o===`.`?`)`:`.`:zE(n),c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((o===`*`||o===`-`)&&t&&(!t.children||!t.children[0])&&n.stack[n.stack.length-1]===`list`&&n.stack[n.stack.length-2]===`listItem`&&n.stack[n.stack.length-3]===`list`&&n.stack[n.stack.length-4]===`listItem`&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),VE(n)===o&&t){let t=-1;for(;++t-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+a);let o=a.length+1;(i===`tab`||i===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let s=n.createTracker(r);s.move(a+` `.repeat(o-a.length)),s.shift(o);let c=n.enter(`listItem`),l=n.indentLines(n.containerFlow(e,s.current()),u);return c(),l;function u(e,t,n){return t?(n?``:` `.repeat(o))+e:(n?a:a+` `.repeat(o-a.length))+e}}function GE(e,t,n,r){let i=n.enter(`paragraph`),a=n.enter(`phrasing`),o=n.containerPhrasing(e,r);return a(),i(),o}var KE=$C([`break`,`delete`,`emphasis`,`footnote`,`footnoteReference`,`image`,`imageReference`,`inlineCode`,`inlineMath`,`link`,`linkReference`,`mdxJsxTextElement`,`mdxTextExpression`,`strong`,`text`,`textDirective`]);function qE(e,t,n,r){return(e.children.some(function(e){return KE(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function JE(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}YE.peek=XE;function YE(e,t,n,r){let i=JE(n),a=n.enter(`strong`),o=n.createTracker(r),s=o.move(i+i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=bE(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=yE(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=bE(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+yE(d));let p=o.move(i+i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function XE(e,t,n){return n.options.strong||`*`}function ZE(e,t,n,r){return n.safe(e.value,r)}function QE(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function $E(e,t,n){let r=(VE(n)+(n.options.ruleSpaces?` `:``)).repeat(QE(n));return n.options.ruleSpaces?r.slice(0,-1):r}var eD={blockquote:oE,break:uE,code:mE,definition:_E,emphasis:xE,hardBreak:uE,heading:wE,html:TE,image:DE,imageReference:kE,inlineCode:jE,link:PE,linkReference:IE,list:HE,listItem:WE,paragraph:GE,root:qE,strong:YE,text:ZE,thematicBreak:$E};function tD(){return{enter:{table:nD,tableData:oD,tableHeader:oD,tableRow:iD},exit:{codeText:sD,table:rD,tableData:aD,tableHeader:aD,tableRow:aD}}}function nD(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function rD(e){this.exit(e),this.data.inTable=void 0}function iD(e){this.enter({type:`tableRow`,children:[]},e)}function aD(e){this.exit(e)}function oD(e){this.enter({type:`tableCell`,children:[]},e)}function sD(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,cD));let n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function cD(e,t){return t===`|`?t:e}function lD(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,a=n?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:` -`,inConstruct:`tableCell`},{atBreak:!0,character:`|`,after:`[ :-]`},{character:`|`,inConstruct:`tableCell`},{atBreak:!0,character:`:`,after:`-`},{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:s}};function o(e,t,n,r){return l(u(e,n,r),e.align)}function s(e,t,n,r){let i=l([d(e,n,r)]);return i.slice(0,i.indexOf(` -`))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return rE(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var VD={tokenize:YD,partial:!0};function HD(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:KD,continuation:{tokenize:qD},exit:JD}},text:{91:{name:`gfmFootnoteCall`,tokenize:GD},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:UD,resolveTo:WD}}}}function UD(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=bb(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function WD(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function GD(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||Ob(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(bb(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return Ob(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function KD(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||Ob(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=bb(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return Ob(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),Pb(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function qD(e,t,n){return e.check(Yb,t,e.attempt(VD,t,n))}function JD(e){e.exit(`gfmFootnoteDefinition`)}function YD(e,t,n){let r=this;return Pb(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function XD(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=Vb(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var ZD=class{constructor(){this.map=[]}add(e,t,n){QD(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}};function QD(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i-1;){let e=r.events[t][1].type;if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):$(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):kb(t)?Pb(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||Ob(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,kb(t)?Pb(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return kb(t)?Pb(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||$(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return kb(t)?Pb(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||$(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||$(n)?(e.exit(`tableRow`),t(n)):kb(n)?Pb(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||Ob(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function nO(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new ZD;for(;++nn[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},aO(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function iO(e,t,n,r,i){let a=[],o=aO(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function aO(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var oO={name:`tasklistCheck`,tokenize:cO};function sO(){return{text:{91:oO}}}function cO(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return Ob(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return $(r)?t(r):kb(r)?e.check({tokenize:lO},t,n)(r):n(r)}}function lO(e,t,n){return Pb(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function uO(e){return gb([ED(),HD(),XD(e),eO(),sO()])}var dO={};function fO(e){let t=this,n=e||dO,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(uO(n)),a.push(hD()),o.push(gD(n))}var pO=new Set([`.md`,`.markdown`,`.mdx`]);function mO({filePath:e,onClose:t}){let[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(!0),c=(0,v.useCallback)(async()=>{s(!0),a(null);try{let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`),n=await fetch(`/api/files/${t}`);if(!n.ok){a((await n.json().catch(()=>({}))).error||`HTTP ${n.status}`);return}r(await n.json())}catch(e){a(e instanceof Error?e.message:`Failed to load file`)}finally{s(!1)}},[e]);(0,v.useEffect)(()=>{c()},[c]),(0,v.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let l=n?pO.has(n.extension):!1;return(0,H.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`relative flex flex-col w-[90vw] max-w-3xl max-h-[80vh] rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-2xl overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2.5 border-b border-[var(--border)] bg-[var(--surface-raised)] flex-shrink-0`,children:[(0,H.jsx)(se,{className:`w-4 h-4 text-[var(--text-muted)] flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate flex-1`,title:e,children:e}),n&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] flex-shrink-0 tabular-nums`,children:gO(n.size)}),(0,H.jsx)(`button`,{onClick:t,className:`p-1 rounded-md text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--surface-hover)] transition-colors flex-shrink-0`,title:`Close (Esc)`,children:(0,H.jsx)(je,{className:`w-4 h-4`})})]}),(0,H.jsxs)(`div`,{className:`flex-1 overflow-auto px-5 py-4 min-h-0`,children:[o&&(0,H.jsx)(`div`,{className:`flex items-center justify-center py-12`,children:(0,H.jsx)(fe,{className:`w-5 h-5 text-[var(--text-muted)] animate-spin`})}),i&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30`,children:[(0,H.jsx)(De,{className:`w-4 h-4 text-red-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs text-red-300`,children:i})]}),n&&!i&&(l?(0,H.jsx)(`div`,{className:`file-viewer-markdown text-xs leading-relaxed text-[var(--text)]`,children:(0,H.jsx)(hO,{content:n.content})}):(0,H.jsx)(`pre`,{className:`font-mono text-[11px] leading-[1.6] text-[var(--text)] whitespace-pre-wrap break-words`,children:n.content}))]})]})})}function hO({content:e}){return(0,H.jsx)(cT,{remarkPlugins:[fO],components:{h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-base font-bold mb-3 mt-2 text-[var(--text)]`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-sm font-bold mb-2 mt-3 text-[var(--text)]`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xs font-bold mb-1.5 mt-2 text-[var(--text)]`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`mb-2 last:mb-0`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside mb-2 space-y-1 ml-2`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside mb-2 space-y-1 ml-2`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{children:e}),code:({children:e,className:t})=>t?.includes(`language-`)?(0,H.jsx)(`code`,{className:`block bg-[var(--bg)] border border-[var(--border)] rounded px-3 py-2 font-mono text-[11px] my-2 overflow-x-auto whitespace-pre`,children:e}):(0,H.jsx)(`code`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded px-1 py-0.5 font-mono text-[11px]`,children:e}),pre:({children:e})=>(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md px-3 py-2.5 font-mono text-[11px] my-2 overflow-x-auto`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic`,children:e}),a:({href:e,children:t})=>(0,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-400 hover:text-blue-300 underline underline-offset-2`,children:t}),blockquote:({children:e})=>(0,H.jsx)(`blockquote`,{className:`border-l-2 border-[var(--border)] pl-3 my-2 opacity-80`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`border-[var(--border)] my-3`}),table:({children:e})=>(0,H.jsx)(`div`,{className:`overflow-x-auto my-2`,children:(0,H.jsx)(`table`,{className:`text-[11px] border-collapse w-full`,children:e})}),th:({children:e})=>(0,H.jsx)(`th`,{className:`border border-[var(--border)] px-2 py-1 text-left bg-[var(--bg)] font-semibold`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`border border-[var(--border)] px-2 py-1`,children:e})},children:e})}function gO(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function _O({node:e}){let t=B(e=>e.sendGateResponse),n=B(e=>e.wsStatus),[r,i]=(0,v.useState)(null),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(!1),[d,f]=(0,v.useState)(!1),[p,m]=(0,v.useState)(null),h=e.status===`waiting`,g=e.status===`completed`;(0,v.useEffect)(()=>{h&&(i(null),o(``),c(null),u(!1),f(!1))},[h,e.gate_prompt_id]);let _=h&&n===`connected`&&r===null,y=(n,r,a)=>{if(_){if(r){i(n),c(r),u(!!a);return}i(n),f(!0),t(e.name,n,void 0,e.gate_prompt_id)}},b=()=>{if(r===null||s===null)return;let n={[s]:a};f(!0),t(e.name,r,n,e.gate_prompt_id),c(null),u(!1)},x=e.option_details,S=x?.find(t=>t.value===e.selected_option)?.label||e.selected_option;return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[h&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30`,children:[(0,H.jsxs)(`span`,{className:`relative flex h-2.5 w-2.5 flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75`}),(0,H.jsx)(`span`,{className:`relative inline-flex rounded-full h-2.5 w-2.5 bg-amber-500`})]}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-amber-400 tracking-wide`,children:`Decision Required`})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-amber-500/50 pl-3 py-0.5`,children:(0,H.jsx)(yO,{text:e.prompt,muted:!1,onFileClick:m})}),x&&x.length>0&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:x.map(e=>{let t=r===e.value,n=r!==null&&!t;return(0,H.jsx)(`button`,{disabled:!_&&!t,onClick:()=>y(e.value,e.prompt_for,e.multiline),className:`w-full text-left px-3 py-2.5 rounded-lg border transition-all duration-150 ${t?`border-green-500/60 bg-green-500/10`:n?`border-[var(--border)] opacity-40 cursor-default`:`border-[var(--border)] bg-[var(--surface)] hover:border-amber-400/60 hover:bg-amber-500/5 cursor-pointer group`}`,children:(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,H.jsx)(`div`,{className:`flex-shrink-0`,children:t?(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full bg-green-500 flex items-center justify-center`,children:(0,H.jsx)(A,{className:`w-2.5 h-2.5 text-white`,strokeWidth:3})}):(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full border-2 transition-colors ${n?`border-[var(--border)]`:`border-[var(--border)] group-hover:border-amber-400`}`})}),(0,H.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,H.jsx)(`span`,{className:`text-xs font-medium ${t?`text-green-400`:`text-[var(--text)]`}`,children:e.label})}),e.route?(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] flex-shrink-0`,children:[`→ `,e.route]}):null]})},e.value)})}),d&&!s&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-1`,children:[(0,H.jsx)(fe,{className:`w-3 h-3 text-green-400 animate-spin`}),(0,H.jsx)(`span`,{className:`text-[10px] text-green-400`,children:`Sending...`})]}),_&&(0,H.jsx)(`p`,{className:`text-[10px] text-[var(--text-muted)] px-1`,children:`Select an option to continue the workflow`})]}),!x&&e.options&&e.options.length>0&&(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(`h4`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Options`}),(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.options.map(e=>(0,H.jsx)(`span`,{className:`text-[11px] px-2 py-0.5 rounded border border-[var(--border)] text-[var(--text-muted)]`,children:e},e))})]}),s&&(0,H.jsxs)(`div`,{className:`rounded-lg border border-[var(--border)] bg-[var(--bg)] overflow-hidden`,children:[(0,H.jsx)(`div`,{className:`px-3 py-2 border-b border-[var(--border)] bg-[var(--surface)]`,children:(0,H.jsx)(`h4`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:s})}),(0,H.jsxs)(`div`,{className:`p-3 space-y-2`,children:[l?(0,H.jsx)(`textarea`,{value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())},rows:6,placeholder:`Enter ${s}...`,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-amber-400 transition-colors resize-y font-mono leading-relaxed`,autoFocus:!0}):(0,H.jsx)(`input`,{type:`text`,value:a,onChange:e=>o(e.target.value),onKeyDown:e=>e.key===`Enter`&&b(),placeholder:`Enter ${s}...`,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-amber-400 transition-colors`,autoFocus:!0}),(0,H.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)]`,children:l?`Enter inserts a newline — press Ctrl/Cmd+Enter or click Submit`:`Press Enter or click Submit`}),(0,H.jsxs)(`button`,{onClick:b,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg bg-amber-500 text-white hover:bg-amber-600 transition-colors font-medium`,children:[(0,H.jsx)(xe,{className:`w-3 h-3`}),`Submit`]})]})]})]})]}),g&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-green-500/10 border border-green-500/30`,children:[(0,H.jsx)(A,{className:`w-3.5 h-3.5 text-green-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-green-400 tracking-wide`,children:`Decision Completed`})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-[var(--border)] pl-3 py-0.5`,children:(0,H.jsx)(yO,{text:e.prompt,muted:!0,onFileClick:m})}),S&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2.5 rounded-lg border border-green-500/30 bg-green-500/5`,children:[(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full bg-green-500 flex items-center justify-center flex-shrink-0`,children:(0,H.jsx)(A,{className:`w-2.5 h-2.5 text-white`,strokeWidth:3})}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)]`,children:S}),e.route&&(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[`→ `,e.route]})]}),x&&x.length>1&&(0,H.jsx)(`div`,{className:`space-y-1`,children:x.filter(t=>t.value!==e.selected_option).map(e=>(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg opacity-35`,children:[(0,H.jsx)(`div`,{className:`w-4 h-4 rounded-full border-2 border-[var(--border)] flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:e.label}),e.route&&(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[`→ `,e.route]})]},e.value))}),!x&&e.options&&e.options.length>0&&(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.options.map(t=>(0,H.jsxs)(`span`,{className:`text-[11px] px-2.5 py-1 rounded-lg border ${t===e.selected_option?`border-green-500/30 text-green-400 bg-green-500/5`:`border-[var(--border)] text-[var(--text-muted)] opacity-40`}`,children:[t===e.selected_option&&`✓ `,t]},t))}),(0,H.jsx)(bO,{node:e})]}),!h&&!g&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Human Gate`}),(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] capitalize`,children:[`(`,e.status,`)`]})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-[var(--border)] pl-3 py-0.5`,children:(0,H.jsx)(yO,{text:e.prompt,muted:!0,onFileClick:m})})]}),p&&(0,H.jsx)(mO,{filePath:p,onClose:()=>m(null)})]})}function vO(e){return!(!e||/^[a-z][a-z0-9+.-]*:/i.test(e)||e.startsWith(`//`)||e.startsWith(`#`)||e.startsWith(`/`)||e.startsWith(`\\`))}function yO({text:e,muted:t,onFileClick:n}){return(0,H.jsx)(`div`,{className:`gate-markdown text-xs leading-relaxed ${t?`text-[var(--text-muted)]`:`text-[var(--text)]`}`,children:(0,H.jsx)(cT,{remarkPlugins:[fO],components:{h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-sm font-bold mb-2 mt-1`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-xs font-bold mb-1.5 mt-1`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xs font-semibold mb-1 mt-1`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`mb-1.5 last:mb-0`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside mb-1.5 space-y-0.5`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside mb-1.5 space-y-0.5`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{children:e}),code:({children:e,className:t})=>t?.includes(`language-`)?(0,H.jsx)(`code`,{className:`block bg-[var(--bg)] border border-[var(--border)] rounded px-2 py-1.5 font-mono text-[11px] my-1 overflow-x-auto whitespace-pre`,children:e}):(0,H.jsx)(`code`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded px-1 py-0.5 font-mono text-[11px]`,children:e}),pre:({children:e})=>(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md px-2.5 py-2 font-mono text-[11px] my-1.5 overflow-x-auto`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic`,children:e}),a:({href:e,children:t})=>n&&vO(e)?(0,H.jsxs)(`button`,{onClick:t=>{t.preventDefault(),n(e)},className:`inline-flex items-center gap-0.5 text-blue-400 hover:text-blue-300 underline underline-offset-2 cursor-pointer`,title:`Open ${e}`,children:[(0,H.jsx)(se,{className:`w-3 h-3 inline flex-shrink-0`}),t]}):(0,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-400 hover:text-blue-300 underline underline-offset-2`,children:t}),blockquote:({children:e})=>(0,H.jsx)(`blockquote`,{className:`border-l-2 border-[var(--border)] pl-2.5 my-1.5 opacity-80`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`border-[var(--border)] my-2`}),table:({children:e})=>(0,H.jsx)(`div`,{className:`overflow-x-auto my-2`,children:(0,H.jsx)(`table`,{className:`text-[11px] border-collapse w-full`,children:e})}),th:({children:e})=>(0,H.jsx)(`th`,{className:`border border-[var(--border)] px-2 py-1 text-left bg-[var(--bg)] font-semibold`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`border border-[var(--border)] px-2 py-1`,children:e})},children:e})})}function bO({node:e}){let t=[];if(e.route&&t.push({label:`Route`,value:`→ ${e.route}`}),e.additional_input){let n=typeof e.additional_input==`object`?JSON.stringify(e.additional_input):e.additional_input;t.push({label:`Additional Input`,value:n})}return t.length===0?null:(0,H.jsx)(_v,{items:t})}function xO({node:e}){let[t,n]=(0,v.useState)(null),r=e.status===`waiting`,i=e.status===`completed`;if(r)return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsx)(SO,{node:e}),e.questions_reject_reason&&(0,H.jsx)(`div`,{className:`px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30 text-[11px] text-red-400`,children:e.questions_reject_reason}),(0,H.jsx)(_O,{node:e})]});if(!i)return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Questions`}),(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] capitalize`,children:[`(`,e.status,`)`]})]}),e.prompt&&(0,H.jsx)(`div`,{className:`border-l-2 border-[var(--border)] pl-3 py-0.5`,children:(0,H.jsx)(yO,{text:e.prompt,muted:!0,onFileClick:n})}),t&&(0,H.jsx)(mO,{filePath:t,onClose:()=>n(null)})]});let a=e.questions_answered_count??0,o=e.questions_skipped_count??0,s=e.questions_outcome??`completed`,c=s===`aborted`;return(0,H.jsxs)(`div`,{className:`space-y-3`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg border ${c?`bg-amber-500/10 border-amber-500/30`:`bg-green-500/10 border-green-500/30`}`,children:[c?(0,H.jsx)(O,{className:`w-3.5 h-3.5 text-amber-400 flex-shrink-0`}):(0,H.jsx)(A,{className:`w-3.5 h-3.5 text-green-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold tracking-wide ${c?`text-amber-400`:`text-green-400`}`,children:c?`Questions Aborted`:s===`skipped_remaining`?`Remaining Questions Skipped`:`Questions Completed`})]}),(0,H.jsx)(_v,{items:[{label:`Answered`,value:a},{label:`Skipped`,value:o},{label:`Outcome`,value:s}]})]})}function SO({node:e}){let t=e.questions_total??0,n=e.questions_answered_count??0,r=e.questions_skipped_count??0,i=n+r,a=t>0?Math.round(i/t*100):0;return(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-[var(--text-muted)]`,children:[(0,H.jsx)(de,{className:`w-3 h-3 flex-shrink-0`}),(0,H.jsxs)(`span`,{children:[i,` of `,t,` answered`]}),r>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(Ce,{className:`w-3 h-3`}),r,` skipped`]})]}),(0,H.jsx)(`div`,{className:`h-1 rounded-full bg-[var(--border)] overflow-hidden`,children:(0,H.jsx)(`div`,{className:`h-full bg-amber-500 transition-all duration-300`,style:{width:`${a}%`}})})]})}function CO({node:e}){let t=e.status,n=X[t]||X.pending,r=Uh()[e.name],i=e.type===`for_each_group`,[a,o]=(0,v.useState)(!0),s=[];e.elapsed!=null&&s.push({label:`Elapsed`,value:gt(e.elapsed)}),r&&(s.push({label:`Total`,value:r.total}),s.push({label:`Completed`,value:r.completed}),r.failed>0&&s.push({label:`Failed`,value:r.failed})),e.success_count!=null&&s.push({label:`Success`,value:e.success_count}),e.failure_count!=null&&s.push({label:`Failures`,value:e.failure_count});let c=e.for_each_items;return(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:i?`For-Each Group`:`Parallel Group`})]}),r&&r.total>0&&(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsxs)(`div`,{className:`flex justify-between text-[10px] text-[var(--text-muted)]`,children:[(0,H.jsx)(`span`,{children:`Progress`}),(0,H.jsxs)(`span`,{children:[r.completed+r.failed,`/`,r.total]})]}),(0,H.jsx)(`div`,{className:`h-1.5 bg-[var(--bg)] rounded-full overflow-hidden`,children:(0,H.jsx)(`div`,{className:`h-full rounded-full transition-all duration-500`,style:{width:`${(r.completed+r.failed)/r.total*100}%`,background:r.failed>0?`linear-gradient(90deg, var(--completed) ${r.completed/(r.completed+r.failed)*100}%, var(--failed) 0%)`:`var(--completed)`}})})]}),(0,H.jsx)(_v,{items:s}),i&&c&&c.length>0&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`button`,{onClick:()=>o(!a),className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold hover:text-[var(--text)] transition-colors`,children:[a?(0,H.jsx)(j,{className:`w-3 h-3`}):(0,H.jsx)(M,{className:`w-3 h-3`}),`Items (`,c.length,`)`]}),a&&(0,H.jsx)(`div`,{className:`space-y-1`,children:c.map(t=>(0,H.jsx)(TO,{groupName:e.name,item:t},`${t.key}-${t.index}`))})]})]})}var wO={running:X.running,completed:X.completed,failed:X.failed};function TO({groupName:e,item:t}){let[n,r]=(0,v.useState)(t.status===`running`),i=wO[t.status],a=Wh(),o=B(e=>e.navigateIntoSubworkflow),s=`${e}[${t.key}]`,c=a.find(e=>e.slotKey===s),l=!!c,u=!!(t.prompt||t.output!=null||t.activity&&t.activity.length>0||t.error_type),d=[];return t.elapsed!=null&&d.push({label:`Elapsed`,value:gt(t.elapsed)}),t.tokens!=null&&d.push({label:`Tokens`,value:_t(t.tokens)}),t.cost_usd!=null&&d.push({label:`Cost`,value:vt(t.cost_usd)}),(0,H.jsxs)(`div`,{className:`rounded-lg border border-[var(--border)] bg-[var(--surface)] overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center`,children:[(0,H.jsxs)(`button`,{onClick:()=>u&&r(!n),className:`flex items-center gap-2 flex-1 min-w-0 px-3 py-2 text-left hover:bg-[var(--node-bg)] transition-colors`,disabled:!u,children:[u?n?(0,H.jsx)(j,{className:`w-3 h-3 text-[var(--text-muted)] flex-shrink-0`}):(0,H.jsx)(M,{className:`w-3 h-3 text-[var(--text-muted)] flex-shrink-0`}):t.status===`running`?(0,H.jsx)(fe,{className:`w-3 h-3 animate-spin flex-shrink-0`,style:{color:i}}):(0,H.jsx)(`span`,{className:`w-2 h-2 rounded-full flex-shrink-0 ml-0.5 mr-0.5`,style:{backgroundColor:i}}),(0,H.jsx)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate flex-1 min-w-0`,children:t.key}),!n&&(t.elapsed!=null||t.tokens!=null||t.cost_usd!=null)&&(0,H.jsxs)(`span`,{className:`flex items-center gap-2 text-[10px] text-[var(--text-muted)] flex-shrink-0`,children:[t.elapsed!=null&&(0,H.jsx)(`span`,{children:gt(t.elapsed)}),t.tokens!=null&&(0,H.jsx)(`span`,{children:_t(t.tokens)}),t.cost_usd!=null&&(0,H.jsx)(`span`,{children:vt(t.cost_usd)})]}),(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider flex-shrink-0 px-1.5 py-0.5 rounded`,style:{backgroundColor:`${i}20`,color:i},children:t.status})]}),l&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>o(s),title:`Dive into ${c?.workflowName??s}`,className:`flex-shrink-0 mr-2 p-1 rounded hover:bg-[var(--accent)]/20 hover:text-[var(--accent)] transition-colors text-[var(--text-muted)] cursor-pointer`,children:(0,H.jsx)(ue,{className:`w-3 h-3`})})]}),n&&u&&(0,H.jsxs)(`div`,{className:`px-3 py-3 space-y-3 border-t border-[var(--border)]`,children:[d.length>0&&(0,H.jsx)(_v,{items:d}),t.prompt&&(0,H.jsx)(yv,{output:t.prompt,title:`Input / Prompt`,defaultExpanded:!1}),t.activity&&t.activity.length>0&&(0,H.jsx)(xv,{activity:t.activity,defaultExpanded:t.status!==`completed`}),t.output!=null&&(0,H.jsx)(yv,{output:t.output,title:`Output`,defaultExpanded:!0}),t.status===`failed`&&(t.error_type||t.error_message)&&(0,H.jsxs)(`div`,{className:`text-xs text-red-400`,children:[t.error_type&&(0,H.jsx)(`span`,{className:`font-semibold`,children:t.error_type}),t.error_message&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`— `,t.error_message]})]})]})]})}function EO({node:e}){let t=B(e=>e.engageDialog),n=B(e=>e.sendDialogDecline),r=B(e=>e.wsStatus),i=e.dialog_id||``,a=e.dialog_messages||[],o=r===`connected`,s=a.find(e=>e.role===`agent`);return(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-fuchsia-500/10 border border-fuchsia-500/30`,children:[(0,H.jsxs)(`span`,{className:`relative flex h-2.5 w-2.5 flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`animate-ping absolute inline-flex h-full w-full rounded-full bg-fuchsia-400 opacity-75`}),(0,H.jsx)(`span`,{className:`relative inline-flex rounded-full h-2.5 w-2.5 bg-fuchsia-500`})]}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-fuchsia-400 tracking-wide`,children:`Dialog Requested`})]}),s&&(0,H.jsxs)(`div`,{className:`rounded-lg px-3 py-2 bg-amber-500/10 border border-amber-500/30`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold mb-1 text-[var(--text-muted)]`,children:e.name}),(0,H.jsx)(`div`,{className:`dialog-markdown text-xs leading-relaxed text-[var(--text)]`,children:(0,H.jsx)(cT,{remarkPlugins:[fO],children:s.content})})]}),(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(`div`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`How would you like to proceed?`}),(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsxs)(`button`,{onClick:t,disabled:!o,className:`flex-1 flex items-center justify-center gap-1.5 text-xs px-3 py-2 rounded-lg border border-fuchsia-500/40 bg-fuchsia-500/10 text-fuchsia-300 hover:bg-fuchsia-500/20 transition-colors font-medium disabled:opacity-40 disabled:cursor-not-allowed`,children:[(0,H.jsx)(me,{className:`w-3 h-3`}),`💬 Discuss`]}),(0,H.jsxs)(`button`,{onClick:()=>{o&&n(e.name,i)},disabled:!o,className:`flex-1 flex items-center justify-center gap-1.5 text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] text-[var(--text-muted)] hover:bg-[var(--surface-hover)] transition-colors font-medium disabled:opacity-40 disabled:cursor-not-allowed`,children:[(0,H.jsx)(je,{className:`w-3 h-3`}),`✕ Skip & continue`]})]})]})]})}function DO({node:e}){let t=e.status,n=X[t]||X.pending,r=B(e=>e.navigateToContext),i=B(e=>e.viewContextPath),a=Wh().map((e,t)=>({ctx:e,index:t})).filter(({ctx:t})=>t.parentAgent===e.name),o=new Map;for(let{ctx:e}of a)o.set(e.slotKey,(o.get(e.slotKey)??0)+1);let s=[];return e.elapsed!=null&&s.push({label:`Elapsed`,value:gt(e.elapsed)}),e.cost_usd!=null&&s.push({label:`Cost`,value:vt(e.cost_usd)}),e.tokens!=null&&s.push({label:`Tokens`,value:_t(e.tokens)}),e.iteration!=null&&e.iteration>1&&s.push({label:`Iteration`,value:e.iteration}),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Subworkflow Agent`})]}),(0,H.jsx)(_v,{items:s}),a.length>0&&(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:[`Subworkflow Runs (`,a.length,`)`]}),(0,H.jsx)(`div`,{className:`space-y-1`,children:a.map(({ctx:e,index:t})=>(0,H.jsx)(OO,{ctx:e,showIteration:(o.get(e.slotKey)??0)>1,onClick:()=>r([...i,t])},`${e.slotKey}-${e.iteration}-${t}`))})]}),t===`failed`&&(e.error_type||e.error_message)&&(0,H.jsxs)(`div`,{className:`text-xs text-red-400`,children:[e.error_type&&(0,H.jsx)(`span`,{className:`font-semibold`,children:e.error_type}),e.error_message&&(0,H.jsxs)(`span`,{className:`ml-1`,children:[`— `,e.error_message]})]}),a.length===0&&t===`pending`&&(0,H.jsx)(`div`,{className:`text-xs text-[var(--text-muted)] italic`,children:`Subworkflow has not started yet.`})]})}function OO({ctx:e,showIteration:t,onClick:n}){let r=X[e.status]||X.pending;return(0,H.jsxs)(`button`,{onClick:n,className:`flex items-center gap-2 w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] hover:bg-[var(--node-bg)] transition-colors text-left`,children:[(0,H.jsx)(ue,{className:`w-3.5 h-3.5 flex-shrink-0`,style:{color:r}}),(0,H.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,H.jsxs)(`span`,{className:`text-xs font-medium text-[var(--text)] truncate`,children:[e.workflowName||e.workflowFile||`Subworkflow`,t&&(0,H.jsxs)(`span`,{className:`ml-1.5 text-[var(--text-muted)] font-normal`,children:[`· Iteration `,e.iteration]})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-[var(--text-muted)]`,children:[e.agentsTotal>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,H.jsx)(le,{className:`w-2.5 h-2.5`}),e.agentsCompleted,`/`,e.agentsTotal,` agents`]}),e.totalCost>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,H.jsx)(ne,{className:`w-2.5 h-2.5`}),vt(e.totalCost)]})]})]}),(0,H.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider flex-shrink-0 px-1.5 py-0.5 rounded`,style:{backgroundColor:`${r}20`,color:r},children:e.status}),(0,H.jsx)(M,{className:`w-3.5 h-3.5 flex-shrink-0 text-[var(--text-muted)]`})]})}function kO({node:e}){let t=e.status,n=X[t]||X.pending,r=[],i=e.requested_seconds??e.duration_seconds;return i!=null&&r.push({label:`Requested`,value:gt(i)}),e.waited_seconds==null?e.elapsed!=null&&r.push({label:`Elapsed`,value:gt(e.elapsed)}):r.push({label:`Waited`,value:gt(e.waited_seconds)}),e.interrupted&&r.push({label:`Interrupted`,value:`yes`}),e.reason&&r.push({label:`Reason`,value:e.reason}),e.error_type&&r.push({label:`Error`,value:e.error_type}),e.error_message&&r.push({label:`Message`,value:e.error_message}),(0,H.jsxs)(`div`,{className:`space-y-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider`,style:{backgroundColor:`${n}20`,color:n},children:t}),(0,H.jsx)(`span`,{className:`text-xs text-[var(--text-muted)]`,children:`Wait`})]}),(0,H.jsx)(_v,{items:r})]})}function AO(){let e=B(e=>e.selectedNode),t=Hh(),n=B(e=>e.selectNode),r=B(e=>e.dialogEngaged),[i,a]=(0,v.useState)(!1);(0,v.useEffect)(()=>(requestAnimationFrame(()=>a(!0)),()=>a(!1)),[e]);let o=e?t??null:null;if(!e||!o)return(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-[var(--surface)]`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between px-4 py-3 border-b border-[var(--border)]`,children:(0,H.jsx)(`h2`,{className:`text-sm font-semibold text-[var(--text)]`,children:`Detail`})}),(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Click a node to view details`})})]});let s=(()=>{if(o.dialog_active&&!r)return EO;if(o.dialog_active&&r)return Tv;switch(o.type){case`script`:return Ov;case`wait`:return kO;case`set`:return kv;case`human_gate`:return _O;case`questions`:return xO;case`parallel_group`:case`for_each_group`:return CO;case`workflow`:return DO;default:return Tv}})();return(0,H.jsxs)(`div`,{className:U(`h-full flex flex-col bg-[var(--surface)] transition-all duration-150 ease-out`,i?`translate-x-0 opacity-100`:`translate-x-4 opacity-0`),children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-3 border-b border-[var(--border)] flex-shrink-0`,children:[(0,H.jsx)(`h2`,{className:`text-sm font-semibold text-[var(--text)] truncate`,children:e?Ih(e).name:``}),(0,H.jsx)(`button`,{onClick:()=>n(null),className:`p-1 rounded hover:bg-[var(--surface-hover)] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,title:`Close panel`,children:(0,H.jsx)(je,{className:`w-4 h-4`})})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3`,children:(0,H.jsx)(s,{node:o})})]})}function jO(e){if(e==null)return``;if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function MO(){let e=B(e=>e.eventLog),t=B(e=>e.activityLog),n=B(e=>e.workflowOutput),r=B(e=>e.workflowStatus),[i,a]=(0,v.useState)(`log`),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0),[u,d]=(0,v.useState)(0),f=(0,v.useCallback)(n=>{a(n),n===`log`&&l(e.length),n===`activity`&&d(t.length)},[e.length,t.length]);(0,v.useEffect)(()=>{i===`log`&&l(e.length)},[i,e.length]),(0,v.useEffect)(()=>{i===`activity`&&d(t.length)},[i,t.length]),(0,v.useEffect)(()=>{r===`completed`&&n!=null&&a(`output`)},[r,n]);let p=n!=null,m=i===`log`?0:Math.max(0,e.length-c),h=i===`activity`?0:Math.max(0,t.length-u);return o?(0,H.jsx)(`div`,{className:`flex items-center bg-[var(--surface)] border-t border-[var(--border)] px-3 py-1`,children:(0,H.jsxs)(`button`,{onClick:()=>s(!1),className:`flex items-center gap-1.5 text-xs text-[var(--text-muted)] hover:text-[var(--text)] transition-colors`,children:[(0,H.jsx)(N,{className:`w-3 h-3`}),(0,H.jsx)(we,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Output`}),t.length>0&&(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)]`,children:[`(`,t.length,`)`]})]})}):(0,H.jsxs)(`div`,{className:`flex flex-col h-full bg-[var(--surface)] border-t border-[var(--border)]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-2 flex-shrink-0 border-b border-[var(--border)]`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,H.jsx)(NO,{active:i===`log`,onClick:()=>f(`log`),icon:(0,H.jsx)(we,{className:`w-3 h-3`}),label:`Log`,count:e.length,unread:m}),(0,H.jsx)(NO,{active:i===`activity`,onClick:()=>f(`activity`),icon:(0,H.jsx)(T,{className:`w-3 h-3`}),label:`Activity`,count:t.length,unread:h}),(0,H.jsx)(NO,{active:i===`output`,onClick:()=>f(`output`),icon:(0,H.jsx)(oe,{className:`w-3 h-3`}),label:`Output`,badge:p?r===`failed`?`error`:`success`:void 0})]}),(0,H.jsx)(`button`,{onClick:()=>s(!0),className:`p-1 rounded text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--surface-hover)] transition-colors`,title:`Collapse panel`,children:(0,H.jsx)(j,{className:`w-3.5 h-3.5`})})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:i===`activity`?(0,H.jsx)(FO,{entries:t}):i===`log`?(0,H.jsx)(LO,{entries:e}):(0,H.jsx)(zO,{output:n,status:r})})]})}function NO({active:e,onClick:t,icon:n,label:r,count:i,badge:a,unread:o}){return(0,H.jsxs)(`button`,{onClick:t,className:U(`relative flex items-center gap-1.5 px-3 py-1.5 text-xs transition-colors border-b-2 -mb-px`,e?`text-[var(--text)] border-[var(--accent)]`:`text-[var(--text-muted)] border-transparent hover:text-[var(--text-secondary)]`),children:[n,(0,H.jsx)(`span`,{children:r}),i!=null&&i>0&&(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] tabular-nums`,children:i}),a&&(0,H.jsx)(`span`,{className:U(`w-1.5 h-1.5 rounded-full`,a===`success`?`bg-[var(--completed)]`:`bg-[var(--failed)]`)}),!e&&o!=null&&o>0&&(0,H.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 flex h-3.5 min-w-[14px] items-center justify-center rounded-full bg-[var(--accent)] px-1`,children:(0,H.jsx)(`span`,{className:`text-[8px] font-bold text-white leading-none tabular-nums`,children:o>99?`99+`:o})})]})}var PO={reasoning:{color:`text-indigo-400/70`,label:`THINK`,labelColor:`text-indigo-500`},"tool-start":{color:`text-blue-400`,label:`TOOL →`,labelColor:`text-blue-500`},"tool-complete":{color:`text-green-400`,label:`TOOL ←`,labelColor:`text-green-600`},turn:{color:`text-amber-400`,label:`STEP`,labelColor:`text-amber-500`},message:{color:`text-[var(--text)]`,label:`MSG`,labelColor:`text-[var(--text-muted)]`},prompt:{color:`text-cyan-400/70`,label:`PROMPT`,labelColor:`text-cyan-600`},"parse-recovery":{color:`text-yellow-400`,label:`RETRY`,labelColor:`text-yellow-600`},"compaction-config":{color:`text-[var(--text-muted)]`,label:`COMPACT`,labelColor:`text-[var(--text-muted)]`},"compaction-start":{color:`text-[var(--text-muted)]`,label:`COMPACT`,labelColor:`text-[var(--text-muted)]`},"compaction-complete":{color:`text-[var(--text-muted)]`,label:`COMPACT`,labelColor:`text-[var(--text-muted)]`},"compaction-error":{color:`text-yellow-400`,label:`COMPACT`,labelColor:`text-yellow-600`}};function FO({entries:e}){let t=(0,v.useRef)(null),n=(0,v.useRef)(!0),r=B(e=>e.selectNode),[i,a]=(0,v.useState)(``),o=(0,v.useCallback)(()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<30)},[]),s=(0,v.useMemo)(()=>{if(!i)return e;let t=i.toLowerCase();return e.filter(e=>e.source.toLowerCase().includes(t)||jO(e.message).toLowerCase().includes(t))},[e,i]);return(0,v.useEffect)(()=>{t.current&&n.current&&(t.current.scrollTop=t.current.scrollHeight)},[s.length]),e.length===0?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Waiting for agent activity…`})}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-1.5 border-b border-[var(--border-subtle)] flex-shrink-0`,children:[(0,H.jsx)(be,{className:`w-3 h-3 text-[var(--text-muted)] flex-shrink-0`}),(0,H.jsx)(`input`,{type:`text`,value:i,onChange:e=>a(e.target.value),placeholder:`Filter by agent or message…`,className:`flex-1 bg-transparent text-[11px] text-[var(--text)] placeholder:text-[var(--text-muted)] outline-none min-w-0`}),i&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`span`,{className:`text-[10px] text-[var(--text-muted)] tabular-nums flex-shrink-0`,children:[s.length,` of `,e.length]}),(0,H.jsx)(`button`,{onClick:()=>a(``),className:`text-[var(--text-muted)] hover:text-[var(--text)] transition-colors flex-shrink-0`,title:`Clear filter`,children:(0,H.jsx)(je,{className:`w-3 h-3`})})]})]}),(0,H.jsxs)(`div`,{ref:t,onScroll:o,className:`flex-1 overflow-y-auto font-mono text-[11px] leading-[1.6] px-3 py-2`,children:[s.map((e,t)=>{let n=PO[e.type]||PO.message;return(0,H.jsxs)(`div`,{className:`group`,children:[(0,H.jsxs)(`div`,{className:`flex gap-1.5 hover:bg-[var(--surface-hover)] rounded px-1 -mx-1`,children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] flex-shrink-0 select-none tabular-nums`,children:RO(e.timestamp)}),(0,H.jsx)(`span`,{className:U(`flex-shrink-0 w-[5ch] text-[10px] font-semibold tabular-nums select-none`,n.labelColor),children:n.label}),(0,H.jsx)(`button`,{onClick:()=>r(Fh([],e.source)),className:`text-[var(--text-secondary)] flex-shrink-0 min-w-[8ch] max-w-[16ch] truncate hover:text-[var(--accent)] hover:underline transition-colors text-left`,title:`Select ${e.source}`,children:e.source}),(0,H.jsx)(`span`,{className:U(`break-words min-w-0`,n.color,e.type===`reasoning`&&`italic`),children:jO(e.message)})]}),e.detail&&(0,H.jsx)(`div`,{className:`ml-[calc(7ch+5ch+8ch+1rem)] px-2 py-1 my-0.5 bg-[var(--bg)] rounded text-[10px] text-[var(--text-muted)] whitespace-pre-wrap break-words max-h-24 overflow-y-auto border-l-2 border-[var(--border)]`,children:jO(e.detail)})]},t)}),i&&s.length===0&&(0,H.jsx)(`div`,{className:`flex items-center justify-center py-4`,children:(0,H.jsxs)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:[`No matches for "`,i,`"`]})})]})]})}var IO={info:{color:`text-blue-400`,icon:`›`},success:{color:`text-green-400`,icon:`✓`},error:{color:`text-red-400`,icon:`✗`},warning:{color:`text-amber-400`,icon:`⚠`},debug:{color:`text-[var(--text-muted)]`,icon:`·`}};function LO({entries:e}){let t=(0,v.useRef)(null),n=(0,v.useRef)(!0),r=B(e=>e.selectNode),i=(0,v.useCallback)(()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<30)},[]);return(0,v.useEffect)(()=>{t.current&&n.current&&(t.current.scrollTop=t.current.scrollHeight)},[e.length]),e.length===0?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:`Waiting for events…`})}):(0,H.jsx)(`div`,{ref:t,onScroll:i,className:`h-full overflow-y-auto font-mono text-[11px] leading-[1.6] px-3 py-2`,children:e.map((e,t)=>{let n=IO[e.level]||IO.info;return(0,H.jsxs)(`div`,{className:`flex gap-2 hover:bg-[var(--surface-hover)] rounded px-1 -mx-1`,children:[(0,H.jsx)(`span`,{className:`text-[var(--text-muted)] flex-shrink-0 select-none tabular-nums`,children:RO(e.timestamp)}),(0,H.jsx)(`span`,{className:U(`flex-shrink-0 w-3 text-center select-none`,n.color),children:n.icon}),(0,H.jsx)(`button`,{onClick:()=>r(Fh([],e.source)),className:`text-[var(--text-secondary)] flex-shrink-0 min-w-[8ch] max-w-[16ch] truncate hover:text-[var(--accent)] hover:underline transition-colors text-left`,title:`Select ${e.source}`,children:e.source}),(0,H.jsx)(`span`,{className:U(`break-words`,e.level===`error`?`text-red-400`:e.level===`success`?`text-green-400`:`text-[var(--text)]`),children:jO(e.message)})]},t)})})}function RO(e){let t=new Date(e*1e3);return`${t.getHours().toString().padStart(2,`0`)}:${t.getMinutes().toString().padStart(2,`0`)}:${t.getSeconds().toString().padStart(2,`0`)}`}function zO({output:e,status:t}){let[n,r]=(0,v.useState)(!1),i=yt(e);return e==null?(0,H.jsx)(`div`,{className:`h-full flex items-center justify-center`,children:(0,H.jsx)(`p`,{className:`text-xs text-[var(--text-muted)]`,children:t===`running`?`Workflow running — output will appear when complete…`:t===`failed`?`Workflow failed — no output produced`:`No output yet`})}):(0,H.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-1 border-b border-[var(--border-subtle)] flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`text-[10px] text-[var(--text-muted)] uppercase tracking-wider font-semibold`,children:`Workflow Result`}),(0,H.jsx)(`button`,{onClick:async()=>{i&&(await navigator.clipboard.writeText(i),r(!0),setTimeout(()=>r(!1),2e3))},className:`flex items-center gap-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text)] transition-colors px-1.5 py-0.5 rounded hover:bg-[var(--surface-hover)]`,title:`Copy to clipboard`,children:n?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(A,{className:`w-3 h-3 text-[var(--completed)]`}),(0,H.jsx)(`span`,{className:`text-[var(--completed)]`,children:`Copied`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(re,{className:`w-3 h-3`}),(0,H.jsx)(`span`,{children:`Copy`})]})})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-auto px-3 py-2`,children:(0,H.jsx)(`pre`,{className:`font-mono text-[11px] leading-relaxed text-[var(--text)] whitespace-pre-wrap break-words`,children:typeof e==`object`?(0,H.jsx)(BO,{text:i}):i})})]})}function BO({text:e}){let t=e.split(/("(?:[^"\\]|\\.)*")/g);return(0,H.jsx)(H.Fragment,{children:t.map((e,n)=>{if(n%2==1){let r=t.slice(n+1).join(``);return(0,H.jsx)(`span`,{className:/^\s*:/.test(r)?`text-blue-400`:`text-green-400`,children:e},n)}return(0,H.jsx)(`span`,{dangerouslySetInnerHTML:{__html:e.replace(/\b(true|false|null)\b|(-?\d+\.?\d*(?:e[+-]?\d+)?)/gi,(e,t,n)=>t?`${e}`:n?`${e}`:e)}},n)})})}function VO({text:e}){return(0,H.jsx)(`div`,{className:`dialog-markdown text-xs leading-relaxed text-[var(--text)]`,children:(0,H.jsx)(cT,{remarkPlugins:[fO],components:{h1:({children:e})=>(0,H.jsx)(`h1`,{className:`text-sm font-bold mb-2 mt-1`,children:e}),h2:({children:e})=>(0,H.jsx)(`h2`,{className:`text-xs font-bold mb-1.5 mt-1`,children:e}),h3:({children:e})=>(0,H.jsx)(`h3`,{className:`text-xs font-semibold mb-1 mt-1`,children:e}),p:({children:e})=>(0,H.jsx)(`p`,{className:`mb-1.5 last:mb-0`,children:e}),ul:({children:e})=>(0,H.jsx)(`ul`,{className:`list-disc list-inside mb-1.5 space-y-0.5`,children:e}),ol:({children:e})=>(0,H.jsx)(`ol`,{className:`list-decimal list-inside mb-1.5 space-y-0.5`,children:e}),li:({children:e})=>(0,H.jsx)(`li`,{children:e}),code:({children:e,className:t})=>t?.includes(`language-`)?(0,H.jsx)(`code`,{className:`block bg-[var(--bg)] border border-[var(--border)] rounded px-2 py-1.5 font-mono text-[11px] my-1 overflow-x-auto whitespace-pre`,children:e}):(0,H.jsx)(`code`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded px-1 py-0.5 font-mono text-[11px]`,children:e}),pre:({children:e})=>(0,H.jsx)(`pre`,{className:`bg-[var(--bg)] border border-[var(--border)] rounded-md px-2.5 py-2 font-mono text-[11px] my-1.5 overflow-x-auto`,children:e}),strong:({children:e})=>(0,H.jsx)(`strong`,{className:`font-semibold`,children:e}),em:({children:e})=>(0,H.jsx)(`em`,{className:`italic`,children:e}),a:({href:e,children:t})=>(0,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-400 hover:text-blue-300 underline underline-offset-2`,children:t}),blockquote:({children:e})=>(0,H.jsx)(`blockquote`,{className:`border-l-2 border-[var(--border)] pl-2.5 my-1.5 opacity-80`,children:e}),hr:()=>(0,H.jsx)(`hr`,{className:`border-[var(--border)] my-2`}),table:({children:e})=>(0,H.jsx)(`div`,{className:`overflow-x-auto my-2`,children:(0,H.jsx)(`table`,{className:`text-[11px] border-collapse w-full`,children:e})}),th:({children:e})=>(0,H.jsx)(`th`,{className:`border border-[var(--border)] px-2 py-1 text-left bg-[var(--bg)] font-semibold`,children:e}),td:({children:e})=>(0,H.jsx)(`td`,{className:`border border-[var(--border)] px-2 py-1`,children:e})},children:e})})}function HO({node:e}){let t=B(e=>e.sendDialogMessage),n=B(e=>e.wsStatus),[r,i]=(0,v.useState)(``),a=(0,v.useRef)(null),o=e.dialog_active===!0,s=e.dialog_id||``,c=e.dialog_messages||[],l=o&&n===`connected`;(0,v.useEffect)(()=>{a.current?.scrollIntoView({behavior:`smooth`})},[c.length,e.dialog_awaiting_response]);let u=()=>{!r.trim()||!l||(t(e.name,s,r.trim()),i(``))};return(0,H.jsxs)(`div`,{className:`flex flex-col h-full`,children:[o?(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-fuchsia-500/10 border border-fuchsia-500/30 mb-3 flex-shrink-0`,children:[(0,H.jsxs)(`span`,{className:`relative flex h-2.5 w-2.5 flex-shrink-0`,children:[(0,H.jsx)(`span`,{className:`animate-ping absolute inline-flex h-full w-full rounded-full bg-fuchsia-400 opacity-75`}),(0,H.jsx)(`span`,{className:`relative inline-flex rounded-full h-2.5 w-2.5 bg-fuchsia-500`})]}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-fuchsia-400 tracking-wide`,children:`Dialog Mode`}),(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[c.length,` message`,c.length===1?``:`s`]})]}):(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg bg-[var(--surface)] border border-[var(--border)] mb-3 flex-shrink-0`,children:[(0,H.jsx)(me,{className:`w-3.5 h-3.5 text-[var(--text-muted)]`}),(0,H.jsx)(`span`,{className:`text-xs font-semibold text-[var(--text-muted)] tracking-wide`,children:`Dialog Completed`}),(0,H.jsxs)(`span`,{className:`ml-auto text-[10px] text-[var(--text-muted)]`,children:[c.length,` message`,c.length===1?``:`s`]})]}),(0,H.jsxs)(`div`,{className:`flex-1 overflow-y-auto space-y-3 min-h-0 mb-3`,children:[c.map((t,n)=>(0,H.jsx)(`div`,{className:`flex ${t.role===`user`?`justify-end`:`justify-start`}`,children:(0,H.jsxs)(`div`,{className:`max-w-[85%] rounded-lg px-3 py-2 ${t.role===`agent`?`bg-amber-500/10 border border-amber-500/30`:`bg-blue-500/10 border border-blue-500/30`}`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold mb-1 text-[var(--text-muted)]`,children:t.role===`agent`?e.name:`You`}),(0,H.jsx)(VO,{text:t.content})]})},n)),e.dialog_awaiting_response&&(0,H.jsx)(`div`,{className:`flex justify-start`,children:(0,H.jsxs)(`div`,{className:`max-w-[85%] rounded-lg px-3 py-2 bg-amber-500/10 border border-amber-500/30`,children:[(0,H.jsx)(`div`,{className:`text-[10px] font-semibold mb-1 text-[var(--text-muted)]`,children:e.name}),(0,H.jsxs)(`div`,{className:`flex gap-1 items-center h-4`,children:[(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-amber-400/60 animate-bounce [animation-delay:0ms]`}),(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-amber-400/60 animate-bounce [animation-delay:150ms]`}),(0,H.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-amber-400/60 animate-bounce [animation-delay:300ms]`})]})]})}),(0,H.jsx)(`div`,{ref:a})]}),o&&(0,H.jsxs)(`div`,{className:`flex-shrink-0 border-t border-[var(--border)] pt-3`,children:[(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[(0,H.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),u())},placeholder:`Type your message...`,className:`flex-1 text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-fuchsia-400 transition-colors`,disabled:!l,autoFocus:!0}),(0,H.jsxs)(`button`,{onClick:u,disabled:!l||!r.trim(),className:`flex items-center justify-center gap-1.5 text-xs px-8 py-2 rounded-lg bg-fuchsia-500 text-white hover:bg-fuchsia-600 transition-colors font-medium disabled:opacity-40 disabled:cursor-not-allowed`,children:[(0,H.jsx)(xe,{className:`w-3 h-3`}),`Send`]})]}),(0,H.jsx)(`p`,{className:`text-[10px] text-[var(--text-muted)] mt-1.5 px-1`,children:`Press Enter to send · Type "done" to end dialog`})]})]})}function UO(){let e=B(e=>e.activeDialog),t=B(e=>e.nodes);if(!e)return null;let n=t[e.agentName];return n?(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-[var(--bg)] overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-5 py-3 border-b border-[var(--border)] bg-[var(--surface)] flex-shrink-0`,children:[(0,H.jsx)(me,{className:`w-4 h-4 text-fuchsia-400`}),(0,H.jsxs)(`h2`,{className:`text-sm font-semibold text-[var(--text)]`,children:[`Dialog with `,e.agentName]})]}),(0,H.jsx)(`div`,{className:`flex-1 overflow-hidden px-5 py-4`,children:(0,H.jsx)(HO,{node:n})})]}):null}function WO(){let e=B(e=>e.selectedNode),t=B(e=>e.activeDialog),n=B(e=>e.dialogEngaged);return(0,H.jsxs)(cr,{direction:`vertical`,className:`flex-1 overflow-hidden`,children:[(0,H.jsx)(Ft,{defaultSize:70,minSize:30,children:(0,H.jsxs)(cr,{direction:`horizontal`,className:`h-full`,children:[(0,H.jsx)(Ft,{defaultSize:e?65:100,minSize:40,children:t&&n?(0,H.jsx)(UO,{}):(0,H.jsx)(uv,{})}),e&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(fr,{className:`w-[3px] bg-[var(--border)] hover:bg-[var(--text-muted)] transition-colors cursor-col-resize`}),(0,H.jsx)(Ft,{defaultSize:35,minSize:20,maxSize:60,children:(0,H.jsx)(AO,{})})]})]})}),(0,H.jsx)(fr,{className:`h-[3px] bg-[var(--border)] hover:bg-[var(--text-muted)] transition-colors cursor-row-resize`}),(0,H.jsx)(Ft,{defaultSize:30,minSize:5,maxSize:70,collapsible:!0,children:(0,H.jsx)(MO,{})})]})}var GO=10;function KO(){let e=B(e=>e.iterationLimitGate),t=B(e=>e.wsStatus),n=B(e=>e.sendIterationLimitResponse),[r,i]=(0,v.useState)(String(GO)),[a,o]=(0,v.useState)(!1);(0,v.useEffect)(()=>{e?.gate_id&&(i(String(GO)),o(!1))},[e?.gate_id]);let s=(0,v.useMemo)(()=>{let e=Number(r);return!Number.isFinite(e)||e<0?null:Math.floor(e)},[r]);if(!e||e.skip_gates)return null;let c=e.agent_name??e.group_name??`workflow`,l=t===`connected`&&!a,u=!l||s==null||s<=0,d=()=>e.agent_name===void 0?{group_name:e.group_name}:{agent_name:e.agent_name},f=()=>{u||s==null||(o(!0),n(d(),e.gate_id,s))};return(0,H.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`iteration-limit-title`,"data-testid":`iteration-limit-modal`,className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm`,children:(0,H.jsxs)(`div`,{className:`relative flex flex-col w-[90vw] max-w-md rounded-xl border border-amber-500/40 bg-[var(--surface)] shadow-2xl overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 px-4 py-3 border-b border-[var(--border)] bg-amber-500/10`,children:[(0,H.jsx)(De,{className:`w-4 h-4 text-amber-400 flex-shrink-0`}),(0,H.jsx)(`h2`,{id:`iteration-limit-title`,className:`text-sm font-semibold text-[var(--text)]`,children:`Max iterations reached`})]}),(0,H.jsxs)(`div`,{className:`px-4 py-4 space-y-3`,children:[(0,H.jsxs)(`p`,{className:`text-xs text-[var(--text)]`,children:[(0,H.jsx)(`span`,{className:`font-semibold`,children:c}),` reached`,` `,(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[e.current_iteration,`/`,e.max_iterations]}),` `,`iterations.`]}),e.possible_loop&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/5 border border-amber-500/30`,children:[(0,H.jsx)(De,{className:`w-3.5 h-3.5 text-amber-400 flex-shrink-0`}),(0,H.jsx)(`span`,{className:`text-[11px] text-amber-300`,children:`The same agent has run repeatedly — this may indicate a loop.`})]}),e.agent_history.length>0&&(0,H.jsxs)(`div`,{className:`space-y-1`,children:[(0,H.jsx)(`h3`,{className:`text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Recent agents`}),(0,H.jsx)(`ol`,{className:`text-[11px] text-[var(--text-muted)] list-decimal list-inside space-y-0.5`,children:e.agent_history.map((e,t)=>(0,H.jsx)(`li`,{children:e},`${t}-${e}`))})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:`iteration-limit-additional`,className:`block text-[10px] uppercase tracking-wider text-[var(--text-muted)] font-semibold`,children:`Additional iterations`}),(0,H.jsx)(`input`,{id:`iteration-limit-additional`,"data-testid":`iteration-limit-input`,type:`number`,min:0,step:1,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),f())},disabled:!l,autoFocus:!0,className:`w-full text-xs px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] outline-none focus:border-amber-400 transition-colors disabled:opacity-50`}),(0,H.jsx)(`p`,{className:`text-[10px] text-[var(--text-muted)]`,children:`Enter a positive number to continue, or press Stop to end the workflow.`})]}),t!==`connected`&&(0,H.jsx)(`div`,{className:`text-[11px] text-red-300`,children:`Disconnected from server — reconnect to resolve this gate.`})]}),(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-2 px-4 py-3 border-t border-[var(--border)] bg-[var(--surface-raised)]`,children:[(0,H.jsxs)(`button`,{type:`button`,"data-testid":`iteration-limit-stop`,onClick:()=>{l&&(o(!0),n(d(),e.gate_id,0))},disabled:!l,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg border border-[var(--border)] text-[var(--text)] hover:bg-[var(--surface-hover)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,children:[(0,H.jsx)(I,{className:`w-3.5 h-3.5`}),`Stop`]}),(0,H.jsxs)(`button`,{type:`button`,"data-testid":`iteration-limit-continue`,onClick:f,disabled:u,className:`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg bg-amber-500 text-white hover:bg-amber-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium`,children:[(0,H.jsx)(ve,{className:`w-3.5 h-3.5`}),`Continue`]})]})]})})}var qO=3e4;function JO(){let e=B(e=>e.processEvent),t=B(e=>e.replayState),n=B(e=>e.setWsStatus),r=B(e=>e.setWsSend),i=B(e=>e.setWsAuthFailed),a=(0,v.useRef)(null),o=(0,v.useRef)(1e3),s=(0,v.useRef)(null),c=(0,v.useRef)(null),l=(0,v.useRef)(()=>{}),u=(0,v.useCallback)(()=>{n(`reconnecting`),s.current=setTimeout(()=>{o.current=Math.min(o.current*2,qO),l.current()},o.current)},[n]),d=(0,v.useCallback)(()=>{n(`connecting`),c.current&&c.current.abort();let s=new AbortController;c.current=s,fetch(`/api/state`,{signal:s.signal}).then(e=>{if(!e.ok)throw Error(`GET /api/state -> ${e.status}`);return e.json()}).then(s=>{s&&s.length>0&&t(s);let c=He(`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}/ws`);try{let t=new WebSocket(c);a.current=t;let s=!1;t.onopen=()=>{s=!0,o.current=1e3,n(`connected`),i(!1),r(e=>{t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))})},t.onmessage=t=>{try{e(JSON.parse(t.data))}catch(e){console.error(`Failed to parse WebSocket message:`,e)}},t.onclose=()=>{n(`disconnected`),r(null),a.current=null,s||(i(!0),o.current=qO),u()},t.onerror=()=>{}}catch{u()}}).catch(e=>{s.signal.aborted||(console.error(`Failed to fetch state:`,e),u())})},[e,t,n,r,i,u]);l.current=d,(0,v.useEffect)(()=>(d(),()=>{c.current&&c.current.abort(),s.current&&clearTimeout(s.current),a.current&&a.current.close(),r(null)}),[d,r])}function YO(){let e=B(e=>e.setReplayMode),t=B(e=>e.markReplayMode),n=B(e=>e.setWsStatus),r=B(e=>e.replayPlaying),i=B(e=>e.replayPosition),a=B(e=>e.replayTotalEvents),o=B(e=>e.replaySpeed),s=B(e=>e.replayEvents),c=B(e=>e.setReplayPosition);(0,v.useEffect)(()=>{t(),n(`connecting`),fetch(`/api/state`).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status} from /api/state`);return e.json()}).then(t=>{e(t),n(`connected`)}).catch(e=>{console.error(`Failed to load replay events:`,e),n(`disconnected`)})},[e,t,n]);let l=(0,v.useRef)(null);(0,v.useEffect)(()=>{if(!r||i>=a){l.current&&clearTimeout(l.current),r&&i>=a&&B.getState().setReplayPlaying(!1);return}let e=s[i-1],t=s[i],n=100;if(e&&t){let r=(t.timestamp-e.timestamp)*1e3;n=Math.max(16,Math.min(r/o,2e3))}return l.current=setTimeout(()=>{c(i+1)},n),()=>{l.current&&clearTimeout(l.current)}},[r,i,a,o,s,c])}function XO(){return JO(),null}function ZO(){return YO(),null}function QO(){let[e,t]=(0,v.useState)(null),n=B(e=>e.replayMode),r=B(e=>e.selectNode),i=B(e=>e.workflowName);return(0,v.useEffect)(()=>{fetch(`/api/replay/info`).then(e=>{e.ok?t(!0):t(!1)}).catch(()=>t(!1))},[]),(0,v.useEffect)(()=>{document.title=i?`Conductor — ${i}`:`Conductor Dashboard`},[i]),(0,v.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r(null)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]),e===null?null:(0,H.jsxs)(`div`,{className:`h-full flex flex-col bg-[var(--bg)]`,children:[e?(0,H.jsx)(ZO,{}):(0,H.jsx)(XO,{}),(0,H.jsx)(mt,{}),(0,H.jsx)(ht,{}),(0,H.jsx)(WO,{}),n?(0,H.jsx)(Tt,{}):(0,H.jsx)(St,{}),!n&&(0,H.jsx)(KO,{})]})}(0,y.createRoot)(document.getElementById(`root`)).render((0,H.jsx)(v.StrictMode,{children:(0,H.jsx)(QO,{})})); \ No newline at end of file diff --git a/src/conductor/web/static/index.html b/src/conductor/web/static/index.html index cd879513..a00047bd 100644 --- a/src/conductor/web/static/index.html +++ b/src/conductor/web/static/index.html @@ -5,7 +5,7 @@ Conductor Dashboard - + diff --git a/tests/test_cli/test_logging.py b/tests/test_cli/test_logging.py index 1afee083..a5dbe81b 100644 --- a/tests/test_cli/test_logging.py +++ b/tests/test_cli/test_logging.py @@ -2386,3 +2386,103 @@ def test_module_verbose_console_is_silent_aware(self) -> None: from conductor.cli.run import _SilentAwareConsole, _verbose_console assert isinstance(_verbose_console, _SilentAwareConsole) + + +class TestConsoleEventSubscriberMcpSteps: + """ConsoleEventSubscriber rendering of mcp step lifecycle events.""" + + def _drive(self, event_type: str, data: dict) -> str: + """Drive the subscriber with one event in verbose mode and return its output.""" + import time + from io import StringIO + + from rich.console import Console + + from conductor.cli.run import ConsoleEventSubscriber + from conductor.events import WorkflowEvent + + subscriber = ConsoleEventSubscriber() + output = StringIO() + token = verbose_mode.set(True) + try: + with patch( + "conductor.cli.run._verbose_console", + Console(file=output, force_terminal=True, no_color=True), + ): + event = WorkflowEvent(type=event_type, timestamp=time.time(), data=data) + subscriber.on_event(event) + return output.getvalue() + finally: + verbose_mode.reset(token) + + def test_mcp_completed_renders_server_tool_and_elapsed(self) -> None: + # Requirement: an mcp step's completion is visible in the console with + # its server, tool, and elapsed time (mirror of the wait_completed branch). + text = self._drive( + "mcp_completed", + { + "agent_name": "fetch", + "elapsed": 1.25, + "server": "filesystem", + "tool": "read_file", + "is_error": False, + "result_bytes": 128, + "truncated": False, + }, + ) + assert "filesystem" in text + assert "read_file" in text + assert "1.25" in text + + def test_mcp_failed_renders_error_line(self) -> None: + # Requirement: a connect/invoke failure is visible immediately, not only + # at workflow_failed — the branch exists where script_failed has none. + text = self._drive( + "mcp_failed", + { + "agent_name": "fetch", + "elapsed": 0.5, + "server": "filesystem", + "tool": "read_file", + "error_type": "ConnectionError", + "message": ( + "MCP step 'fetch' failed; full diagnostic: /tmp/conductor/x.mcp-diagnostics.log" + ), + }, + ) + assert "filesystem" in text + assert "read_file" in text + assert "ConnectionError" in text + + def test_mcp_started_is_not_printed(self) -> None: + # Requirement: started events never reach the console (precedent of all + # other step types) — only the completion/failure lines may appear. + text = self._drive( + "mcp_started", + { + "agent_name": "fetch", + "iteration": 1, + "server": "filesystem", + "tool": "read_file", + "argument_keys": ["path"], + }, + ) + assert "filesystem" not in text + + def test_mcp_completed_bracketed_server_name_renders_verbatim(self) -> None: + # Requirement: markup-injection guard — a server name containing a + # bracketed token must render literally, not be parsed as styling, + # deleted, or raise MarkupError (#406 rules). + text = self._drive( + "mcp_completed", + { + "agent_name": "fetch", + "elapsed": 0.1, + "server": "my[bracket]server", + "tool": "read_file", + "is_error": False, + "result_bytes": 8, + "truncated": False, + }, + ) + assert "my[bracket]server" in text diff --git a/tests/test_config/test_mcp_step_schema.py b/tests/test_config/test_mcp_step_schema.py new file mode 100644 index 00000000..c497c7c2 --- /dev/null +++ b/tests/test_config/test_mcp_step_schema.py @@ -0,0 +1,226 @@ +"""Tests for ``type: mcp`` step schema validation. + +Tests cover: +- Valid mcp agent definitions (minimal + full) +- Required server/tool validation +- The full forbidden-field matrix (every LLM and sibling-step field) +- Literal-only server/tool (Jinja templates rejected at load time) +- timeout acceptance (unlike wait/set steps) +- server/tool/arguments rejection on all other step types + +Field matrix under test (requirement: every AgentDef field must be +allow / forbid / covered-by-standalone-guard for ``type: mcp``): +- ALLOWED: name, description, input, output, routes, timeout, server, tool, + arguments +- FORBIDDEN: prompt, system_prompt, provider, model, tools, reasoning, + context_tier, skills, plugins, validator, dialog, sandbox, session_key, + max_agent_iterations, max_session_seconds, output_mode, retry, + timeout_seconds, command, args, env, working_dir, options, workflow, + input_mapping, max_depth, value, values, output_type +- COVERED BY STANDALONE GUARDS: stdin (script guard), duration + reason + (wait/terminate guard), status + output_template (terminate guard), + questions/source/allow_*/abort_route (questions guard), server/tool/ + arguments on non-mcp types (mcp-exclusive guard) +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from pydantic import ValidationError + +from conductor.config.schema import AgentDef, GateOption, OutputField, RouteDef + + +def _mcp_agent(**overrides: Any) -> AgentDef: + """Build a valid minimal mcp agent, applying overrides.""" + kwargs: dict[str, Any] = {"name": "lookup", "type": "mcp", "server": "docs", "tool": "search"} + kwargs.update(overrides) + return AgentDef(**kwargs) + + +class TestMcpAgentDefValid: + """Tests for valid mcp type AgentDef construction.""" + + def test_valid_minimal_mcp_step(self) -> None: + """Requirement: a minimal type: mcp step needs only server and tool.""" + agent = _mcp_agent() + assert agent.type == "mcp" + assert agent.server == "docs" + assert agent.tool == "search" + assert agent.arguments is None + assert agent.timeout is None + + def test_valid_mcp_step_with_all_allowed_fields(self) -> None: + """Requirement: output, routes, input, timeout, description, arguments are allowed.""" + agent = _mcp_agent( + description="Look up docs", + arguments={"query": "{{ workflow.input.q }}"}, + input=["prep.output"], + output={"hits": OutputField(type="number")}, + routes=[RouteDef(to="$end")], + timeout=30, + ) + assert agent.arguments == {"query": "{{ workflow.input.q }}"} + assert agent.timeout == 30 + assert "hits" in (agent.output or {}) + + def test_mcp_step_timeout_accepted(self) -> None: + """Requirement: timeout is allowed on mcp steps (unlike wait/set which forbid it).""" + agent = _mcp_agent(timeout=30) + assert agent.timeout == 30 + + def test_mcp_step_output_accepted(self) -> None: + """Requirement: mcp steps may declare an output schema like script steps.""" + agent = _mcp_agent(output={"result": OutputField(type="string")}) + assert agent.output is not None + + def test_mcp_arguments_allow_jinja_templates(self) -> None: + """Requirement: arguments ARE rendered recursively, so Jinja is allowed there.""" + agent = _mcp_agent(arguments={"q": "{{ searcher.output.query }}", "n": 5}) + assert agent.arguments == {"q": "{{ searcher.output.query }}", "n": 5} + + +class TestMcpAgentDefRequiredFields: + """Tests for required server/tool fields.""" + + def test_mcp_without_server_raises(self) -> None: + """Requirement: mcp steps require 'server'.""" + with pytest.raises(ValidationError, match="mcp agents require 'server'"): + AgentDef(name="bad", type="mcp", tool="search") + + def test_mcp_with_empty_server_raises(self) -> None: + """Requirement: an empty server string is rejected as missing.""" + with pytest.raises(ValidationError, match="mcp agents require 'server'"): + AgentDef(name="bad", type="mcp", server="", tool="search") + + def test_mcp_without_tool_raises(self) -> None: + """Requirement: mcp steps require 'tool'.""" + with pytest.raises(ValidationError, match="mcp agents require 'tool'"): + AgentDef(name="bad", type="mcp", server="docs") + + def test_mcp_with_empty_tool_raises(self) -> None: + """Requirement: an empty tool string is rejected as missing.""" + with pytest.raises(ValidationError, match="mcp agents require 'tool'"): + AgentDef(name="bad", type="mcp", server="docs", tool="") + + +# Requirement: each LLM-only or sibling-step field must be rejected on mcp steps. +# field name -> (kwarg value, regex fragment matching the error message). +_FORBIDDEN_FIELDS: list[tuple[str, Any, str]] = [ + # LLM fields + ("prompt", "do something", r"'prompt'"), + ("system_prompt", "You are...", r"'system_prompt'"), + ("provider", "copilot", r"'provider'"), + ("model", "gpt-4", r"'model'"), + ("tools", ["web_search"], r"'tools'"), + ("reasoning", {"effort": "high"}, r"'reasoning'"), + ("context_tier", "long_context", r"'context_tier'"), + ("skills", ["conductor"], r"'skills'"), + ("plugins", ["prs"], r"'plugins'"), + ("validator", {"criteria": "must be good"}, r"'validator'"), + ("dialog", {"trigger_prompt": "pause if unsure"}, r"'dialog'"), + ("sandbox", {"identifier_scope": "item"}, r"'sandbox'"), + ("session_key", "my-key", r"'session_key'"), + ("max_agent_iterations", 5, r"'max_agent_iterations'"), + ("max_session_seconds", 60.0, r"'max_session_seconds'"), + ("output_mode", "raw", r"'output_mode'"), + ("retry", {"max_attempts": 2}, r"'retry'"), + ( + "timeout_seconds", + 30.0, + r"'timeout_seconds'.*use 'timeout'", + ), # mirrors the script branch message + # Sibling-step fields + ("command", "echo", r"'command'"), + ("args", ["a"], r"'args'"), + ("env", {"A": "b"}, r"'env'"), + ("working_dir", "/tmp", r"'working_dir'"), + ("settings_dir", "/tmp", r"'settings_dir'"), + ("options", [GateOption(label="OK", value="ok", route="$end")], r"'options'"), + ("workflow", "sub.yaml", r"'workflow'"), + ("input_mapping", {"a": "{{ b }}"}, r"'input_mapping'"), + ("max_depth", 2, r"'max_depth'"), + ("value", "{{ 1 }}", r"'value'"), + ("values", {"a": "{{ 1 }}"}, r"'values'"), + ("output_type", "auto", r"'output_type'"), +] + + +class TestMcpAgentDefForbiddenFields: + """Parameterized matrix: every forbidden field is rejected with a named error.""" + + @pytest.mark.parametrize(("field_name", "value", "message"), _FORBIDDEN_FIELDS) + def test_mcp_forbidden_field_raises(self, field_name: str, value: Any, message: str) -> None: + """Requirement: mcp steps cannot set LLM-only or sibling-step fields.""" + with pytest.raises(ValidationError, match=message): + _mcp_agent(**{field_name: value}) + + def test_mcp_with_stdin_raises(self) -> None: + """Requirement: stdin is rejected via the standalone script guard.""" + with pytest.raises(ValidationError, match="'stdin'"): + _mcp_agent(stdin="payload") + + def test_mcp_with_duration_raises(self) -> None: + """Requirement: duration is rejected via the wait-only guard at method bottom.""" + with pytest.raises(ValidationError, match="'duration'"): + _mcp_agent(duration=5) + + def test_mcp_with_reason_raises(self) -> None: + """Requirement: reason is rejected (only wait/terminate support it).""" + with pytest.raises(ValidationError, match="'reason'"): + _mcp_agent(reason="because") + + def test_mcp_with_status_raises(self) -> None: + """Requirement: status is rejected via the terminate-exclusive guard.""" + with pytest.raises(ValidationError, match="'status'"): + _mcp_agent(status="success") + + def test_mcp_with_output_template_raises(self) -> None: + """Requirement: output_template is rejected via the terminate-exclusive guard.""" + with pytest.raises(ValidationError, match="'output_template'"): + _mcp_agent(output_template={"a": "b"}) + + +class TestMcpFieldsLiteralOnly: + """Tests for the literal-only server/tool contract.""" + + @pytest.mark.parametrize( + "template", ["{{ workflow.input.server }}", "{% if x %}docs{% endif %}"] + ) + def test_jinja_in_server_rejected(self, template: str) -> None: + """Requirement: server is never rendered — Jinja templates are rejected at load time.""" + with pytest.raises(ValidationError, match="never rendered"): + AgentDef(name="bad", type="mcp", server=template, tool="search") + + @pytest.mark.parametrize( + "template", ["{{ workflow.input.tool }}", "{% if x %}search{% endif %}"] + ) + def test_jinja_in_tool_rejected(self, template: str) -> None: + """Requirement: tool is never rendered — Jinja templates are rejected at load time.""" + with pytest.raises(ValidationError, match="never rendered"): + AgentDef(name="bad", type="mcp", server="docs", tool=template) + + +class TestMcpFieldsForbiddenOnOtherTypes: + """server/tool/arguments are exclusive to type: mcp.""" + + @pytest.mark.parametrize("field_name", ["server", "tool", "arguments"]) + def test_mcp_fields_rejected_on_script(self, field_name: str) -> None: + """Requirement: server/tool/arguments on a script step raise the mcp-exclusive error.""" + value: Any = {"server": "docs", "tool": "search"}.get(field_name, {"q": "x"}) + with pytest.raises(ValidationError, match=f"cannot have '{field_name}'"): + AgentDef(name="bad", type="script", command="echo", **{field_name: value}) + + @pytest.mark.parametrize("field_name", ["server", "tool", "arguments"]) + def test_mcp_fields_rejected_on_regular_agent(self, field_name: str) -> None: + """Requirement: server/tool/arguments on an LLM agent raise the mcp-exclusive error.""" + value: Any = {"server": "docs", "tool": "search"}.get(field_name, {"q": "x"}) + with pytest.raises(ValidationError, match=f"cannot have '{field_name}'"): + AgentDef(name="bad", prompt="hello", **{field_name: value}) + + def test_mcp_fields_rejected_on_wait(self) -> None: + """Requirement: server on a wait step is rejected even though wait has its own branch.""" + with pytest.raises(ValidationError, match="cannot have 'server'"): + AgentDef(name="bad", type="wait", duration=5, server="docs") diff --git a/tests/test_config/test_mcp_step_validation.py b/tests/test_config/test_mcp_step_validation.py new file mode 100644 index 00000000..9a8d87ed --- /dev/null +++ b/tests/test_config/test_mcp_step_validation.py @@ -0,0 +1,333 @@ +"""Tests for static ``type: mcp`` step validation in ``config/validator.py``. + +Covers the early off-network diagnostics that ``conductor validate`` runs: +- The step's ``server`` must be declared in ``workflow.runtime.mcp_servers``. +- The server's ``tools`` filter must allow the step's ``tool``. +- Only stdio servers are supported (http/sse is not implemented yet). +- ``arguments`` templates are collected recursively, so references to + unknown steps or same-parallel-group members fail at validate-time. +- Explicit context mode must not emit a spurious ``workflow.input`` warning + for mcp steps (they read rendered arguments, not declared inputs). +- Inline for-each mcp agents (absent from ``config.agents``) are validated + too, with errors naming the enclosing for-each group. +""" + +from __future__ import annotations + +import pytest + +from conductor.config.schema import ( + AgentDef, + ContextConfig, + ForEachDef, + InputDef, + MCPServerDef, + ParallelGroup, + RouteDef, + RuntimeConfig, + WorkflowConfig, + WorkflowDef, +) +from conductor.config.validator import validate_workflow_config +from conductor.exceptions import ConfigurationError + + +def _make_workflow( + *agents: AgentDef, + entry_point: str | None = None, + mcp_servers: dict[str, MCPServerDef] | None = None, + parallel: list[ParallelGroup] | None = None, + for_each: list[ForEachDef] | None = None, + context: ContextConfig | None = None, + inputs: dict[str, InputDef] | None = None, +) -> WorkflowConfig: + """Build a minimal WorkflowConfig carrying the given mcp server table.""" + names = ( + [a.name for a in agents] + + [p.name for p in parallel or []] + + [f.name for f in for_each or []] + ) + return WorkflowConfig( + workflow=WorkflowDef( + name="mcp-step-test", + entry_point=entry_point or names[0], + runtime=RuntimeConfig(provider="copilot", mcp_servers=mcp_servers or {}), + context=context or ContextConfig(), + input=inputs or {}, + ), + agents=list(agents), + parallel=parallel or [], + for_each=for_each or [], + ) + + +def _mcp_agent( + name: str = "m", + server: str = "srv", + tool: str = "do_thing", + arguments: dict[str, object] | None = None, +) -> AgentDef: + return AgentDef( + name=name, + type="mcp", + server=server, + tool=tool, + arguments=arguments, + ) + + +class TestValidMcpStep: + def test_stdio_server_with_star_allowlist_passes(self) -> None: + # Requirement: an mcp step against a stdio server with tools ["*"] validates clean. + config = _make_workflow( + _mcp_agent(), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + ) + assert validate_workflow_config(config) == [] + + def test_tool_in_explicit_allowlist_passes(self) -> None: + # Requirement: exact membership in the server's tools list allows the tool. + config = _make_workflow( + _mcp_agent(tool="get_issue"), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server", tools=["get_issue"])}, + ) + assert validate_workflow_config(config) == [] + + def test_nested_arguments_pass(self) -> None: + # Requirement: nested dict/list argument templates are collected without false positives. + config = _make_workflow( + _mcp_agent(arguments={"opts": {"labels": ["a", "{{ workflow.input.x }}"]}}), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + inputs={"x": InputDef(type="string")}, + ) + assert validate_workflow_config(config) == [] + + +class TestUnknownServer: + def test_unknown_server_errors_and_lists_available(self) -> None: + # Requirement: a server not declared in runtime.mcp_servers is an error naming both. + config = _make_workflow( + _mcp_agent(server="nope"), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + ) + with pytest.raises(ConfigurationError, match="unknown MCP server 'nope'"): + validate_workflow_config(config) + + def test_no_servers_declared(self) -> None: + # Requirement: the error message stays useful when no servers are declared at all. + config = _make_workflow(_mcp_agent()) + with pytest.raises(ConfigurationError, match="unknown MCP server 'srv'"): + validate_workflow_config(config) + + +class TestToolAllowlist: + def test_tool_outside_allowlist_errors(self) -> None: + # Requirement: a tool not in the server's tools filter (and no "*") is an error. + config = _make_workflow( + _mcp_agent(tool="delete_everything"), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server", tools=["get_issue"])}, + ) + with pytest.raises(ConfigurationError, match="not allowed by server 'srv'"): + validate_workflow_config(config) + + def test_unknown_server_skips_allowlist_check(self) -> None: + # Requirement: an unknown server reports one error, not a cascade. + config = _make_workflow( + _mcp_agent(server="nope", tool="delete_everything"), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server", tools=["get_issue"])}, + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + assert "not allowed by server" not in str(exc_info.value) + + def test_singleton_wildcard_allows_any_tool(self) -> None: + # Requirement: ["*"] means all tools (schema docstring contract). + config = _make_workflow( + _mcp_agent(tool="anything_at_all"), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server", tools=["*"])}, + ) + assert validate_workflow_config(config) == [] + + def test_mixed_wildcard_list_allows_any_tool(self) -> None: + # Requirement: wildcard MEMBERSHIP is the rule at both boundaries — + # ["*", "health"] is accepted here exactly when the runtime check in + # engine/workflow.py::_run_mcp_step accepts it (shared rule). + config = _make_workflow( + _mcp_agent(tool="anything_at_all"), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server", tools=["*", "health"])}, + ) + assert validate_workflow_config(config) == [] + + def test_empty_tools_list_allows_nothing(self) -> None: + # Requirement: an explicitly empty allowlist permits no tool. + config = _make_workflow( + _mcp_agent(tool="anything_at_all"), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server", tools=[])}, + ) + with pytest.raises(ConfigurationError, match="not allowed by server 'srv'"): + validate_workflow_config(config) + + +class TestArgumentTemplateSyntax: + def test_malformed_template_in_arguments_errors(self) -> None: + # Requirement: a syntax-broken argument template fails at validate + # time with the step and nested path named — reference analysis + # (_extract_template_refs) deliberately swallows TemplateSyntaxError, + # so without the explicit parse this only failed at execution. + config = _make_workflow( + _mcp_agent(arguments={"path": "{{ workflow.input.foo"}), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + inputs={"foo": InputDef(type="string")}, + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + assert "invalid Jinja2 template syntax" in str(exc_info.value) + assert "arguments.path" in str(exc_info.value) + + def test_malformed_template_nested_in_list_errors(self) -> None: + # Requirement: the syntax check walks lists too, not just mappings. + config = _make_workflow( + _mcp_agent(arguments={"opts": {"labels": ["ok", "{% if x"]}}), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + assert "invalid Jinja2 template syntax" in str(exc_info.value) + assert "arguments.opts.labels[1]" in str(exc_info.value) + + def test_valid_nested_templates_still_pass(self) -> None: + # Requirement: well-formed nested templates produce no syntax error. + config = _make_workflow( + _mcp_agent(arguments={"opts": {"labels": ["a", "{{ workflow.input.x }}"], "n": 3}}), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + inputs={"x": InputDef(type="string")}, + ) + assert validate_workflow_config(config) == [] + + +class TestTransport: + def test_http_server_errors(self) -> None: + # Requirement: type: mcp supports stdio servers only; http is rejected with a clear message. + config = _make_workflow( + _mcp_agent(), + mcp_servers={"srv": MCPServerDef(type="http", url="http://localhost:8080/mcp")}, + ) + with pytest.raises( + ConfigurationError, + match=r"stdio servers only \(got 'http'\); http/sse support is not implemented yet", + ): + validate_workflow_config(config) + + def test_sse_server_errors(self) -> None: + # Requirement: sse transport is rejected the same way as http. + config = _make_workflow( + _mcp_agent(), + mcp_servers={"srv": MCPServerDef(type="sse", url="http://localhost:8080/sse")}, + ) + with pytest.raises(ConfigurationError, match=r"got 'sse'"): + validate_workflow_config(config) + + +class TestArgumentsTemplateReferences: + def test_unknown_step_reference_in_arguments_errors(self) -> None: + # Requirement: arguments templates are validated, so a reference to an + # unknown step fails at validate-time with the arguments label. + config = _make_workflow( + _mcp_agent(arguments={"query": "{{ ghost.output.x }}"}), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + message = str(exc_info.value) + assert "arguments.query" in message + assert "unknown agent 'ghost'" in message + + def test_same_parallel_group_reference_in_arguments_errors(self) -> None: + # Requirement: an mcp step in a parallel group cannot reference another + # member of the same group via arguments (pre-group snapshot semantics). + config = _make_workflow( + _mcp_agent(name="m", arguments={"q": "{{ m2.output.x }}"}), + _mcp_agent(name="m2"), + entry_point="pg", + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + parallel=[ + ParallelGroup( + name="pg", + agents=["m", "m2"], + ) + ], + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + message = str(exc_info.value) + assert "arguments.q" in message + assert "same parallel group 'pg'" in message + + def test_explicit_mode_workflow_input_reference_does_not_warn(self) -> None: + # Requirement: mcp steps read rendered arguments (not declared inputs), + # so a workflow.input reference must not trigger the explicit-mode warning. + config = _make_workflow( + _mcp_agent(arguments={"q": "{{ workflow.input.topic }}"}), + mcp_servers={"srv": MCPServerDef(command="my-mcp-server")}, + context=ContextConfig(mode="explicit"), + inputs={"topic": InputDef(type="string")}, + ) + assert validate_workflow_config(config) == [] + + +class TestInlineForEachAgent: + def _for_each_workflow( + self, agent: AgentDef, servers: dict[str, MCPServerDef] + ) -> WorkflowConfig: + return _make_workflow( + entry_point="fans", + mcp_servers=servers, + for_each=[ + ForEachDef( + name="fans", + type="for_each", + source="workflow.input.items", + **{"as": "item"}, + agent=agent, + routes=[RouteDef(to="$end")], + ) + ], + inputs={"items": InputDef(type="array")}, + ) + + def test_unknown_server_errors_naming_the_group(self) -> None: + # Requirement: inline for-each mcp agents (absent from config.agents) are + # validated, and the error names the enclosing for-each group. + config = self._for_each_workflow( + _mcp_agent(server="nope"), + {"srv": MCPServerDef(command="my-mcp-server")}, + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + message = str(exc_info.value) + assert "unknown MCP server 'nope'" in message + assert "for-each group 'fans'" in message + + def test_http_transport_errors_naming_the_group(self) -> None: + # Requirement: transport restrictions apply to inline for-each agents too. + config = self._for_each_workflow( + _mcp_agent(), + {"srv": MCPServerDef(type="http", url="http://localhost:8080/mcp")}, + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + message = str(exc_info.value) + assert "stdio servers only" in message + assert "for-each group 'fans'" in message + + def test_tool_outside_allowlist_errors_naming_the_group(self) -> None: + # Requirement: the tools-filter restriction applies to inline for-each agents too. + config = self._for_each_workflow( + _mcp_agent(tool="delete_everything"), + {"srv": MCPServerDef(command="my-mcp-server", tools=["get_issue"])}, + ) + with pytest.raises(ConfigurationError) as exc_info: + validate_workflow_config(config) + message = str(exc_info.value) + assert "not allowed by server 'srv'" in message + assert "for-each group 'fans'" in message diff --git a/tests/test_engine/test_mcp_step_groups.py b/tests/test_engine/test_mcp_step_groups.py new file mode 100644 index 00000000..1abe3c83 --- /dev/null +++ b/tests/test_engine/test_mcp_step_groups.py @@ -0,0 +1,1101 @@ +"""Tests for `type: mcp` steps inside parallel groups and for-each groups. + +Covers: +- An mcp step as a parallel-group member completes with ``group_name`` in + every ``mcp_*`` payload and no ``parallel_agent_started`` (LLM-only event) +- for_each inline mcp over an N-element array invokes the tool N times, with + ``item_key`` present in ALL ``mcp_*`` events +- Two concurrently active items stay isolated: one item's completion never + closes or mutates the other's events or output +- The per-server slot lock serializes for_each items against ONE server + (max simultaneous calls = 1) while different servers run concurrently +- A Jinja-templated ``runtime.working_dir`` resolving to different + directories per item produces one pool manager per (server, cwd) +- ``is_error: true`` on an item is DATA, not an exception: fail_fast / + continue_on_error are not triggered and the group completes as on success +- A child completing with ``CancelledError`` by itself (a BaseException that + bypasses ``except Exception``) still triggers the fail-fast cancel+drain — + the sibling observes cancellation before the pool close in run()'s + finally — and the CancelledError propagates unchanged; external + cancellation of the whole group cancels+drains children the same way + +All MCP interaction is mocked — no real MCP servers are spawned. +""" + +from __future__ import annotations + +import asyncio +import json +import os +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from conductor.config.schema import ( + AgentDef, + ContextConfig, + ForEachDef, + LimitsConfig, + MCPServerDef, + OutputField, + ParallelGroup, + RouteDef, + RuntimeConfig, + WorkflowConfig, + WorkflowDef, +) +from conductor.engine.workflow import WorkflowEngine +from conductor.events import WorkflowEvent, WorkflowEventEmitter +from conductor.exceptions import ExecutionError + + +def _make_engine(config: WorkflowConfig) -> WorkflowEngine: + return WorkflowEngine(config, MagicMock()) + + +def _collect_events(engine: WorkflowEngine) -> list[WorkflowEvent]: + emitter = WorkflowEventEmitter() + received: list[WorkflowEvent] = [] + emitter.subscribe(received.append) + engine._event_emitter = emitter + return received + + +def _envelope(is_error: bool = False, answer: int = 42) -> dict[str, Any]: + """A raw manager-shaped envelope (before the executor's structured merge).""" + return { + "content": [{"type": "text", "text": f"result-{answer}", "truncated": False}], + "structured": {"answer": answer}, + "is_error": is_error, + } + + +def _patch_manager(*, call: Any = None) -> Any: + """Patch MCPManager where the engine lazily imports it. + + The fake manager advertises one tool ``echo`` on every server. + ``call`` is an optional async side_effect for ``call_tool_structured``; + without it every call returns a success envelope. + """ + patcher = patch("conductor.mcp.manager.MCPManager") + manager_cls = patcher.start() + manager = manager_cls.return_value + manager.connect_server = AsyncMock(return_value=[]) + manager.close = AsyncMock() + manager.get_server_tools = MagicMock( + side_effect=lambda name: [{"name": f"{name}__echo", "original_name": "echo"}] + ) + if call is None: + manager.call_tool_structured = AsyncMock(return_value=_envelope()) + else: + manager.call_tool_structured = AsyncMock(side_effect=call) + return patcher + + +def _runtime( + *, mcp_servers: dict[str, MCPServerDef], working_dir: str | None = None +) -> RuntimeConfig: + return RuntimeConfig(provider="copilot", mcp_servers=mcp_servers, working_dir=working_dir) + + +def _mcp_agent(name: str, server: str, arguments: dict[str, Any] | None = None) -> AgentDef: + return AgentDef( + name=name, + type="mcp", + server=server, + tool="echo", + arguments=arguments or {"q": "hello"}, + ) + + +class _ConcurrencyProbe: + """Async side effect tracking max simultaneous ``call_tool_structured`` calls.""" + + def __init__(self, delay: float = 0.02) -> None: + self._delay = delay + self.active = 0 + self.max_active = 0 + self.calls = 0 + + async def run(self, *_args: Any, **_kwargs: Any) -> dict[str, Any]: + self.calls += 1 + self.active += 1 + self.max_active = max(self.max_active, self.active) + try: + await asyncio.sleep(self._delay) + return _envelope() + finally: + self.active -= 1 + + +class TestMcpInParallelGroup: + @pytest.mark.asyncio + async def test_mcp_member_completes_with_group_events(self) -> None: + # Requirement: an mcp step as a parallel-group member completes; every + # mcp_* payload carries group_name; the member completion event has + # agent_type "mcp" with NO output field (no-values policy); and NO + # parallel_agent_started is emitted for the mcp member (that event is + # LLM-only, mirroring the set branch). + provider = MagicMock() + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel", + entry_point="grp", + runtime=_runtime(mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + _mcp_agent("call", "srv"), + AgentDef(name="flag", type="set", value="ready", routes=[]), + ], + parallel=[ + ParallelGroup(name="grp", agents=["call", "flag"], routes=[RouteDef(to="$end")]) + ], + output={ + "answer": "{{ grp.outputs.call.answer }}", + "flag": "{{ grp.outputs.flag }}", + }, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + patcher = _patch_manager() + try: + result = await engine.run({}) + finally: + patcher.stop() + + assert result == {"answer": 42, "flag": "ready"} + provider.execute.assert_not_called() + + mcp_events = [ev for ev in received if ev.type.startswith("mcp_")] + assert {ev.type for ev in mcp_events} == {"mcp_started", "mcp_completed"} + for ev in mcp_events: + assert ev.data["group_name"] == "grp" + + completed = next( + ev + for ev in received + if ev.type == "parallel_agent_completed" and ev.data["agent_name"] == "call" + ) + assert completed.data["agent_type"] == "mcp" + assert "output" not in completed.data + + started = [ev for ev in received if ev.type == "parallel_agent_started"] + assert all(ev.data["agent_name"] != "call" for ev in started) + + @pytest.mark.asyncio + async def test_two_servers_in_parallel_group_run_concurrently(self) -> None: + # Requirement: two mcp steps on DIFFERENT servers in one parallel + # group are not serialized by the per-server slot lock — max + # simultaneous calls observed is 2 (proven by a cross-wait: each call + # waits for the other's start, so under serialization the wait + # deadline would trip). + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel-two-servers", + entry_point="grp", + runtime=_runtime( + mcp_servers={ + "one": MCPServerDef(type="stdio", command="npx"), + "two": MCPServerDef(type="stdio", command="npx"), + } + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[_mcp_agent("cx", "one"), _mcp_agent("cy", "two")], + parallel=[ParallelGroup(name="grp", agents=["cx", "cy"], routes=[RouteDef(to="$end")])], + output={"total": "{{ grp.outputs.cx.answer + grp.outputs.cy.answer }}"}, + ) + engine = _make_engine(config) + + probe = _ConcurrencyProbe() + started: dict[str, asyncio.Event] = {"one": asyncio.Event(), "two": asyncio.Event()} + other = {"one": "two", "two": "one"} + + async def cross_wait(server: str, *_args: Any, **_kwargs: Any) -> dict[str, Any]: + started[server].set() + await asyncio.wait_for(started[other[server]].wait(), timeout=5) + return await probe.run() + + patcher = _patch_manager(call=cross_wait) + try: + result = await engine.run({}) + finally: + patcher.stop() + + assert result == {"total": 84} + assert probe.max_active == 2 + assert probe.calls == 2 + + @pytest.mark.asyncio + async def test_fail_fast_cancels_and_drains_sibling_mcp_call(self) -> None: + # Requirement: when one mcp member fails under fail_fast, the sibling + # still blocked inside its call is cancelled and AWAITED before the + # exception propagates — no mcp task outlives the group to race the + # pool close in run()'s finally or emit events after the failure. + # Group failure events must also carry no raw exception text. + canary = "secret-argument-value" + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel-fail-fast", + entry_point="grp", + runtime=_runtime( + mcp_servers={ + "one": MCPServerDef(type="stdio", command="npx"), + "two": MCPServerDef(type="stdio", command="npx"), + } + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + _mcp_agent("fast", "one"), + _mcp_agent("slow", "two"), + ], + parallel=[ParallelGroup(name="grp", agents=["fast", "slow"])], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + order: list[str] = [] + original_close = engine._close_mcp_step_managers + + async def recording_close() -> None: + order.append("pool-close") + await original_close() + + engine._close_mcp_step_managers = recording_close # type: ignore[method-assign] + + blocking = asyncio.Event() + + async def fast_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + # Fail only once the sibling is genuinely blocked inside its call, + # so the drain must cancel an in-flight step, not a not-yet-started one. + await asyncio.wait_for(blocking.wait(), timeout=5) + raise RuntimeError(f"fast exploded with {canary}") + + async def slow_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + blocking.set() + try: + await asyncio.Event().wait() # blocks until cancelled + except asyncio.CancelledError: + order.append("sibling-cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + async def dispatch(server: str, *_args: Any, **_kwargs: Any) -> dict[str, Any]: + if server == "one": + return await fast_call() + return await slow_call() + + patcher = _patch_manager(call=dispatch) + try: + with pytest.raises(ExecutionError): + await engine.run({}) + finally: + patcher.stop() + + # The sibling observed cancellation, and was drained before the pool + # was closed at end of run(). + assert order == ["sibling-cancelled", "pool-close"] + # Group failure events carry only the redacted message. + failed = [ev for ev in received if ev.type == "parallel_agent_failed"] + assert len(failed) == 1 + assert failed[0].data["agent_name"] == "fast" + assert canary not in json.dumps(failed[0].data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + + @pytest.mark.asyncio + async def test_fail_fast_child_cancellederror_drains_sibling(self) -> None: + # Requirement: a child completing with CancelledError BY ITSELF (a + # BaseException, not an external cancel) propagates out of gather + # without entering an except-Exception arm — the fail-fast path must + # still cancel and drain the sibling blocked inside its mcp call + # before anything propagates, and the CancelledError must propagate + # unchanged (no conversion to a group failure, no workflow_failed). + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel-cancelled", + entry_point="grp", + runtime=_runtime( + mcp_servers={ + "one": MCPServerDef(type="stdio", command="npx"), + "two": MCPServerDef(type="stdio", command="npx"), + } + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + _mcp_agent("fast", "one"), + _mcp_agent("slow", "two"), + ], + parallel=[ParallelGroup(name="grp", agents=["fast", "slow"])], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + order: list[str] = [] + original_close = engine._close_mcp_step_managers + + async def recording_close() -> None: + order.append("pool-close") + await original_close() + + engine._close_mcp_step_managers = recording_close # type: ignore[method-assign] + + blocking = asyncio.Event() + + async def fast_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + # Fail only once the sibling is genuinely blocked inside its call, + # so the drain must cancel an in-flight step. + await asyncio.wait_for(blocking.wait(), timeout=5) + raise asyncio.CancelledError() + + async def slow_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + blocking.set() + try: + await asyncio.Event().wait() # blocks until cancelled + except asyncio.CancelledError: + order.append("sibling-cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + async def dispatch(server: str, *_args: Any, **_kwargs: Any) -> dict[str, Any]: + if server == "one": + return await fast_call() + return await slow_call() + + patcher = _patch_manager(call=dispatch) + try: + with pytest.raises(asyncio.CancelledError): + await engine.run({}) + finally: + patcher.stop() + + # The sibling observed cancellation and was drained before the pool + # close; cancellation stayed cancellation all the way out (no + # workflow_failed is emitted for it). + assert order == ["sibling-cancelled", "pool-close"] + assert not any(ev.type == "workflow_failed" for ev in received) + + @pytest.mark.asyncio + async def test_external_cancellation_drains_children_before_propagating(self) -> None: + # Requirement: cancelling the run task from outside (dashboard stop / + # timeout) lands as CancelledError at the gather and must cancel and + # drain in-flight group children before propagating — the sibling + # observes cancellation before the pool close in run()'s finally. + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel-external-cancel", + entry_point="grp", + runtime=_runtime( + mcp_servers={ + "one": MCPServerDef(type="stdio", command="npx"), + "two": MCPServerDef(type="stdio", command="npx"), + } + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + _mcp_agent("idle", "one"), + _mcp_agent("slow", "two"), + ], + parallel=[ParallelGroup(name="grp", agents=["idle", "slow"])], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + order: list[str] = [] + original_close = engine._close_mcp_step_managers + + async def recording_close() -> None: + order.append("pool-close") + await original_close() + + engine._close_mcp_step_managers = recording_close # type: ignore[method-assign] + + entered = asyncio.Event() + + async def idle_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + return _envelope() + + async def slow_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + entered.set() + try: + await asyncio.Event().wait() # blocks until cancelled + except asyncio.CancelledError: + order.append("sibling-cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + async def dispatch(server: str, *_args: Any, **_kwargs: Any) -> dict[str, Any]: + if server == "one": + return await idle_call() + return await slow_call() + + run_task = asyncio.ensure_future(engine.run({})) + patcher = _patch_manager(call=dispatch) + try: + await asyncio.wait_for(entered.wait(), timeout=5) + run_task.cancel() + with pytest.raises(asyncio.CancelledError): + await run_task + finally: + patcher.stop() + + assert order == ["sibling-cancelled", "pool-close"] + assert not any(ev.type == "workflow_failed" for ev in received) + + @pytest.mark.asyncio + async def test_repeated_cancellation_still_drains_sibling_cleanup(self) -> None: + # Requirement: a SECOND cancel() arriving while the fail-fast drain is + # in flight must not abandon the drain — the sibling's cancellation + # cleanup (which awaits, e.g. releasing a resource) completes before + # the pool close in run()'s finally, and the propagated exception is + # the original CancelledError (the extra cancellation never replaces + # it). + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel-repeated-cancel", + entry_point="grp", + runtime=_runtime( + mcp_servers={ + "one": MCPServerDef(type="stdio", command="npx"), + "two": MCPServerDef(type="stdio", command="npx"), + } + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + _mcp_agent("idle", "one"), + _mcp_agent("slow", "two"), + ], + parallel=[ParallelGroup(name="grp", agents=["idle", "slow"])], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + order: list[str] = [] + original_close = engine._close_mcp_step_managers + + async def recording_close() -> None: + order.append("pool-close") + await original_close() + + engine._close_mcp_step_managers = recording_close # type: ignore[method-assign] + + entered = asyncio.Event() + + async def idle_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + return _envelope() + + async def slow_call(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + entered.set() + try: + await asyncio.Event().wait() # blocks until cancelled + except asyncio.CancelledError: + await asyncio.sleep(0.05) # cancellation cleanup that awaits + order.append("sibling-cleanup-done") + raise + raise AssertionError("unreachable") # pragma: no cover + + async def dispatch(server: str, *_args: Any, **_kwargs: Any) -> dict[str, Any]: + if server == "one": + return await idle_call() + return await slow_call() + + run_task = asyncio.ensure_future(engine.run({})) + patcher = _patch_manager(call=dispatch) + try: + await asyncio.wait_for(entered.wait(), timeout=5) + run_task.cancel() + # Let the first cancellation reach the group gather and the drain + # start (the sibling is now inside its 0.05s cleanup), then cancel + # again — this second request must land on the shield, not the + # drain. + await asyncio.sleep(0.01) + run_task.cancel() + with pytest.raises(asyncio.CancelledError): + await run_task + finally: + patcher.stop() + + # The sibling's cleanup COMPLETED before the pool close, and the + # propagated exception stayed the original CancelledError (no + # workflow_failed is emitted for it). + assert order == ["sibling-cleanup-done", "pool-close"] + assert not any(ev.type == "workflow_failed" for ev in received) + + @pytest.mark.asyncio + async def test_output_schema_mismatch_in_group_member_leaks_no_values(self) -> None: + # Requirement: an output: schema mismatch on an mcp PARALLEL-group + # member wraps redacted — the ValidationError message echoes the + # received result value, so the canary must appear in neither + # parallel_agent_failed nor workflow_failed payloads, nor the raised + # error (the sibling set member succeeding must not change this). + canary = "SECRET_CANARY_9f13" + mcp = _mcp_agent("call", "srv") + mcp.output = {"answer": OutputField(type="number")} + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel-schema", + entry_point="grp", + runtime=_runtime(mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[mcp, AgentDef(name="flag", type="set", value="ready", routes=[])], + parallel=[ + ParallelGroup(name="grp", agents=["call", "flag"], routes=[RouteDef(to="$end")]) + ], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + def _value_envelope(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": "ok", "truncated": False}], + "structured": {"answer": canary}, + "is_error": False, + } + + patcher = _patch_manager(call=_value_envelope) + try: + with pytest.raises(ExecutionError) as exc_info: + await engine.run({}) + finally: + patcher.stop() + + assert canary not in str(exc_info.value) + failed = [ev for ev in received if ev.type == "parallel_agent_failed"] + assert len(failed) == 1 + assert failed[0].data["agent_name"] == "call" + assert canary not in json.dumps(failed[0].data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + + @pytest.mark.asyncio + async def test_templated_working_dir_in_group_member_leaks_no_values(self) -> None: + # Requirement: the runtime working_dir not-a-directory check on an mcp + # PARALLEL-group member must not leak the Jinja-rendered path or the + # raw template — both come from the execution context. The redacted + # message surfaces through parallel_agent_failed / workflow_failed; + # the authored name-only runtime checks stay verbatim (covered by the + # unknown-server test in test_mcp_step_workflow.py). + canary = "SECRET_CANARY_9f13" + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-parallel-cwd", + entry_point="grp", + runtime=_runtime( + mcp_servers={ + "srv": MCPServerDef(type="stdio", command="npx"), + "srv2": MCPServerDef(type="stdio", command="npx"), + }, + working_dir="{{ workflow.input.secret_path }}", + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[_mcp_agent("call", "srv"), _mcp_agent("sibling", "srv2")], + parallel=[ + ParallelGroup(name="grp", agents=["call", "sibling"], routes=[RouteDef(to="$end")]) + ], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + patcher = _patch_manager() + try: + with pytest.raises(ExecutionError) as exc_info: + await engine.run({"secret_path": f"/nonexistent/{canary}"}) + finally: + patcher.stop() + + assert "does not exist or is not a directory" in str(exc_info.value) + assert canary not in str(exc_info.value) + assert "{{ workflow.input.secret_path }}" not in str(exc_info.value) + failed = [ev for ev in received if ev.type == "parallel_agent_failed"] + # Both members share the workflow-level working_dir, so both hit the + # same redacted cwd check. + assert len(failed) == 2 + for ev in failed: + assert canary not in json.dumps(ev.data) + assert "{{ workflow.input.secret_path }}" not in json.dumps(ev.data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + assert "{{ workflow.input.secret_path }}" not in json.dumps(wf_failed[0].data) + + +class TestMcpInForEach: + def _config(self, *, max_concurrent: int = 3) -> WorkflowConfig: + return WorkflowConfig( + workflow=WorkflowDef( + name="mcp-for-each", + entry_point="loop", + runtime=_runtime(mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[], + for_each=[ + ForEachDef( + name="loop", + type="for_each", + source="workflow.input.items", + **{"as": "item"}, + max_concurrent=max_concurrent, + failure_mode="fail_fast", + agent=_mcp_agent("call", "srv", arguments={"q": "{{ item }}"}), + routes=[RouteDef(to="$end")], + ) + ], + output={"count": "{{ loop.outputs | length }}"}, + ) + + @pytest.mark.asyncio + async def test_three_items_with_item_key_in_all_events(self) -> None: + # Requirement: a for_each inline mcp step over a 3-element array + # completes all items, and item_key is present in ALL mcp_* event + # payloads (plus group_name) so per-item events are distinguishable; + # for_each_item_completed carries no output field (no-values policy). + engine = _make_engine(self._config()) + received = _collect_events(engine) + + patcher = _patch_manager() + try: + result = await engine.run({"items": ["a", "b", "c"]}) + finally: + patcher.stop() + + assert result == {"count": 3} + + mcp_started = [ev for ev in received if ev.type == "mcp_started"] + mcp_completed = [ev for ev in received if ev.type == "mcp_completed"] + assert len(mcp_started) == 3 + assert len(mcp_completed) == 3 + for ev in mcp_started + mcp_completed: + assert ev.data["group_name"] == "loop" + assert ev.data["item_key"] in {"0", "1", "2"} + assert {ev.data["item_key"] for ev in mcp_started} == {"0", "1", "2"} + + item_completed = [ev for ev in received if ev.type == "for_each_item_completed"] + assert len(item_completed) == 3 + for ev in item_completed: + assert ev.data["item_key"] in {"0", "1", "2"} + assert "output" not in ev.data + + @pytest.mark.asyncio + async def test_invocation_count_matches_items(self) -> None: + # Requirement: the tool is invoked exactly once per item, each call + # receiving its own item's rendered arguments. + engine = _make_engine(self._config()) + seen: list[str] = [] + + async def record_call( + _server: str, _tool: str, arguments: dict[str, Any] + ) -> dict[str, Any]: + seen.append(arguments["q"]) + return _envelope() + + patcher = _patch_manager(call=record_call) + try: + await engine.run({"items": ["a", "b", "c"]}) + finally: + patcher.stop() + + assert sorted(seen) == ["a", "b", "c"] + + @pytest.mark.asyncio + async def test_interleaved_completions_do_not_cross_contaminate_items(self) -> None: + # Requirement: with two concurrently active items, one item's + # completion (is_error=true) never closes or mutates the other — + # no for_each_item_failed is emitted, both items complete, and each + # item's stored envelope carries only its own outcome. The slot lock + # is loosened to per-call locks so both items are genuinely in flight + # at once (real single-server serialization is pinned by the + # max_concurrent test; real two-server concurrency by the parallel + # test) — one for_each agent cannot name two servers, and server is + # literal-only by schema. + engine = _make_engine(self._config(max_concurrent=2)) + received = _collect_events(engine) + + async def per_call_slot(_server: str) -> asyncio.Lock: + return asyncio.Lock() + + engine._mcp_step_slot = per_call_slot # type: ignore[method-assign] + + started: dict[str, asyncio.Event] = {"x": asyncio.Event(), "y": asyncio.Event()} + finished_x = asyncio.Event() + + async def item_call(_server: str, _tool: str, arguments: dict[str, Any]) -> dict[str, Any]: + item = arguments["q"] + started[item].set() + if item == "x": + # x completes while y is still in flight. + await asyncio.wait_for(started["y"].wait(), timeout=5) + finished_x.set() + return _envelope(is_error=True, answer=1) + await asyncio.wait_for(finished_x.wait(), timeout=5) + return _envelope(is_error=False, answer=2) + + patcher = _patch_manager(call=item_call) + try: + result = await engine.run({"items": ["x", "y"]}) + finally: + patcher.stop() + + assert result == {"count": 2} + assert not any(ev.type == "for_each_item_failed" for ev in received) + assert not any(ev.type == "mcp_failed" for ev in received) + assert not any(ev.type == "workflow_failed" for ev in received) + + # item keys are positional indexes ("0" for x, "1" for y) + x_completed = next( + ev for ev in received if ev.type == "mcp_completed" and ev.data["item_key"] == "0" + ) + assert x_completed.data["is_error"] is True + y_completed = next( + ev for ev in received if ev.type == "mcp_completed" and ev.data["item_key"] == "1" + ) + assert y_completed.data["is_error"] is False + + # Stored outputs stay per-item: x kept its error envelope, y its own. + outputs = engine.context.agent_outputs["loop"]["outputs"] + assert len(outputs) == 2 + by_is_error = {out["is_error"]: out["answer"] for out in outputs} + assert by_is_error == {True: 1, False: 2} + + @pytest.mark.asyncio + async def test_max_concurrent_two_against_one_server_serializes(self) -> None: + # Requirement: even with max_concurrent: 2, items against ONE server + # run strictly sequentially — the per-server slot lock caps max + # simultaneous calls at 1. + engine = _make_engine(self._config(max_concurrent=2)) + probe = _ConcurrencyProbe() + + patcher = _patch_manager(call=probe.run) + try: + await engine.run({"items": ["a", "b", "c"]}) + finally: + patcher.stop() + + assert probe.calls == 3 + assert probe.max_active == 1 + + @pytest.mark.asyncio + async def test_templated_working_dir_pools_per_item_cwd(self, tmp_path: Any) -> None: + # Requirement: a Jinja-templated runtime.working_dir resolving to two + # different directories per for_each item produces one pool entry per + # (server, cwd), and every call runs with its own item's cwd. + dir_a = tmp_path / "dir_a" + dir_b = tmp_path / "dir_b" + dir_a.mkdir() + dir_b.mkdir() + config = self._config(max_concurrent=2) + config.workflow.runtime.working_dir = "{{ item }}" + engine = _make_engine(config) + + original = engine._get_mcp_step_manager + resolved: list[tuple[str, str]] = [] + + async def recording(server_name: str, resolved_cwd: str) -> Any: + resolved.append((server_name, resolved_cwd)) + return await original(server_name, resolved_cwd) + + engine._get_mcp_step_manager = recording # type: ignore[method-assign] + + patcher = _patch_manager() + try: + await engine.run({"items": [str(dir_a), str(dir_b)]}) + finally: + patcher.stop() + + assert sorted(resolved) == [ + ("srv", os.path.normpath(str(dir_a))), + ("srv", os.path.normpath(str(dir_b))), + ] + + @pytest.mark.asyncio + async def test_fail_fast_cancels_and_drains_sibling_item(self) -> None: + # Requirement (for_each variant): a failing item under fail_fast + # cancels and drains the sibling item before the exception + # propagates — the sibling observes cancellation before the pool + # close in run()'s finally, item failure events carry no raw + # exception text, and mcp_failed reports the real error type. + # + # Roles follow CALL order, not item identity: both items share one + # server, so the per-server slot serializes them and no coordination + # event could ever let both be inside a call at once (an earlier + # version of this test waited on exactly such an event — the wait + # timed out, the canary-bearing RuntimeError never fired, and the + # redaction assertions were vacuous). The first item to acquire the + # slot fails immediately; the sibling is cancelled wherever the + # fail-fast drain finds it (blocked at the slot boundary or blocked + # inside its call) — both land in `order` before the pool close. + canary = "secret-argument-value" + engine = _make_engine(self._config(max_concurrent=2)) + received = _collect_events(engine) + + order: list[str] = [] + original_close = engine._close_mcp_step_managers + + async def recording_close() -> None: + order.append("pool-close") + await original_close() + + engine._close_mcp_step_managers = recording_close # type: ignore[method-assign] + + async def item_call(_server: str, _tool: str, _arguments: dict[str, Any]) -> dict[str, Any]: + if not any(entry.startswith("call") for entry in order): + order.append("call-raised") + raise RuntimeError(f"call exploded with {canary}") + # The sibling blocks until the fail-fast drain cancels it. + order.append("sibling-blocked") + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + order.append("sibling-cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + patcher = _patch_manager(call=item_call) + try: + with pytest.raises(ExecutionError): + await engine.run({"items": ["a", "b"]}) + finally: + patcher.stop() + + assert order == ["call-raised", "sibling-blocked", "sibling-cancelled", "pool-close"] + # The canary-bearing RuntimeError genuinely happened (an earlier + # version never raised it) and its type reached mcp_failed. + mcp_failed = [ev for ev in received if ev.type == "mcp_failed"] + assert len(mcp_failed) == 1 + assert mcp_failed[0].data["error_type"] == "RuntimeError" + assert canary not in json.dumps(mcp_failed[0].data) + failed = [ev for ev in received if ev.type == "for_each_item_failed"] + assert len(failed) == 1 + assert canary not in json.dumps(failed[0].data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + + @pytest.mark.asyncio + async def test_fail_fast_item_cancellederror_drains_sibling(self) -> None: + # Requirement: an item completing with CancelledError BY ITSELF (a + # BaseException that bypasses except Exception) must still trigger the + # fail-fast cancel+drain — the sibling item observes cancellation + # (whether parked on the per-server slot or inside its call) before + # the pool close in run()'s finally — and the CancelledError + # propagates unchanged out of the run. + engine = _make_engine(self._config(max_concurrent=2)) + received = _collect_events(engine) + + order: list[str] = [] + original_close = engine._close_mcp_step_managers + + async def recording_close() -> None: + order.append("pool-close") + await original_close() + + engine._close_mcp_step_managers = recording_close # type: ignore[method-assign] + + # One server serializes the items on the slot lock, so the sibling + # may observe cancellation at the slot or inside its call — record + # both by wrapping the step (event_fields carries the item_key). + original_step = engine._run_mcp_step + + async def recording_step( + agent: AgentDef, agent_context: Any, *, event_fields: Any = None + ) -> Any: + try: + return await original_step(agent, agent_context, event_fields=event_fields) + except asyncio.CancelledError: + if event_fields and event_fields.get("item_key") == "1": + order.append("sibling-cancelled") + raise + + engine._run_mcp_step = recording_step # type: ignore[method-assign] + + async def item_call(_server: str, _tool: str, arguments: dict[str, Any]) -> dict[str, Any]: + if arguments["q"] == "a": + raise asyncio.CancelledError() + await asyncio.Event().wait() # blocks until cancelled + raise AssertionError("unreachable") # pragma: no cover + + patcher = _patch_manager(call=item_call) + try: + with pytest.raises(asyncio.CancelledError): + await engine.run({"items": ["a", "b"]}) + finally: + patcher.stop() + + assert order == ["sibling-cancelled", "pool-close"] + assert not any(ev.type == "workflow_failed" for ev in received) + + @pytest.mark.asyncio + async def test_repeated_cancellation_still_drains_item_cleanup(self) -> None: + # Requirement (for_each): same invariant as the parallel variant — a + # second cancel() arriving while the fail-fast drain is in flight + # must not abandon the drain; item "a"'s cancellation cleanup (which + # awaits) completes before the pool close in run()'s finally, and + # the propagated exception is the original CancelledError. + engine = _make_engine(self._config(max_concurrent=2)) + received = _collect_events(engine) + + order: list[str] = [] + original_close = engine._close_mcp_step_managers + + async def recording_close() -> None: + order.append("pool-close") + await original_close() + + engine._close_mcp_step_managers = recording_close # type: ignore[method-assign] + + entered = asyncio.Event() + + async def item_call(_server: str, _tool: str, arguments: dict[str, Any]) -> dict[str, Any]: + if arguments["q"] == "a": + entered.set() + try: + await asyncio.Event().wait() # blocks until cancelled + except asyncio.CancelledError: + await asyncio.sleep(0.05) # cancellation cleanup that awaits + order.append("sibling-cleanup-done") + raise + await asyncio.Event().wait() # item "b" parked on the slot: cancelled there + raise AssertionError("unreachable") # pragma: no cover + + run_task = asyncio.ensure_future(engine.run({"items": ["a", "b"]})) + patcher = _patch_manager(call=item_call) + try: + await asyncio.wait_for(entered.wait(), timeout=5) + run_task.cancel() + # Let the first cancellation reach the batch gather and the drain + # start (item "a" is now inside its 0.05s cleanup), then cancel + # again — this second request must land on the shield, not the + # drain. + await asyncio.sleep(0.01) + run_task.cancel() + with pytest.raises(asyncio.CancelledError): + await run_task + finally: + patcher.stop() + + assert order == ["sibling-cleanup-done", "pool-close"] + assert not any(ev.type == "workflow_failed" for ev in received) + + @pytest.mark.asyncio + async def test_output_schema_mismatch_in_item_leaks_no_values(self) -> None: + # Requirement: an output: schema mismatch on a for_each mcp item wraps + # redacted — the canary result value must appear in neither + # for_each_item_failed nor workflow_failed payloads, nor the raised + # error, and the mcp_failed payload stays redacted too. + canary = "SECRET_CANARY_9f13" + config = self._config() + config.for_each[0].agent.output = {"answer": OutputField(type="number")} + engine = _make_engine(config) + received = _collect_events(engine) + + def _value_envelope(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": "ok", "truncated": False}], + "structured": {"answer": canary}, + "is_error": False, + } + + patcher = _patch_manager(call=_value_envelope) + try: + with pytest.raises(ExecutionError) as exc_info: + await engine.run({"items": ["only"]}) + finally: + patcher.stop() + + assert canary not in str(exc_info.value) + mcp_failed = [ev for ev in received if ev.type == "mcp_failed"] + assert len(mcp_failed) == 1 + assert canary not in json.dumps(mcp_failed[0].data) + item_failed = [ev for ev in received if ev.type == "for_each_item_failed"] + assert len(item_failed) == 1 + assert canary not in json.dumps(item_failed[0].data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + + @pytest.mark.asyncio + async def test_templated_working_dir_from_item_leaks_no_values(self) -> None: + # Requirement: when runtime.working_dir renders from the LOOP + # VARIABLE ("{{ item }}"), the not-a-directory check must not leak + # the item's value or the raw template — the for_each_item_failed + # and workflow_failed payloads stay value-free. The item value is a + # relative path segment, so the rendered cwd cannot exist. + canary = "SECRET_CANARY_9f13" + config = self._config() + config.workflow.runtime.working_dir = "{{ item }}" + engine = _make_engine(config) + received = _collect_events(engine) + + patcher = _patch_manager() + try: + with pytest.raises(ExecutionError) as exc_info: + await engine.run({"items": [canary]}) + finally: + patcher.stop() + + assert "does not exist or is not a directory" in str(exc_info.value) + assert canary not in str(exc_info.value) + assert "{{ item }}" not in str(exc_info.value) + mcp_failed = [ev for ev in received if ev.type == "mcp_failed"] + assert len(mcp_failed) == 1 + assert canary not in json.dumps(mcp_failed[0].data) + assert "{{ item }}" not in json.dumps(mcp_failed[0].data) + item_failed = [ev for ev in received if ev.type == "for_each_item_failed"] + assert len(item_failed) == 1 + assert canary not in json.dumps(item_failed[0].data) + assert "{{ item }}" not in json.dumps(item_failed[0].data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + assert "{{ item }}" not in json.dumps(wf_failed[0].data) + + @pytest.mark.asyncio + async def test_is_error_item_is_a_successful_item_under_fail_fast(self) -> None: + # Requirement (explicit): is_error=true on an item is DATA for + # routing, not an exception — fail_fast is NOT triggered, no + # for_each_item_failed / workflow_failed is emitted, and the group + # completes exactly as on a successful call. + engine = _make_engine(self._config()) + received = _collect_events(engine) + + patcher = _patch_manager(call=lambda *_a, **_k: _envelope(is_error=True, answer=7)) + try: + result = await engine.run({"items": ["only"]}) + finally: + patcher.stop() + + assert result == {"count": 1} + assert not any(ev.type == "for_each_item_failed" for ev in received) + assert not any(ev.type == "workflow_failed" for ev in received) + completed = [ev for ev in received if ev.type == "for_each_item_completed"] + assert len(completed) == 1 + assert completed[0].data["item_key"] == "0" + stored = engine.context.agent_outputs["loop"]["outputs"][0] + assert stored["is_error"] is True + assert stored["answer"] == 7 diff --git a/tests/test_engine/test_mcp_step_pool.py b/tests/test_engine/test_mcp_step_pool.py new file mode 100644 index 00000000..1c211bfe --- /dev/null +++ b/tests/test_engine/test_mcp_step_pool.py @@ -0,0 +1,440 @@ +"""Tests for the engine-owned MCPManager pool backing `type: mcp` steps. + +Covers: +- Lazy connect happens once and the manager is reused for repeated calls +- connect_server raising propagates, leaves no half-open manager in the pool, + and the next call re-attempts the connect +- Two servers connect concurrently (the pool guard never spans I/O) +- run()/resume() finally blocks close all pooled managers and clear the pool +- The per-server slot lock is a stable object per server name and distinct + across server names + +All MCP interaction is mocked — no real MCP servers are spawned. +""" + +from __future__ import annotations + +import asyncio +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from conductor.config.schema import ( + AgentDef, + ContextConfig, + LimitsConfig, + MCPServerDef, + RouteDef, + RuntimeConfig, + WorkflowConfig, + WorkflowDef, +) +from conductor.engine.workflow import _MCP_STEP_POOL_MAX, WorkflowEngine +from conductor.exceptions import ExecutionError + + +def _make_engine(mcp_servers: dict[str, MCPServerDef] | None = None) -> WorkflowEngine: + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-pool", + entry_point="start", + runtime=RuntimeConfig( + provider="copilot", + mcp_servers=mcp_servers or {}, + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="start", + prompt="start", + output={"done": {"type": "boolean"}}, + routes=[RouteDef(to="$end")], + ) + ], + ) + return WorkflowEngine(config, MagicMock()) + + +def _patch_manager_class() -> Any: + """Patch MCPManager where the engine lazily imports it.""" + return patch("conductor.mcp.manager.MCPManager") + + +def _manager_factory(**_kwargs: Any) -> MagicMock: + """Build a distinct fake manager per MCPManager construction. + + ``manager_cls.return_value`` would hand every pool key the same instance, + proving nothing about distinctness — each construction gets its own. + """ + manager = MagicMock() + manager.connect_server = AsyncMock(return_value=[]) + manager.close = AsyncMock() + return manager + + +class TestLazyConnectAndReuse: + @pytest.mark.asyncio + async def test_connect_once_manager_reused(self) -> None: + # Requirement: the first call connects lazily; repeated calls for the + # same (server, cwd) key return the pooled manager without reconnecting. + engine = _make_engine({"srv": MCPServerDef(type="stdio", command="npx")}) + with _patch_manager_class() as manager_cls: + manager = manager_cls.return_value + manager.connect_server = AsyncMock(return_value=[]) + async with await engine._mcp_step_slot("srv"): + first = await engine._get_mcp_step_manager("srv", "/tmp/wd") + async with await engine._mcp_step_slot("srv"): + second = await engine._get_mcp_step_manager("srv", "/tmp/wd") + assert first is second + manager.connect_server.assert_awaited_once() + assert engine._mcp_step_managers == {("srv", "/tmp/wd"): manager} + + @pytest.mark.asyncio + async def test_connect_failure_propagates_and_pool_stays_empty(self) -> None: + # Requirement: a connect_server failure propagates, leaves no half-open + # manager in the pool, and the next call re-attempts the connect. + engine = _make_engine({"srv": MCPServerDef(type="stdio", command="npx")}) + with _patch_manager_class() as manager_cls: + manager = manager_cls.return_value + manager.connect_server = AsyncMock(side_effect=RuntimeError("spawn failed")) + with pytest.raises(RuntimeError, match="spawn failed"): + async with await engine._mcp_step_slot("srv"): + await engine._get_mcp_step_manager("srv", "/tmp/wd") + assert engine._mcp_step_managers == {} + with pytest.raises(RuntimeError, match="spawn failed"): + async with await engine._mcp_step_slot("srv"): + await engine._get_mcp_step_manager("srv", "/tmp/wd") + assert manager.connect_server.await_count == 2 + + @pytest.mark.asyncio + async def test_different_cwds_get_distinct_managers(self) -> None: + # Requirement: the pool key is (server_name, resolved_cwd) — a for_each + # whose runtime.working_dir renders differently per item must not reuse + # the first item's server process for the rest. Each connect must + # return a DISTINCT manager instance, and a repeated key must reuse + # its own instance without reconnecting. + engine = _make_engine({"srv": MCPServerDef(type="stdio", command="npx")}) + with _patch_manager_class() as manager_cls: + manager_cls.side_effect = _manager_factory + async with await engine._mcp_step_slot("srv"): + a1 = await engine._get_mcp_step_manager("srv", "/tmp/a") + async with await engine._mcp_step_slot("srv"): + b = await engine._get_mcp_step_manager("srv", "/tmp/b") + async with await engine._mcp_step_slot("srv"): + a2 = await engine._get_mcp_step_manager("srv", "/tmp/a") + assert a1 is not b + assert a1 is a2 + assert manager_cls.call_count == 2 + assert a1.connect_server.await_count == 1 + assert b.connect_server.await_count == 1 + assert set(engine._mcp_step_managers) == {("srv", "/tmp/a"), ("srv", "/tmp/b")} + assert engine._mcp_step_managers[("srv", "/tmp/a")] is a1 + assert engine._mcp_step_managers[("srv", "/tmp/b")] is b + + +class TestConcurrentServers: + @pytest.mark.asyncio + async def test_two_servers_connect_concurrently(self) -> None: + # Requirement: the pool guard only covers lock-dict mutation, never + # I/O — two servers' lazy connects must overlap, not serialize. Each + # connect waits for the other's start event; under serialization the + # first connect would block until the wait_for deadline. + engine = _make_engine( + { + "one": MCPServerDef(type="stdio", command="npx"), + "two": MCPServerDef(type="stdio", command="npx"), + } + ) + started: dict[str, asyncio.Event] = {"one": asyncio.Event(), "two": asyncio.Event()} + + async def fake_connect(name: str, **_kwargs: Any) -> list[dict[str, Any]]: + started[name].set() + await asyncio.wait_for(started[{"one": "two", "two": "one"}[name]].wait(), timeout=5) + return [] + + with _patch_manager_class() as manager_cls: + manager = manager_cls.return_value + manager.connect_server = AsyncMock(side_effect=fake_connect) + + async def acquire(server: str) -> None: + async with await engine._mcp_step_slot(server): + await engine._get_mcp_step_manager(server, "/tmp/wd") + + await asyncio.wait_for(asyncio.gather(acquire("one"), acquire("two")), timeout=10) + assert set(engine._mcp_step_managers) == {("one", "/tmp/wd"), ("two", "/tmp/wd")} + + +class TestSlotLocks: + @pytest.mark.asyncio + async def test_same_lock_per_server_distinct_across_servers(self) -> None: + # Requirement: _mcp_step_slot returns one stable lock object per server + # name; different servers get different locks (per-server serialization, + # cross-server concurrency). + engine = _make_engine() + lock_a1 = await engine._mcp_step_slot("a") + lock_a2 = await engine._mcp_step_slot("a") + lock_b = await engine._mcp_step_slot("b") + assert lock_a1 is lock_a2 + assert lock_a1 is not lock_b + + +class TestPoolBound: + async def _fill_pool(self, engine: WorkflowEngine, *, locked: bool) -> list[MagicMock]: + managers = [] + for i in range(_MCP_STEP_POOL_MAX): + manager = MagicMock() + manager.close = AsyncMock() + engine._mcp_step_managers[(f"srv{i}", f"/tmp/{i}")] = manager + engine._mcp_step_locks[f"srv{i}"] = asyncio.Lock() + managers.append(manager) + if locked: + for lock in engine._mcp_step_locks.values(): + await lock.acquire() + return managers + + @pytest.mark.asyncio + async def test_pool_cap_evicts_oldest_idle_entry(self) -> None: + # Requirement: when the pool is at the cap and a new key needs + # connecting, the oldest entry whose per-server slot lock is free is + # evicted (closed best-effort) — the pool never grows past the cap. + engine = _make_engine({"srv": MCPServerDef(type="stdio", command="npx")}) + managers = await self._fill_pool(engine, locked=False) + + with _patch_manager_class() as manager_cls: + manager_cls.side_effect = _manager_factory + async with await engine._mcp_step_slot("srv"): + fresh = await engine._get_mcp_step_manager("srv", "/tmp/new") + + # Oldest (first-inserted) entry was evicted and closed; the new key + # took its place; every other entry is untouched. + assert managers[0].close.await_count == 1 + for manager in managers[1:]: + manager.close.assert_not_called() + assert ("srv0", "/tmp/0") not in engine._mcp_step_managers + assert engine._mcp_step_managers[("srv", "/tmp/new")] is fresh + assert len(engine._mcp_step_managers) == _MCP_STEP_POOL_MAX + + @pytest.mark.asyncio + async def test_pool_cap_overflow_allowed_when_every_entry_locked(self) -> None: + # Requirement: eviction must never close a manager mid-call — when + # every entry's per-server slot lock is held, the new connect is + # allowed to overflow the cap instead of blocking or killing a + # live call. + engine = _make_engine({"srv": MCPServerDef(type="stdio", command="npx")}) + managers = await self._fill_pool(engine, locked=True) + + with _patch_manager_class() as manager_cls: + manager_cls.side_effect = _manager_factory + fresh = await engine._get_mcp_step_manager("srv", "/tmp/overflow") + + assert len(engine._mcp_step_managers) == _MCP_STEP_POOL_MAX + 1 + assert engine._mcp_step_managers[("srv", "/tmp/overflow")] is fresh + for manager in managers: + manager.close.assert_not_called() + + @pytest.mark.asyncio + async def test_one_server_many_cwds_stays_at_cap_through_slot_path(self) -> None: + # Requirement (regression): the per-server slot lock is held across + # _get_mcp_step_manager, so every entry of the connecting server + # reads as "locked" to the old eviction check — one server with many + # cwds (a for_each over templated working_dirs) bypassed the cap and + # grew unbounded. Entries of the CURRENT server must be evictable; + # 20 sequential slot-locked connects for one server keep the pool at + # the cap, closing the oldest manager each time. + engine = _make_engine({"srv": MCPServerDef(type="stdio", command="npx")}) + managers: list[MagicMock] = [] + + def tracking_factory(**_kwargs: Any) -> MagicMock: + manager = _manager_factory(**_kwargs) + managers.append(manager) + return manager + + total = _MCP_STEP_POOL_MAX + 4 + with _patch_manager_class() as manager_cls: + manager_cls.side_effect = tracking_factory + for i in range(total): + async with await engine._mcp_step_slot("srv"): + await engine._get_mcp_step_manager("srv", f"/tmp/wd{i}") + + assert len(engine._mcp_step_managers) == _MCP_STEP_POOL_MAX + # The oldest (total - cap) managers were evicted and closed, in + # insertion order; the surviving entries are the newest ones. + evicted = managers[: total - _MCP_STEP_POOL_MAX] + survivors = managers[total - _MCP_STEP_POOL_MAX :] + for manager in evicted: + manager.close.assert_awaited_once() + for manager in survivors: + manager.close.assert_not_called() + assert set(engine._mcp_step_managers) == { + ("srv", f"/tmp/wd{i}") for i in range(total - _MCP_STEP_POOL_MAX, total) + } + + @pytest.mark.asyncio + async def test_concurrent_first_connects_reserve_capacity(self) -> None: + # Requirement: admission reserves a slot for an in-flight connect — + # with the pool one below the cap, two concurrent first-time + # connects to DISTINCT servers must not both pass a size-only check + # (which would leave cap+1 managers cached and nothing evicted); the + # second evicts an idle entry and the pool finishes AT the cap. + engine = _make_engine( + { + "srvA": MCPServerDef(type="stdio", command="npx"), + "srvB": MCPServerDef(type="stdio", command="npx"), + } + ) + prefilled: list[MagicMock] = [] + for i in range(_MCP_STEP_POOL_MAX - 1): + manager = MagicMock() + manager.close = AsyncMock() + engine._mcp_step_managers[(f"old{i}", f"/tmp/{i}")] = manager + engine._mcp_step_locks[f"old{i}"] = asyncio.Lock() + prefilled.append(manager) + + started = 0 + both_started = asyncio.Event() + + async def gated_connect(**_kwargs: Any) -> list[dict[str, Any]]: + # Both connects must be genuinely in flight before either + # returns, or the test proves nothing about the admission race. + nonlocal started + started += 1 + if started == 2: + both_started.set() + await asyncio.wait_for(both_started.wait(), timeout=5) + return [] + + def factory(**_kwargs: Any) -> MagicMock: + manager = _manager_factory() + manager.connect_server = AsyncMock(side_effect=gated_connect) + return manager + + async def get(server: str) -> Any: + async with await engine._mcp_step_slot(server): + return await engine._get_mcp_step_manager(server, "/tmp/new") + + with _patch_manager_class() as manager_cls: + manager_cls.side_effect = factory + first, second = await asyncio.gather(get("srvA"), get("srvB")) + + assert first is not second + # One prefilled entry was evicted to make room; the pool ends exactly + # at the cap (cap-1 prefilled, one evicted, two new = cap). + assert sum(m.close.await_count for m in prefilled) == 1 + assert len(engine._mcp_step_managers) == _MCP_STEP_POOL_MAX + assert engine._mcp_step_pending == 0 + + @pytest.mark.asyncio + async def test_eviction_close_reraises_cancellation(self) -> None: + # Requirement: MCPManager.close() deliberately absorbs CancelledError + # while draining connection teardown — awaited directly during + # eviction, that would swallow the workflow's cancellation and let a + # NEW tool call start after it. The eviction close runs shielded, the + # close still completes, and CancelledError is re-raised BEFORE any + # new connect happens. + engine = _make_engine({"srv": MCPServerDef(type="stdio", command="npx")}) + managers = await self._fill_pool(engine, locked=False) + + close_gate = asyncio.Event() + + async def blocking_close() -> None: + await asyncio.wait_for(close_gate.wait(), timeout=5) + + managers[0].close = AsyncMock(side_effect=blocking_close) + + with _patch_manager_class() as manager_cls: + manager_cls.side_effect = _manager_factory + + async def connect_and_get() -> Any: + async with await engine._mcp_step_slot("srv"): + return await engine._get_mcp_step_manager("srv", "/tmp/new") + + task = asyncio.create_task(connect_and_get()) + await asyncio.sleep(0.05) # let it reach the eviction close + task.cancel() + await asyncio.sleep(0.05) + # The close is still draining: cancellation was absorbed by the + # manager's close, not lost — the eviction has not returned yet. + assert not task.done() + close_gate.set() + with pytest.raises(asyncio.CancelledError): + await task + + # The evicted manager finished closing; the new connect never ran. + managers[0].close.assert_awaited_once() + assert ("srv", "/tmp/new") not in engine._mcp_step_managers + assert engine._mcp_step_pending == 0 + + @pytest.mark.asyncio + async def test_close_clears_locks_even_when_pool_is_empty(self) -> None: + # Requirement: cleanup clears BOTH dicts unconditionally — a failed + # connect leaves slot locks behind without pooling any manager, and + # the old early return on an empty pool would have leaked them. + engine = _make_engine() + engine._mcp_step_locks = {"srv": asyncio.Lock()} + + await engine._close_mcp_step_managers() + + assert engine._mcp_step_managers == {} + assert engine._mcp_step_locks == {} + + +class TestCleanup: + @pytest.mark.asyncio + async def test_close_clears_pool_and_swallows_failures(self) -> None: + # Requirement: cleanup closes every pooled manager best-effort (one + # failing close does not prevent the others) and clears the pool. + engine = _make_engine() + good = MagicMock() + good.close = AsyncMock() + bad = MagicMock() + bad.close = AsyncMock(side_effect=RuntimeError("close failed")) + engine._mcp_step_managers = {("good", "/tmp"): good, ("bad", "/tmp"): bad} + engine._mcp_step_locks = {"good": asyncio.Lock()} + + await engine._close_mcp_step_managers() + + good.close.assert_awaited_once() + bad.close.assert_awaited_once() + assert engine._mcp_step_managers == {} + assert engine._mcp_step_locks == {} + + @pytest.mark.asyncio + async def test_run_finally_closes_pooled_managers(self) -> None: + # Requirement: run()'s finally block shuts the pool down even when the + # loop body raised — a run that fails mid-step must not leak the + # server process. + engine = _make_engine() + manager = MagicMock() + manager.close = AsyncMock() + engine._mcp_step_managers = {("srv", "/tmp"): manager} + + async def failing_loop(_entry: str) -> dict[str, Any]: + raise ExecutionError("boom") + + engine._execute_loop = failing_loop # type: ignore[method-assign] + with pytest.raises(ExecutionError, match="boom"): + await engine.run({}) + + manager.close.assert_awaited_once() + assert engine._mcp_step_managers == {} + + @pytest.mark.asyncio + async def test_resume_finally_closes_pooled_managers(self) -> None: + # Requirement: resume()'s finally block performs the same cleanup — + # run/resume parity for the pool lifecycle. + engine = _make_engine() + manager = MagicMock() + manager.close = AsyncMock() + engine._mcp_step_managers = {("srv", "/tmp"): manager} + + async def ok_loop(_entry: str) -> dict[str, Any]: + return {} + + engine._execute_loop = ok_loop # type: ignore[method-assign] + await engine.resume("start") + + manager.close.assert_awaited_once() + assert engine._mcp_step_managers == {} diff --git a/tests/test_engine/test_mcp_step_workflow.py b/tests/test_engine/test_mcp_step_workflow.py new file mode 100644 index 00000000..c899a148 --- /dev/null +++ b/tests/test_engine/test_mcp_step_workflow.py @@ -0,0 +1,978 @@ +"""Integration tests for `type: mcp` steps in WorkflowEngine. + +Covers: +- A workflow of ONLY mcp steps completes without the LLM provider ever + being called +- The result envelope round-trips through ``context.to_dict()`` JSON + serialization (checkpoint parity) +- set -> mcp -> route on ``output.is_error`` works for both outcomes +- ``mcp_started`` / ``mcp_completed`` / ``mcp_failed`` events carry no + argument or result values +- An ``output:`` schema mismatch fails the workflow via a single redacted + ``mcp_failed`` +- An unknown server fails at runtime naming the available servers (the + static validator is never called by ``conductor run``) +- A templated runtime ``working_dir`` rendering to a nonexistent directory + fails redacted (the rendered path and template stay in the debug log only) +- A value-bearing ``BaseException`` (e.g. ``SystemExit``) from the manager + wraps into the generic redacted failure; ``CancelledError`` re-raises + untouched with no ``mcp_failed`` +- With ``workflow.context.mode: explicit``, mcp ``arguments`` can reference + ``workflow.input.*`` (always available to local-render step types) and + prior-step outputs declared via ``input:`` + +All MCP interaction is mocked — no real MCP servers are spawned. The mock +pattern mirrors ``tests/test_engine/test_mcp_step_pool.py``: ``MCPManager`` +is patched where the engine lazily imports it, and the real +``McpStepExecutor`` runs against the mock manager. +""" + +from __future__ import annotations + +import asyncio +import json +import re +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from conductor.config.schema import ( + AgentDef, + ContextConfig, + LimitsConfig, + MCPServerDef, + OutputField, + RouteDef, + RuntimeConfig, + WorkflowConfig, + WorkflowDef, +) +from conductor.engine.context import WorkflowContext +from conductor.engine.workflow import WorkflowEngine +from conductor.events import WorkflowEvent, WorkflowEventEmitter +from conductor.exceptions import ExecutionError, InterruptError + +_SECRET_ARG = "s3cr3t-token-value" +_SECRET_RESULT = "classified-result-body" + + +def _make_engine(config: WorkflowConfig) -> WorkflowEngine: + return WorkflowEngine(config, MagicMock()) + + +def _collect_events(engine: WorkflowEngine) -> list[WorkflowEvent]: + emitter = WorkflowEventEmitter() + received: list[WorkflowEvent] = [] + emitter.subscribe(received.append) + engine._event_emitter = emitter + return received + + +def _envelope(is_error: bool = False) -> dict[str, Any]: + """A raw manager-shaped envelope (before the executor's structured merge).""" + return { + "content": [ + { + "type": "text", + "text": _SECRET_RESULT, + "truncated": False, + } + ], + "structured": {"answer": 42}, + "is_error": is_error, + } + + +def _patch_manager(envelope: Any = None) -> Any: + """Patch MCPManager where the engine lazily imports it. + + The fake manager advertises one tool ``echo``. ``envelope`` is either a + dict returned from every ``call_tool_structured`` or a callable used as + the AsyncMock side_effect (for failure paths). + """ + patcher = patch("conductor.mcp.manager.MCPManager") + manager_cls = patcher.start() + manager = manager_cls.return_value + manager.connect_server = AsyncMock(return_value=[]) + manager.close = AsyncMock(return_value=None) + manager.get_server_tools = MagicMock( + return_value=[{"name": "srv__echo", "original_name": "echo"}] + ) + if callable(envelope): + manager.call_tool_structured = AsyncMock(side_effect=envelope) + else: + manager.call_tool_structured = AsyncMock(return_value=envelope or _envelope()) + return patcher + + +def _mcp_workflow(*, arguments: dict[str, Any] | None = None) -> WorkflowConfig: + return WorkflowConfig( + workflow=WorkflowDef( + name="mcp-only", + entry_point="call", + runtime=RuntimeConfig( + provider="copilot", + mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}, + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="call", + type="mcp", + server="srv", + tool="echo", + arguments=arguments or {"q": "hello"}, + routes=[RouteDef(to="$end")], + ), + ], + output={"answer": "{{ call.output.answer }}"}, + ) + + +class TestMcpOnlyWorkflow: + @pytest.mark.asyncio + async def test_mcp_only_workflow_completes_without_llm(self) -> None: + # Requirement: a workflow of ONLY mcp steps completes end-to-end and + # never touches the LLM provider — mcp steps are provider-free. + provider = MagicMock() + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-chain", + entry_point="first", + runtime=RuntimeConfig( + provider="copilot", + mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}, + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="first", + type="mcp", + server="srv", + tool="echo", + arguments={"q": "hello"}, + routes=[RouteDef(to="second")], + ), + AgentDef( + name="second", + type="mcp", + server="srv", + tool="echo", + arguments={"q": "follow-up-{{ first.output.answer }}"}, + routes=[RouteDef(to="$end")], + ), + ], + output={"answer": "{{ second.output.answer }}"}, + ) + patcher = _patch_manager() + try: + engine = WorkflowEngine(config, provider) + result = await engine.run({}) + finally: + patcher.stop() + + assert result == {"answer": 42} + provider.execute.assert_not_called() + # Both steps executed and the second saw the first's merged key. + assert engine.context.agent_outputs["first"]["answer"] == 42 + assert engine.context.agent_outputs["second"]["answer"] == 42 + + @pytest.mark.asyncio + async def test_context_round_trips_through_json(self) -> None: + # Requirement: the stored mcp envelope is JSON-safe — a checkpoint + # save/load (context.to_dict -> json.dumps -> from_dict) preserves it. + config = _mcp_workflow() + patcher = _patch_manager() + try: + engine = _make_engine(config) + await engine.run({}) + finally: + patcher.stop() + + snapshot = engine.context.to_dict() + rendered = json.dumps(snapshot) + restored = WorkflowContext.from_dict(json.loads(rendered)) + stored = restored.agent_outputs["call"] + assert stored["is_error"] is False + assert stored["answer"] == 42 # merged structured key survives + assert stored["content"][0]["text"] == _SECRET_RESULT + + +class TestMcpRouting: + @pytest.mark.asyncio + async def test_route_on_is_error_branches_both_ways(self) -> None: + # Requirement: set -> mcp -> route on output.is_error completes and + # picks the right branch for both is_error=true and is_error=false. + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-route", + entry_point="flag", + runtime=RuntimeConfig( + provider="copilot", + mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}, + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="flag", + type="set", + values={"q": "{{ workflow.input.q }}"}, + routes=[RouteDef(to="call")], + ), + AgentDef( + name="call", + type="mcp", + server="srv", + tool="echo", + arguments={"q": "{{ flag.output.q }}"}, + routes=[ + RouteDef(to="on_error", when="{{ output.is_error }}"), + RouteDef(to="on_ok"), + ], + ), + AgentDef( + name="on_error", + type="set", + value="error-path", + routes=[RouteDef(to="$end")], + ), + AgentDef( + name="on_ok", + type="set", + value="ok-path", + routes=[RouteDef(to="$end")], + ), + ], + output={ + "path": ( + "{% if on_error is defined %}{{ on_error.output }}" + "{% else %}{{ on_ok.output }}{% endif %}" + ) + }, + ) + + patcher = _patch_manager(_envelope(is_error=False)) + try: + result_ok = await _make_engine(config).run({"q": "hi"}) + finally: + patcher.stop() + + patcher = _patch_manager(_envelope(is_error=True)) + try: + result_err = await _make_engine(config).run({"q": "hi"}) + finally: + patcher.stop() + + assert result_ok == {"path": "ok-path"} + assert result_err == {"path": "error-path"} + + +class TestMcpEventPayloads: + @pytest.mark.asyncio + async def test_events_carry_no_argument_or_result_values(self) -> None: + # Requirement: no mcp_* event payload may contain argument values or + # result values — only server/tool/argument_keys/elapsed/is_error/ + # result_bytes/truncated/spill_path (failed: error_type/message). + config = _mcp_workflow(arguments={"token": _SECRET_ARG, "q": "hello"}) + engine = _make_engine(config) + received = _collect_events(engine) + + patcher = _patch_manager() + try: + await engine.run({}) + finally: + patcher.stop() + + mcp_events = [ev for ev in received if ev.type.startswith("mcp_")] + assert {ev.type for ev in mcp_events} == {"mcp_started", "mcp_completed"} + + started = next(ev for ev in mcp_events if ev.type == "mcp_started") + # Argument VALUES stay out; only key names are listed. + assert started.data["argument_keys"] == ["q", "token"] + assert _SECRET_ARG not in json.dumps(started.data) + + completed = next(ev for ev in mcp_events if ev.type == "mcp_completed") + assert completed.data["server"] == "srv" + assert completed.data["tool"] == "echo" + assert completed.data["is_error"] is False + assert completed.data["truncated"] is False + assert completed.data["result_bytes"] > 0 + # The result body never appears in ANY event payload. + assert _SECRET_RESULT not in json.dumps([ev.data for ev in received]) + + @pytest.mark.asyncio + async def test_failure_event_is_redacted(self) -> None: + # Requirement: a failing mcp step emits exactly one mcp_failed whose + # message is generic (no raw exception text), raises a redacted + # ExecutionError (not the raw manager error — its text can carry + # argument/result values), and workflow_failed carries no canary + # value either. + def _boom(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + raise RuntimeError(f"call exploded with {_SECRET_ARG}") + + config = _mcp_workflow() + engine = _make_engine(config) + received = _collect_events(engine) + + patcher = _patch_manager(_boom) + try: + with pytest.raises(ExecutionError) as exc_info: + await engine.run({}) + finally: + patcher.stop() + + # The raised error is the generic redacted form, not the manager's + # raw text (which embedded the secret argument value), and it points + # at the private diagnostic file — the one place raw details land + # (`--log-file` is a console mirror, not a Python logging sink). + assert "call exploded" not in str(exc_info.value) + assert _SECRET_ARG not in str(exc_info.value) + assert "full diagnostic: " in str(exc_info.value) + + # The diagnostic sink holds the full traceback, canary included. + diag_match = re.search(r"full diagnostic: (.+)$", str(exc_info.value)) + assert diag_match is not None + diag_text = Path(diag_match.group(1)).read_text(encoding="utf-8") + assert "call exploded" in diag_text + assert _SECRET_ARG in diag_text + + failed = [ev for ev in received if ev.type == "mcp_failed"] + assert len(failed) == 1 + failed_data = failed[0].data + assert failed_data["error_type"] == "RuntimeError" + assert _SECRET_ARG not in json.dumps(failed_data) + assert _SECRET_RESULT not in json.dumps(failed_data) + assert "full diagnostic: " in failed_data["message"] + # The manager saw the call; the failure came from inside the step. + assert failed_data["server"] == "srv" + assert failed_data["tool"] == "echo" + # workflow_failed must not smuggle the raw exception text either. + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert _SECRET_ARG not in json.dumps(wf_failed[0].data) + assert "call exploded" not in json.dumps(wf_failed[0].data) + + +class TestMcpOutputSchemaValidation: + @pytest.mark.asyncio + async def test_schema_mismatch_fails_workflow_with_single_redacted_event(self) -> None: + # Requirement: an output: schema mismatch on an mcp step raises a + # REDACTED ExecutionError (not the ValidationError, whose message + # echoes the received result value) and emits exactly one redacted + # mcp_failed — the canary result scalar must appear in neither the + # raised error nor any event payload (incl. workflow_failed). + canary = "SECRET_CANARY_9f13" + config = _mcp_workflow() + config.agents[0].output = {"answer": OutputField(type="number")} + + def _value_envelope(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": "ok", "truncated": False}], + "structured": {"answer": canary}, + "is_error": False, + } + + engine = _make_engine(config) + received = _collect_events(engine) + + patcher = _patch_manager(_value_envelope) + try: + with pytest.raises(ExecutionError) as exc_info: + await engine.run({}) + finally: + patcher.stop() + + # The raised error is the generic redacted form — the schema + # ValidationError's "received: ''" text must not surface — and + # it points at the private diagnostic file holding the full details. + assert canary not in str(exc_info.value) + assert "full diagnostic: " in str(exc_info.value) + + diag_match = re.search(r"full diagnostic: (.+)$", str(exc_info.value)) + assert diag_match is not None + diag_text = Path(diag_match.group(1)).read_text(encoding="utf-8") + assert canary in diag_text + + failed = [ev for ev in received if ev.type == "mcp_failed"] + assert len(failed) == 1 + assert failed[0].data["error_type"] == "ValidationError" + assert canary not in json.dumps(failed[0].data) + # No mcp_completed on the failure path; the run itself failed too. + assert not any(ev.type == "mcp_completed" for ev in received) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + + +class TestMcpRuntimeChecks: + @pytest.mark.asyncio + async def test_unknown_server_names_available_servers(self) -> None: + # Requirement: an mcp step referencing a server absent from + # runtime.mcp_servers raises ExecutionError naming the available + # servers at runtime (conductor run never calls the validator). + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-ghost", + entry_point="call", + runtime=RuntimeConfig( + provider="copilot", + mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}, + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="call", + type="mcp", + server="ghost", + tool="echo", + routes=[RouteDef(to="$end")], + ), + ], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + with pytest.raises(ExecutionError, match="Available servers: srv"): + await engine.run({}) + + assert any(ev.type == "mcp_failed" for ev in received) + + @pytest.mark.asyncio + async def test_templated_working_dir_value_leaks_no_values(self) -> None: + # Requirement: the runtime working_dir not-a-directory check must not + # leak the Jinja-rendered path or the raw template — both are rendered + # from the execution context and can carry values. The propagated + # message is redacted; the authored name-only runtime-check messages + # (like the unknown-server one above) stay verbatim. + canary = "SECRET_CANARY_9f13" + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-cwd-leak", + entry_point="call", + runtime=RuntimeConfig( + provider="copilot", + working_dir="{{ workflow.input.secret_path }}", + mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}, + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="call", + type="mcp", + server="srv", + tool="echo", + routes=[RouteDef(to="$end")], + ), + ], + output={}, + ) + engine = _make_engine(config) + received = _collect_events(engine) + + with pytest.raises(ExecutionError) as excinfo: + await engine.run({"secret_path": f"/nonexistent/{canary}"}) + + assert "does not exist or is not a directory" in str(excinfo.value) + assert canary not in str(excinfo.value) + assert "{{ workflow.input.secret_path }}" not in str(excinfo.value) + + failed = [ev for ev in received if ev.type == "mcp_failed"] + assert len(failed) == 1 + assert canary not in json.dumps(failed[0].data) + assert "{{ workflow.input.secret_path }}" not in json.dumps(failed[0].data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + assert "{{ workflow.input.secret_path }}" not in json.dumps(wf_failed[0].data) + + @pytest.mark.asyncio + async def test_mixed_wildcard_tools_list_allows_any_tool(self) -> None: + # Requirement: the runtime allowlist check uses wildcard MEMBERSHIP, + # exactly like config/validator.py — ["*", "health"] must allow any + # tool here precisely when `conductor validate` accepts it (a + # size/exact-list rule would fail the step before it even connects). + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-wildcard", + entry_point="call", + runtime=RuntimeConfig( + provider="copilot", + mcp_servers={ + "srv": MCPServerDef(type="stdio", command="npx", tools=["*", "health"]) + }, + ), + context=ContextConfig(mode="accumulate"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="call", + type="mcp", + server="srv", + tool="echo", + routes=[RouteDef(to="$end")], + ), + ], + output={}, + ) + engine = _make_engine(config) + + patcher = _patch_manager() + try: + await engine.run({}) + finally: + patcher.stop() + + assert engine.context.agent_outputs["call"]["is_error"] is False + + +class TestMcpStepInterrupt: + """Dashboard/keyboard Stop wiring for `type: mcp` steps (main loop).""" + + def _engine_with_interrupt( + self, config: WorkflowConfig, *, web_dashboard: Any = None + ) -> tuple[WorkflowEngine, asyncio.Event]: + interrupt_event = asyncio.Event() + engine = WorkflowEngine( + config, + MagicMock(), + interrupt_event=interrupt_event, + web_dashboard=web_dashboard, + ) + return engine, interrupt_event + + @pytest.mark.asyncio + async def test_stop_during_call_pauses_and_resume_reexecutes(self) -> None: + # Requirement: a Stop landing mid-call cancels the in-flight + # invocation (never auto-replayed inside the cancelled execution), + # enters the dashboard pause flow (agent_paused), and Resume + # re-executes the step from the top — the documented at-least-once + # semantics — rather than the workflow silently continuing past the + # pause as if provider-level interruption had handled it. + from types import SimpleNamespace + + web_dashboard = SimpleNamespace( + has_connections=lambda: True, + resume_event=asyncio.Event(), + kill_event=asyncio.Event(), + disconnect_event=asyncio.Event(), + ) + config = _mcp_workflow() + engine, interrupt_event = self._engine_with_interrupt(config, web_dashboard=web_dashboard) + received = _collect_events(engine) + + calls: list[str] = [] + + async def call(_server: str, _tool: str, _arguments: dict[str, Any]) -> dict[str, Any]: + calls.append("call") + if len(calls) == 1: + # First execution: signal the Stop from inside the call, then + # block until the interrupt race cancels us. + interrupt_event.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + calls.append("cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + return _envelope() + + patcher = _patch_manager(call) + try: + + async def resume_once_paused() -> None: + for _ in range(200): + if any(ev.type == "agent_paused" for ev in received): + web_dashboard.resume_event.set() + return + await asyncio.sleep(0.01) + raise AssertionError("agent_paused never emitted") + + result, _ = await asyncio.gather(engine.run({}), resume_once_paused()) + finally: + patcher.stop() + + # The interrupted call was cancelled, then Resume re-executed the + # step: exactly one successful completion, no mcp_failed. + assert calls == ["call", "cancelled", "call"] + assert result == {"answer": 42} + assert [ev.type for ev in received].count("mcp_completed") == 1 + assert not any(ev.type == "mcp_failed" for ev in received) + assert any(ev.type == "agent_paused" for ev in received) + assert any(ev.type == "agent_resumed" for ev in received) + + @pytest.mark.asyncio + async def test_stop_during_call_kill_unwinds(self) -> None: + # Requirement: choosing Kill at the pause unwinds the workflow via + # InterruptError (stopped_by_user), never completing the step. + from types import SimpleNamespace + + web_dashboard = SimpleNamespace( + has_connections=lambda: True, + resume_event=asyncio.Event(), + kill_event=asyncio.Event(), + disconnect_event=asyncio.Event(), + ) + config = _mcp_workflow() + engine, interrupt_event = self._engine_with_interrupt(config, web_dashboard=web_dashboard) + received = _collect_events(engine) + + calls: list[str] = [] + + async def call(_server: str, _tool: str, _arguments: dict[str, Any]) -> dict[str, Any]: + calls.append("call") + interrupt_event.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + calls.append("cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + patcher = _patch_manager(call) + try: + + async def kill_once_paused() -> None: + for _ in range(200): + if any(ev.type == "agent_paused" for ev in received): + web_dashboard.kill_event.set() + return + await asyncio.sleep(0.01) + raise AssertionError("agent_paused never emitted") + + with pytest.raises(InterruptError): + await asyncio.gather(engine.run({}), kill_once_paused()) + finally: + patcher.stop() + + assert calls == ["call", "cancelled"] + assert not any(ev.type == "mcp_completed" for ev in received) + assert not any(ev.type == "mcp_failed" for ev in received) + + @pytest.mark.asyncio + async def test_stop_during_call_disconnect_parks_resumable_stop(self) -> None: + # Requirement: when every dashboard client disconnects while the + # pause is pending, the interrupted call is NOT re-executed — there + # is no one to make the resume decision, and transparently repeating + # a side-effecting call could duplicate unknown external effects. + # The run parks as a resumable stop instead: an InterruptError + # subclass (stopped_by_user on workflow_failed), no mcp_failed, no + # agent_resumed, exactly one attempted call, so `conductor resume` + # becomes the explicit at-least-once re-execution boundary. + from types import SimpleNamespace + + web_dashboard = SimpleNamespace( + has_connections=lambda: True, + resume_event=asyncio.Event(), + kill_event=asyncio.Event(), + disconnect_event=asyncio.Event(), + ) + config = _mcp_workflow() + engine, interrupt_event = self._engine_with_interrupt(config, web_dashboard=web_dashboard) + received = _collect_events(engine) + + calls: list[str] = [] + + async def call(_server: str, _tool: str, _arguments: dict[str, Any]) -> dict[str, Any]: + calls.append("call") + interrupt_event.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + calls.append("cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + patcher = _patch_manager(call) + try: + + async def disconnect_once_paused() -> None: + for _ in range(200): + if any(ev.type == "agent_paused" for ev in received): + web_dashboard.disconnect_event.set() + return + await asyncio.sleep(0.01) + raise AssertionError("agent_paused never emitted") + + with pytest.raises(InterruptError) as exc_info: + await asyncio.gather(engine.run({}), disconnect_once_paused()) + finally: + patcher.stop() + + assert "not resumed" in str(exc_info.value) + assert calls == ["call", "cancelled"] + assert not any(ev.type == "mcp_completed" for ev in received) + assert not any(ev.type == "mcp_failed" for ev in received) + assert not any(ev.type == "agent_resumed" for ev in received) + failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(failed) == 1 + assert failed[0].data["stopped_by_user"] is True + + @pytest.mark.asyncio + async def test_stop_during_call_no_clients_parks_resumable_stop(self) -> None: + # Requirement: a dashboard attached with ZERO connected clients is + # also "no one to decide", so the interrupted call is not + # auto-replayed — diverging from the LLM auto-resume, whose re-run + # only costs tokens. The run parks as a resumable stop without ever + # presenting a pause (no agent_paused / agent_resumed). + from types import SimpleNamespace + + web_dashboard = SimpleNamespace( + has_connections=lambda: False, + resume_event=asyncio.Event(), + kill_event=asyncio.Event(), + disconnect_event=asyncio.Event(), + ) + config = _mcp_workflow() + engine, interrupt_event = self._engine_with_interrupt(config, web_dashboard=web_dashboard) + received = _collect_events(engine) + + calls: list[str] = [] + + async def call(_server: str, _tool: str, _arguments: dict[str, Any]) -> dict[str, Any]: + calls.append("call") + interrupt_event.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + calls.append("cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + patcher = _patch_manager(call) + try: + with pytest.raises(InterruptError) as exc_info: + await engine.run({}) + finally: + patcher.stop() + + assert "not resumed" in str(exc_info.value) + assert calls == ["call", "cancelled"] + assert not any(ev.type == "agent_paused" for ev in received) + assert not any(ev.type == "agent_resumed" for ev in received) + assert not any(ev.type == "mcp_failed" for ev in received) + failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(failed) == 1 + assert failed[0].data["stopped_by_user"] is True + + @pytest.mark.asyncio + async def test_disconnect_park_saves_failure_checkpoint(self, tmp_path: Path) -> None: + # Requirement: the parked run is genuinely resumable — the failure + # checkpoint is written with current_agent pointing at the parked + # mcp step, so `conductor resume` re-enters exactly that step (the + # explicit at-least-once boundary), not an earlier one. + from types import SimpleNamespace + + from conductor.engine.checkpoint import CheckpointManager + + workflow_file = tmp_path / "workflow.yaml" + workflow_file.write_text("name: mcp-only\n") + + web_dashboard = SimpleNamespace( + has_connections=lambda: True, + resume_event=asyncio.Event(), + kill_event=asyncio.Event(), + disconnect_event=asyncio.Event(), + ) + interrupt_event = asyncio.Event() + provider = MagicMock() + # The failure checkpoint serializes collected provider session ids — + # a bare MagicMock return value is not JSON-serializable. + provider.get_session_ids.return_value = {} + provider.get_session_cwds.return_value = {} + engine = WorkflowEngine( + _mcp_workflow(), + provider, + interrupt_event=interrupt_event, + web_dashboard=web_dashboard, + workflow_path=workflow_file, + ) + received = _collect_events(engine) + + calls: list[str] = [] + + async def call(_server: str, _tool: str, _arguments: dict[str, Any]) -> dict[str, Any]: + calls.append("call") + interrupt_event.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + calls.append("cancelled") + raise + raise AssertionError("unreachable") # pragma: no cover + + patcher = _patch_manager(call) + try: + with patch.object(CheckpointManager, "get_checkpoints_dir", return_value=tmp_path): + + async def disconnect_once_paused() -> None: + for _ in range(200): + if any(ev.type == "agent_paused" for ev in received): + web_dashboard.disconnect_event.set() + return + await asyncio.sleep(0.01) + raise AssertionError("agent_paused never emitted") + + with pytest.raises(InterruptError): + await asyncio.gather(engine.run({}), disconnect_once_paused()) + finally: + patcher.stop() + + saved = [ev for ev in received if ev.type == "checkpoint_saved"] + assert len(saved) == 1 + checkpoint_path = engine._last_checkpoint_path + assert checkpoint_path is not None and checkpoint_path.exists() + data = json.loads(checkpoint_path.read_text()) + assert data["current_agent"] == "call" + + @pytest.mark.asyncio + async def test_call_completed_before_stop_returns_normally(self) -> None: + # Requirement: when the call has already completed by the time the + # interrupt fires, the result is returned (no spurious + # interruption); the pending Stop is consumed by the between-step + # interrupt check as on every other step type. + config = _mcp_workflow() + engine, interrupt_event = self._engine_with_interrupt(config) + _collect_events(engine) + + async def call(_server: str, _tool: str, _arguments: dict[str, Any]) -> dict[str, Any]: + return _envelope() + + patcher = _patch_manager(call) + try: + interrupt_event.set() # already pending before the step runs + # The pending flag fires the race immediately; simulate the + # dashboard-less CLI path by clearing it as the menu would. + engine._interrupt_handler = MagicMock() + engine._interrupt_handler.handle_interrupt = AsyncMock( + return_value=MagicMock(action="continue") + ) + await engine.run({}) + finally: + patcher.stop() + + assert engine.context.agent_outputs["call"]["answer"] == 42 + + @pytest.mark.asyncio + async def test_system_exit_from_manager_wraps_redacted(self) -> None: + # Requirement: a value-bearing BaseException raised from MCP + # SDK / connect / renderer code (e.g. SystemExit("secret")) must not + # bypass the redaction and reach workflow_failed via the outer + # except BaseException — it becomes a redacted step failure with + # exactly one mcp_failed, and the canary appears in no surface. + canary = "SECRET_CANARY_9f13" + engine = _make_engine(_mcp_workflow()) + received = _collect_events(engine) + + async def _raise_system_exit(*_args: Any, **_kwargs: Any) -> Any: + raise SystemExit(canary) + + patcher = _patch_manager(envelope=_raise_system_exit) + try: + with pytest.raises(ExecutionError) as exc_info: + await engine.run({}) + finally: + patcher.stop() + + assert "SystemExit" not in str(exc_info.value) + assert canary not in str(exc_info.value) + failed = [ev for ev in received if ev.type == "mcp_failed"] + assert len(failed) == 1 + assert canary not in json.dumps(failed[0].data) + wf_failed = [ev for ev in received if ev.type == "workflow_failed"] + assert len(wf_failed) == 1 + assert canary not in json.dumps(wf_failed[0].data) + + @pytest.mark.asyncio + async def test_cancelled_step_reraises_without_mcp_failed(self) -> None: + # Requirement: cancellation is not a step failure — the step re-raises + # CancelledError untouched and emits NO mcp_failed, preserving the + # engine's cancellation semantics. + engine = _make_engine(_mcp_workflow()) + received = _collect_events(engine) + + async def _raise_cancelled(*_args: Any, **_kwargs: Any) -> Any: + raise asyncio.CancelledError() + + patcher = _patch_manager(envelope=_raise_cancelled) + try: + with pytest.raises(asyncio.CancelledError): + await engine._run_mcp_step( + engine.config.agents[0], engine.context.build_for_agent("call", []) + ) + finally: + patcher.stop() + + assert not any(ev.type == "mcp_failed" for ev in received) + + +class TestMcpExplicitContextMode: + @pytest.mark.asyncio + async def test_arguments_render_workflow_inputs_and_declared_outputs(self) -> None: + # Requirement: with workflow.context.mode: explicit, the validator + # allows workflow.input.* references in mcp arguments (mirroring + # set/script/wait), so the runtime context must make them renderable + # too — a reference that passes static validation must render at + # run time. Prior-step outputs still require an explicit input: + # declaration, as for every step type. + config = WorkflowConfig( + workflow=WorkflowDef( + name="mcp-explicit", + entry_point="prep", + runtime=RuntimeConfig( + provider="copilot", + mcp_servers={"srv": MCPServerDef(type="stdio", command="npx")}, + ), + context=ContextConfig(mode="explicit"), + limits=LimitsConfig(max_iterations=10), + ), + agents=[ + AgentDef( + name="prep", + type="set", + value="from-prep", + routes=[RouteDef(to="call")], + ), + AgentDef( + name="call", + type="mcp", + server="srv", + tool="echo", + input=["prep.output"], + arguments={ + "q": "{{ workflow.input.question }}", + "prior": "{{ prep.output }}", + }, + routes=[RouteDef(to="$end")], + ), + ], + output={}, + ) + engine = _make_engine(config) + + captured: list[dict[str, Any]] = [] + + async def capture_call(_server: str, _tool: str, arguments: dict[str, Any]) -> Any: + captured.append(arguments) + return _envelope() + + patcher = _patch_manager(envelope=capture_call) + try: + await engine.run({"question": "what is python?"}) + finally: + patcher.stop() + + assert captured == [{"q": "what is python?", "prior": "from-prep"}] diff --git a/tests/test_engine/test_workflow_interrupt.py b/tests/test_engine/test_workflow_interrupt.py index ff823757..d7f0f65a 100644 --- a/tests/test_engine/test_workflow_interrupt.py +++ b/tests/test_engine/test_workflow_interrupt.py @@ -1172,3 +1172,137 @@ async def signal_then_resume() -> None: ) # Resume returned handled=True; no InterruptError raised. assert result.handled is True + + +class TestHandleWebPauseReasons: + """Pins for ``WebPauseOutcome.reason`` and the ``agent_resumed`` contract. + + Callers whose interrupted work has unknown external side effects (an + in-flight ``type: mcp`` tool call) re-execute only on an explicit resume + decision, so the outcome must distinguish Resume/guidance from a + disconnect — and a disconnect must NOT emit ``agent_resumed`` (the LLM + caller emits it only when it actually auto-resumes). + """ + + def _make_dashboard(self) -> object: + from types import SimpleNamespace + + return SimpleNamespace( + has_connections=lambda: True, + resume_event=asyncio.Event(), + kill_event=asyncio.Event(), + disconnect_event=asyncio.Event(), + ) + + def _make_engine(self, config: WorkflowConfig, dashboard: object) -> WorkflowEngine: + provider = CopilotProvider(mock_handler=lambda a, p, c: {}) + engine = WorkflowEngine( + config, + provider, + interrupt_event=asyncio.Event(), + web_dashboard=dashboard, # type: ignore[arg-type] + ) + emitter = WorkflowEventEmitter() + received: list[WorkflowEvent] = [] + emitter.subscribe(received.append) + engine._event_emitter = emitter + engine._received_for_test = received # type: ignore[attr-defined] + return engine + + @pytest.mark.asyncio + async def test_disconnect_reason_and_no_agent_resumed( + self, two_agent_config: WorkflowConfig + ) -> None: + # Requirement: a mid-pause disconnect resolves the wait with + # reason="disconnect" and emits NO agent_resumed — disconnecting is + # not a resume decision, and reporting one would be a lie on the + # mcp parking path. + from conductor.providers.base import AgentOutput + + dashboard = self._make_dashboard() + engine = self._make_engine(two_agent_config, dashboard) + partial = AgentOutput(content={"plan": "partial"}, raw_response="x", partial=True) + + async def disconnect() -> None: + await asyncio.sleep(0.05) + dashboard.disconnect_event.set() # type: ignore[attr-defined] + + outcome, _ = await asyncio.gather( + engine._handle_web_pause("planner", partial), disconnect() + ) + + assert outcome.handled is True + assert outcome.reason == "disconnect" + assert outcome.guidance == [] + resumed = [e for e in engine._received_for_test if e.type == "agent_resumed"] + assert resumed == [] + + @pytest.mark.asyncio + async def test_resume_reason_emits_agent_resumed( + self, two_agent_config: WorkflowConfig + ) -> None: + # Requirement: an explicit Resume click keeps reason="resume" and + # still emits agent_resumed — the explicit-decision path both + # callers re-execute on. + from conductor.providers.base import AgentOutput + + dashboard = self._make_dashboard() + engine = self._make_engine(two_agent_config, dashboard) + partial = AgentOutput(content={"plan": "partial"}, raw_response="x", partial=True) + + async def resume() -> None: + await asyncio.sleep(0.05) + dashboard.resume_event.set() # type: ignore[attr-defined] + + outcome, _ = await asyncio.gather(engine._handle_web_pause("planner", partial), resume()) + + assert outcome.handled is True + assert outcome.reason == "resume" + resumed = [e for e in engine._received_for_test if e.type == "agent_resumed"] + assert len(resumed) == 1 + assert resumed[0].data["with_guidance"] is False + + @pytest.mark.asyncio + async def test_resume_wins_over_simultaneous_disconnect( + self, two_agent_config: WorkflowConfig + ) -> None: + # Requirement: when a Resume click and the last client's disconnect + # complete in the SAME wait batch, the explicit decision wins — + # reason="resume" and exactly one agent_resumed. Parking a run the + # user explicitly resumed would discard their decision. + from conductor.providers.base import AgentOutput + + dashboard = self._make_dashboard() + engine = self._make_engine(two_agent_config, dashboard) + partial = AgentOutput(content={"plan": "partial"}, raw_response="x", partial=True) + + async def resume_and_disconnect() -> None: + await asyncio.sleep(0.05) + dashboard.resume_event.set() # type: ignore[attr-defined] + dashboard.disconnect_event.set() # type: ignore[attr-defined] + + outcome, _ = await asyncio.gather( + engine._handle_web_pause("planner", partial), resume_and_disconnect() + ) + + assert outcome.handled is True + assert outcome.reason == "resume" + resumed = [e for e in engine._received_for_test if e.type == "agent_resumed"] + assert len(resumed) == 1 + assert resumed[0].data["with_guidance"] is False + + @pytest.mark.asyncio + async def test_no_dashboard_is_unavailable(self, two_agent_config: WorkflowConfig) -> None: + # Requirement: without a dashboard the outcome is reason= + # "unavailable" (handled=False) so the caller falls through to the + # CLI interactive handler — an explicit decision by definition. + from conductor.providers.base import AgentOutput + + provider = CopilotProvider(mock_handler=lambda a, p, c: {}) + engine = WorkflowEngine(two_agent_config, provider, interrupt_event=asyncio.Event()) + partial = AgentOutput(content={"plan": "partial"}, raw_response="x", partial=True) + + outcome = await engine._handle_web_pause("planner", partial) + + assert outcome.handled is False + assert outcome.reason == "unavailable" diff --git a/tests/test_executor/test_mcp_step.py b/tests/test_executor/test_mcp_step.py new file mode 100644 index 00000000..326e7513 --- /dev/null +++ b/tests/test_executor/test_mcp_step.py @@ -0,0 +1,333 @@ +"""Unit tests for :mod:`conductor.executor.mcp_step`. + +Covers: +- Recursive argument rendering with set-auto coercion (whole-string templates + coerce to typed scalars, embedded templates stay strings) +- Non-string YAML-native leaves passing through unchanged +- FileString (``!file`` tag) rendering as a normal template +- Envelope merge (structured keys merged on top; envelope keys never overridden) +- Per-call timeout raising :class:`ExecutionError` +- Manager errors (unknown tool ValueError) propagating unchanged +- :func:`mcp_result_bytes` byte-exactness, including multibyte UTF-8 text +""" + +from __future__ import annotations + +import asyncio +import json +import logging +from pathlib import Path +from typing import Any + +import pytest + +from conductor.config.schema import AgentDef +from conductor.exceptions import ExecutionError +from conductor.executor.mcp_step import McpStepExecutor, mcp_result_bytes +from conductor.file_string import FileString + + +class FakeMCPManager: + """Minimal stand-in for MCPManager recording the last structured call.""" + + def __init__( + self, + envelope: dict[str, Any] | None = None, + *, + error: Exception | None = None, + delay: float = 0.0, + ) -> None: + self.envelope = envelope or {"content": [], "structured": None, "is_error": False} + self.calls: list[tuple[str, str, dict[str, Any]]] = [] + self.error = error + self.delay = delay + + async def call_tool_structured( + self, + server_name: str, + tool_name: str, + arguments: dict[str, Any], + ) -> dict[str, Any]: + """Record the call and return the canned envelope (or raise / sleep).""" + self.calls.append((server_name, tool_name, arguments)) + if self.error is not None: + raise self.error + if self.delay: + await asyncio.sleep(self.delay) + return self.envelope + + +@pytest.fixture +def executor() -> McpStepExecutor: + return McpStepExecutor() + + +def make_agent(**overrides: Any) -> AgentDef: + """Build an mcp AgentDef with sensible defaults, overridden per test.""" + kwargs: dict[str, Any] = {"name": "lookup", "type": "mcp", "server": "srv", "tool": "ping"} + kwargs.update(overrides) + return AgentDef(**kwargs) + + +class TestArgumentRendering: + """Recursive render + auto-coercion of ``arguments``.""" + + async def test_whole_string_template_coerces_to_int(self, executor: McpStepExecutor) -> None: + # Requirement: a whole-string numeric template renders to a typed int argument. + manager = FakeMCPManager() + agent = make_agent(arguments={"limit": "{{ limit }}"}) + await executor.execute(agent, {"limit": 105}, manager) # type: ignore[arg-type] + assert manager.calls[0][2] == {"limit": 105} + assert isinstance(manager.calls[0][2]["limit"], int) + + async def test_embedded_template_stays_string(self, executor: McpStepExecutor) -> None: + # Requirement: a template embedded in surrounding text must remain a string. + manager = FakeMCPManager() + agent = make_agent(arguments={"query": "pre-{{ x }}"}) + await executor.execute(agent, {"x": "fix"}, manager) # type: ignore[arg-type] + assert manager.calls[0][2] == {"query": "pre-fix"} + + async def test_boolean_template_coerces_to_bool(self, executor: McpStepExecutor) -> None: + # Requirement: a whole-string boolean template renders to a typed bool argument. + manager = FakeMCPManager() + agent = make_agent(arguments={"strict": "{{ flag }}"}) + await executor.execute(agent, {"flag": True}, manager) # type: ignore[arg-type] + assert manager.calls[0][2] == {"strict": True} + assert isinstance(manager.calls[0][2]["strict"], bool) + + async def test_nested_dict_and_list_arguments_recurse(self, executor: McpStepExecutor) -> None: + # Requirement: rendering recurses through nested dicts and lists at any depth. + manager = FakeMCPManager() + agent = make_agent( + arguments={ + "filter": {"name": "{{ name }}", "tags": ["a", "{{ tag }}"]}, + } + ) + await executor.execute(agent, {"name": "n1", "tag": "b"}, manager) # type: ignore[arg-type] + assert manager.calls[0][2] == {"filter": {"name": "n1", "tags": ["a", "b"]}} + + async def test_non_string_leaves_pass_through(self, executor: McpStepExecutor) -> None: + # Requirement: YAML-native scalars (int/float/bool/None) pass through unchanged. + manager = FakeMCPManager() + agent = make_agent(arguments={"n": 7, "f": 1.5, "b": False, "nothing": None}) + await executor.execute(agent, {}, manager) # type: ignore[arg-type] + args = manager.calls[0][2] + assert args == {"n": 7, "f": 1.5, "b": False, "nothing": None} + assert isinstance(args["n"], int) + + async def test_file_string_renders_as_template( + self, executor: McpStepExecutor, tmp_path: Path + ) -> None: + # Requirement: a FileString (!file tag) is a str subclass and renders like a + # normal template, yielding a plain string argument. + source = tmp_path / "prompt.txt" + source.write_text("Hello {{ who }}", encoding="utf-8") + manager = FakeMCPManager() + file_value = FileString("Hello {{ who }}", source_path=source) + agent = make_agent(arguments={"greeting": file_value}) + await executor.execute(agent, {"who": "world"}, manager) # type: ignore[arg-type] + assert manager.calls[0][2] == {"greeting": "Hello world"} + assert type(manager.calls[0][2]["greeting"]) is str + + async def test_empty_render_binds_empty_string_not_none( + self, executor: McpStepExecutor + ) -> None: + # Requirement: an empty/whitespace-only template render binds "" (not None), + # matching the set-step auto rule. + manager = FakeMCPManager() + agent = make_agent(arguments={"q": "{{ missing | default('') }}"}) + await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert manager.calls[0][2] == {"q": ""} + + async def test_no_arguments_sends_empty_dict(self, executor: McpStepExecutor) -> None: + # Requirement: steps without arguments call the tool with an empty dict. + manager = FakeMCPManager() + agent = make_agent(arguments=None) + await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert manager.calls[0][2] == {} + + +class TestEnvelopeMerge: + """Structured keys merged on top; envelope keys never overridden.""" + + async def test_structured_keys_merge_on_top(self, executor: McpStepExecutor) -> None: + # Requirement: dict structured content lands on top of the envelope so routes + # can address individual result fields. + manager = FakeMCPManager( + envelope={ + "content": [{"type": "text", "text": "ok"}], + "structured": {"count": 3, "items": ["a"]}, + "is_error": False, + } + ) + agent = make_agent() + result = await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert result["count"] == 3 + assert result["items"] == ["a"] + assert result["content"] == [{"type": "text", "text": "ok"}] + assert result["is_error"] is False + + async def test_envelope_key_collisions_are_dropped(self, executor: McpStepExecutor) -> None: + # Requirement: structured keys named content/structured/is_error can never + # override the envelope fields — collisions are dropped. + manager = FakeMCPManager( + envelope={ + "content": [{"type": "text", "text": "real"}], + "structured": {"content": "fake", "is_error": True, "structured": {}, "ok": 1}, + "is_error": False, + } + ) + agent = make_agent() + result = await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert result["content"] == [{"type": "text", "text": "real"}] + assert result["is_error"] is False + assert result["ok"] == 1 + assert "structured" in result # the envelope's own structured mapping survives + + async def test_shadow_collision_logged_at_debug( + self, executor: McpStepExecutor, caplog: pytest.LogCaptureFixture + ) -> None: + # Requirement: dropped envelope-key collisions are logged at debug level, + # listing the offending keys (mirrors the script-step shadow precedent). + manager = FakeMCPManager( + envelope={ + "content": [], + "structured": {"content": "fake", "is_error": True}, + "is_error": False, + } + ) + agent = make_agent() + with caplog.at_level(logging.DEBUG, logger="conductor.executor.mcp_step"): + await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert any( + "content" in record.message and "is_error" in record.message + for record in caplog.records + if record.levelno == logging.DEBUG + ) + + async def test_non_dict_structured_is_not_merged(self, executor: McpStepExecutor) -> None: + # Requirement: a None (or otherwise non-dict) structured payload leaves the + # envelope untouched. + manager = FakeMCPManager(envelope={"content": [], "structured": None, "is_error": False}) + agent = make_agent() + result = await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert result == {"content": [], "structured": None, "is_error": False} + + async def test_outputs_errors_keys_are_reserved_from_flattening( + self, executor: McpStepExecutor + ) -> None: + # Requirement: structured keys named ``outputs``/``errors`` are never + # flattened onto the envelope — WorkflowContext duck-types + # parallel/for-each group outputs by exactly those two top-level + # keys, so flattening them would misclassify this step's output as a + # group output in every context mode (and confuse for-each source + # resolution). They stay reachable under ``structured``. + manager = FakeMCPManager( + envelope={ + "content": [{"type": "text", "text": "ok"}], + "structured": {"outputs": [1, 2], "errors": [], "answer": 7}, + "is_error": False, + } + ) + agent = make_agent() + result = await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert "outputs" not in result + assert "errors" not in result + assert result["answer"] == 7 + assert result["structured"] == {"outputs": [1, 2], "errors": [], "answer": 7} + assert result["is_error"] is False + + +class TestGroupOutputMisclassification: + """A merged envelope must never read as a parallel/for-each group output.""" + + async def test_envelope_with_structured_outputs_keys_keeps_output_wrapper( + self, executor: McpStepExecutor + ) -> None: + # Requirement: stored in the workflow context, the envelope keeps its + # normal ``.output`` wrapper — ``{{ step.output.is_error }}`` works + # even when the tool's structured payload carries ``outputs`` / + # ``errors`` keys of its own. + from conductor.engine.context import WorkflowContext + + manager = FakeMCPManager( + envelope={ + "content": [{"type": "text", "text": "ok"}], + "structured": {"outputs": [1, 2], "errors": [], "answer": 7}, + "is_error": False, + } + ) + agent = make_agent() + envelope = await executor.execute(agent, {}, manager) # type: ignore[arg-type] + + context = WorkflowContext() + context.store("call", envelope) + built = context.build_for_agent("downstream", []) + assert built["call"]["output"]["is_error"] is False + assert built["call"]["output"]["answer"] == 7 + + +class TestTimeoutAndErrors: + """Timeout and error propagation contracts.""" + + async def test_timeout_raises_execution_error(self, executor: McpStepExecutor) -> None: + # Requirement: a call exceeding agent.timeout raises ExecutionError naming the + # step and the timeout. + manager = FakeMCPManager(delay=5.0) + agent = make_agent(timeout=1) + with pytest.raises(ExecutionError, match="lookup.*timed out after 1s"): + await asyncio.wait_for(executor.execute(agent, {}, manager), timeout=10) # type: ignore[arg-type] + + async def test_no_timeout_awaits_without_wait_for(self, executor: McpStepExecutor) -> None: + # Requirement: without agent.timeout the call is awaited with no wait_for wrapper. + manager = FakeMCPManager(delay=0.01) + agent = make_agent() + result = await executor.execute(agent, {}, manager) # type: ignore[arg-type] + assert result["is_error"] is False + assert manager.calls # the call went through + + async def test_manager_value_error_propagates(self, executor: McpStepExecutor) -> None: + # Requirement: the manager's ValueError (unknown server/tool) propagates + # unchanged so the engine can classify it. + manager = FakeMCPManager(error=ValueError("Unknown server: srv")) + agent = make_agent() + with pytest.raises(ValueError, match="Unknown server: srv"): + await executor.execute(agent, {}, manager) # type: ignore[arg-type] + + +class TestMcpResultBytes: + """Byte-exactness of the shared result-size contract.""" + + def test_byte_exactness_against_manual_computation(self) -> None: + # Requirement: mcp_result_bytes equals the length of the compact UTF-8 JSON + # encoding of {"content": ..., "structured": ...}. + content = [{"type": "text", "text": "hello"}] + structured = {"a": 1} + expected = len( + json.dumps( + {"content": content, "structured": structured}, + ensure_ascii=False, + separators=(",", ":"), + ).encode("utf-8") + ) + assert mcp_result_bytes(content, structured) == expected + + def test_multibyte_text_counts_utf8_bytes(self) -> None: + # Requirement: multibyte characters are measured in UTF-8 bytes, not characters + # (ensure_ascii=False keeps them as-is). + content = [{"type": "text", "text": "こんにちは"}] + measured = mcp_result_bytes(content, None) + payload = '{"content":[{"type":"text","text":"こんにちは"}],"structured":null}' + assert measured == len(payload.encode("utf-8")) + assert measured > len(payload) # 5 Japanese chars are 3 bytes each + + def test_none_structured_serializes_as_null(self) -> None: + # Requirement: a None structured payload serializes as JSON null in the + # measured payload. + assert mcp_result_bytes([], None) == len(b'{"content":[],"structured":null}') + + def test_separators_are_compact(self) -> None: + # Requirement: the measurement uses compact separators so it never depends on + # default ", " / ": " formatting. + measured = mcp_result_bytes([{"a": 1}], {"b": 2}) + assert measured == len(b'{"content":[{"a":1}],"structured":{"b":2}}') diff --git a/tests/test_fleet/test_summary.py b/tests/test_fleet/test_summary.py index 832d793b..f9f18069 100644 --- a/tests/test_fleet/test_summary.py +++ b/tests/test_fleet/test_summary.py @@ -277,11 +277,19 @@ def test_prefilter_matches_an_unfiltered_scan(self, tmp_path: Path) -> None: _event("script_completed", {"agent_name": "e"}), _event("wait_completed", {"agent_name": "f"}), _event("set_completed", {"agent_name": "g"}), + _event( + "mcp_completed", + {"agent_name": "g2", "server": "fs", "tool": "read", "result_bytes": 8}, + ), _event("subworkflow_completed", {"agent_name": "h"}), _event("questions_completed", {"agent_name": "i"}), _event("script_failed", {"agent_name": "j"}), _event("wait_failed", {"agent_name": "k"}), _event("set_failed", {"agent_name": "l"}), + _event( + "mcp_failed", + {"agent_name": "l2", "server": "fs", "tool": "read", "error_type": "Error"}, + ), _event("subworkflow_failed", {"agent_name": "m"}), _event("agent_failed", {"agent_name": "n"}), _event( @@ -617,6 +625,114 @@ def test_human_gate_step_closes_via_gate_resolved(self, tmp_path: Path) -> None: assert summary.current_step is None assert summary.status == "running" + def test_mcp_step_closes_via_mcp_completed(self, tmp_path: Path) -> None: + """An mcp step opens via the generic `agent_started` (like script/wait/set) + and must close via `mcp_completed` — `mcp_started` is NOT an opening + event, otherwise one close would leave a second open record behind.""" + path = tmp_path / "run.events.jsonl" + _write_jsonl( + path, + [ + _event("agent_started", {"agent_name": "fetch", "agent_type": "mcp"}), + _event( + "mcp_started", + { + "agent_name": "fetch", + "iteration": 1, + "server": "filesystem", + "tool": "read_file", + "argument_keys": ["path"], + }, + ), + _event( + "mcp_completed", + { + "agent_name": "fetch", + "elapsed": 0.5, + "server": "filesystem", + "tool": "read_file", + "is_error": False, + "result_bytes": 128, + "truncated": False, + }, + ), + ], + ) + record = _make_record(tmp_path, event_log_path=str(path)) + + summary = derive_run_summary(record) + + assert summary.current_step is None + assert summary.status == "running" + + def test_mcp_step_closes_via_mcp_failed(self, tmp_path: Path) -> None: + """An mcp failure must also close the open step (as a failed one), not + leave the step stuck "running" after the workflow has moved on.""" + path = tmp_path / "run.events.jsonl" + _write_jsonl( + path, + [ + _event("agent_started", {"agent_name": "fetch", "agent_type": "mcp"}), + _event( + "mcp_failed", + { + "agent_name": "fetch", + "elapsed": 0.1, + "server": "filesystem", + "tool": "read_file", + "error_type": "ConnectionError", + "message": "MCP step 'fetch' failed", + }, + ), + _event( + "workflow_failed", + {"agent_name": "fetch", "error_type": "ConnectionError"}, + ), + ], + ) + record = _make_record(tmp_path, event_log_path=str(path)) + + summary = derive_run_summary(record) + + assert summary.current_step is None + assert summary.status == "failed" + + def test_mcp_step_in_for_each_group_closes_without_residual_open_step( + self, tmp_path: Path + ) -> None: + """An mcp step inside a for_each group emits `mcp_completed` carrying + `group_name`/`item_key`; the scanner closes by `agent_name` like any + other step-close event, so no residual open step remains.""" + path = tmp_path / "run.events.jsonl" + _write_jsonl( + path, + [ + _event("for_each_started", {"group_name": "fanout"}), + _event("agent_started", {"agent_name": "fetch", "agent_type": "mcp"}), + _event( + "mcp_completed", + { + "agent_name": "fetch", + "elapsed": 0.2, + "server": "filesystem", + "tool": "read_file", + "is_error": False, + "result_bytes": 64, + "truncated": False, + "group_name": "fanout", + "item_key": "a", + }, + ), + _event("for_each_completed", {"group_name": "fanout"}), + ], + ) + record = _make_record(tmp_path, event_log_path=str(path)) + + summary = derive_run_summary(record) + + assert summary.current_step is None + assert summary.status == "running" + def test_total_elapsed_from_record_started_at(self, tmp_path: Path) -> None: path = tmp_path / "run.events.jsonl" path.write_text("") diff --git a/tests/test_mcp/test_manager.py b/tests/test_mcp/test_manager.py index 8fe89cf8..c1192439 100644 --- a/tests/test_mcp/test_manager.py +++ b/tests/test_mcp/test_manager.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio +import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager from typing import Any @@ -543,6 +544,44 @@ async def test_failed_connection_cleans_up_in_lifecycle_owner_task(self) -> None assert environment.exits == environment.entries + async def test_redacted_connection_error_logs_safe_metadata_only( + self, caplog: pytest.LogCaptureFixture + ) -> None: + # Requirement: with redact_errors=True (the deterministic `type: mcp` + # step path), a connection failure logs only the safe server name at + # ERROR — the raw exception (which can embed server-supplied stderr, + # i.e. values the step's no-values policy excludes) must not appear in + # the log record or its traceback. The raised RuntimeError still chains + # the original exception for the caller's own diagnostic sink. + async with _task_affine_manager() as (manager, environment): + environment.initialize_error = RuntimeError("server stderr: SECRET_CANARY") + + with pytest.raises(RuntimeError, match="Failed to connect"): + await manager.connect_server(name="fs", command="server", redact_errors=True) + + error_records = [r for r in caplog.records if r.levelno == logging.ERROR] + assert len(error_records) == 1 + assert error_records[0].exc_info is None + assert "SECRET_CANARY" not in caplog.text + # The chained cause survives for the caller's diagnostic sink. + assert manager.sessions == {} + + async def test_unredacted_connection_error_keeps_full_log( + self, caplog: pytest.LogCaptureFixture + ) -> None: + # Requirement: the default path (providers relying on it elsewhere) is + # unchanged — the raw exception text and traceback are logged at ERROR. + async with _task_affine_manager() as (manager, environment): + environment.initialize_error = RuntimeError("plain failure text") + + with pytest.raises(RuntimeError, match="Failed to connect"): + await manager.connect_server(name="fs", command="server") + + error_records = [r for r in caplog.records if r.levelno == logging.ERROR] + assert len(error_records) == 1 + assert "plain failure text" in caplog.text + assert error_records[0].exc_info is not None + async def test_cancelled_connection_cleans_up_in_lifecycle_owner_task(self) -> None: # Requirement: cancelling a connection cannot orphan its task-affine MCP contexts. async with _task_affine_manager() as (manager, environment): diff --git a/tests/test_mcp/test_manager_structured.py b/tests/test_mcp/test_manager_structured.py new file mode 100644 index 00000000..2dba6976 --- /dev/null +++ b/tests/test_mcp/test_manager_structured.py @@ -0,0 +1,276 @@ +"""Tests for MCPManager.call_tool_structured. + +Covers the structured envelope contract consumed by the ``type: mcp`` workflow +step (executor layer): content blocks as JSON-safe dicts, the strictly +``dict | None`` ``structured`` slot, the ``is_error`` flag, the per-result +text budget with spill-to-file, and the value-free logging contract. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from conductor.config.schema import ToolOutputConfig + + +def _make_manager(tool_output: ToolOutputConfig | None = None) -> Any: + """Build an MCPManager with a single mocked server session.""" + with patch("conductor.mcp.manager.MCP_SDK_AVAILABLE", True): + from conductor.mcp.manager import MCPManager + + manager = MCPManager(tool_output=tool_output) + manager.sessions["server"] = AsyncMock() + return manager + + +def _make_result( + content: list[Any], + structured: Any = None, + is_error: bool = False, +) -> Any: + """Build a real mcp CallToolResult (1.x field names).""" + from mcp.types import CallToolResult + + return CallToolResult(content=content, structuredContent=structured, isError=is_error) + + +def _text_block(text: str) -> Any: + """Build a real mcp TextContent block.""" + from mcp.types import TextContent + + return TextContent(type="text", text=text) + + +@pytest.mark.asyncio +async def test_envelope_shape_happy_path() -> None: + # Requirement: a successful call returns {"content", "structured", "is_error"} + # where content blocks are model_dump(mode="json") dicts, structured is the + # structuredContent payload, and is_error mirrors the result flag. + manager = _make_manager() + session = manager.sessions["server"] + session.call_tool.return_value = _make_result( + content=[_text_block("hello")], + structured={"rows": [1, 2]}, + is_error=False, + ) + + envelope = await manager.call_tool_structured("server", "my_tool", {"a": 1}) + + session.call_tool.assert_awaited_once_with("my_tool", arguments={"a": 1}) + assert envelope["content"][0]["type"] == "text" + assert envelope["content"][0]["text"] == "hello" + assert envelope["structured"] == {"rows": [1, 2]} + assert envelope["is_error"] is False + + +@pytest.mark.asyncio +async def test_is_error_true_is_passed_through() -> None: + # Requirement: the envelope's is_error flag reflects a tool-level error + # reported by the server (the call itself succeeded). + manager = _make_manager() + manager.sessions["server"].call_tool.return_value = _make_result( + content=[_text_block("bad input")], + is_error=True, + ) + + envelope = await manager.call_tool_structured("server", "my_tool", {}) + + assert envelope["is_error"] is True + assert envelope["structured"] is None + + +@pytest.mark.asyncio +async def test_call_error_becomes_chained_runtime_error() -> None: + # Requirement: errors from session.call_tool surface as a chained + # RuntimeError("MCP tool call failed: ..."), mirroring call_tool's contract. + manager = _make_manager() + session = manager.sessions["server"] + boom = ConnectionError("transport died") + session.call_tool.side_effect = boom + + with pytest.raises(RuntimeError, match="MCP tool call failed: my_tool") as exc_info: + await manager.call_tool_structured("server", "my_tool", {}) + + assert exc_info.value.__cause__ is boom + + +@pytest.mark.asyncio +async def test_unknown_server_raises_value_error() -> None: + # Requirement: calling a server the manager has no record of is a + # ValueError (the server name itself is invalid), not a call failure. + manager = _make_manager() + + with pytest.raises(ValueError, match="Unknown server: nope"): + await manager.call_tool_structured("nope", "my_tool", {}) + + +@pytest.mark.asyncio +async def test_missing_session_raises_runtime_error() -> None: + # Requirement: a known server without a live session raises RuntimeError + # ("No session for server"), matching the call_tool lookup contract. + manager = _make_manager() + manager.sessions["server"] = None + + with pytest.raises(RuntimeError, match="No session for server: server"): + await manager.call_tool_structured("server", "my_tool", {}) + + +@pytest.mark.asyncio +async def test_non_dict_structured_is_malformed_response() -> None: + # Requirement: the envelope contract for "structured" is strictly dict | None; + # any other shape is a malformed MCP response and raises RuntimeError + # instead of returning an envelope with a wrong-typed slot. + manager = _make_manager() + mock_result = MagicMock() + mock_result.content = [_text_block("ok")] + mock_result.structured_content = ["not", "a", "dict"] + mock_result.isError = False + manager.sessions["server"].call_tool.return_value = mock_result + + with pytest.raises(RuntimeError, match="malformed"): + await manager.call_tool_structured("server", "my_tool", {}) + + +@pytest.mark.asyncio +async def test_block_without_model_dump_uses_fallback_dict() -> None: + # Requirement: content blocks that are not pydantic models degrade to a + # {"type", "text": str(block)} dict instead of failing the envelope build. + + class _PlainBlock: + type = "image" + + def __str__(self) -> str: + return "" + + manager = _make_manager() + mock_result = MagicMock() + mock_result.content = [_PlainBlock()] + mock_result.structured_content = None + mock_result.structuredContent = None + mock_result.isError = False + mock_result.is_error = False + manager.sessions["server"].call_tool.return_value = mock_result + + envelope = await manager.call_tool_structured("server", "my_tool", {}) + + assert envelope["content"] == [{"type": "image", "text": ""}] + + +@pytest.mark.asyncio +async def test_text_budget_truncates_in_order_and_spills_full_text( + tmp_path: Path, +) -> None: + # Requirement: when the combined text length exceeds max_chars, blocks are + # walked in order with a shared remaining budget; every truncated block + # keeps a prefix, gets "truncated": true, and a spill_path whose file holds + # the block's FULL original text. + config = ToolOutputConfig(enabled=True, max_chars=1000, spill_to_file=True) + manager = _make_manager(tool_output=config) + first, second = "a" * 600, "b" * 600 + manager.sessions["server"].call_tool.return_value = _make_result( + content=[_text_block(first), _text_block(second)], + structured={"k": "v"}, + ) + + with patch("conductor.mcp.manager.tempfile.gettempdir", return_value=str(tmp_path)): + envelope = await manager.call_tool_structured("server", "my_tool", {}) + + blocks = envelope["content"] + # First block fits the initial budget and is untouched. + assert blocks[0]["text"] == first + assert "truncated" not in blocks[0] + # Second block is cut to the remaining 400 chars and flagged with a spill. + assert blocks[1]["text"] == "b" * 400 + assert blocks[1]["truncated"] is True + spill_file = Path(blocks[1]["spill_path"]) + assert spill_file.read_text() == second + assert spill_file.name.startswith("mcp-server-my_tool-") + + +@pytest.mark.asyncio +async def test_text_budget_not_applied_when_disabled() -> None: + # Requirement: with tool_output disabled, text blocks pass through + # untruncated regardless of size. + config = ToolOutputConfig(enabled=False, max_chars=1000, spill_to_file=True) + manager = _make_manager(tool_output=config) + full = "x" * 5000 + manager.sessions["server"].call_tool.return_value = _make_result(content=[_text_block(full)]) + + envelope = await manager.call_tool_structured("server", "my_tool", {}) + + assert envelope["content"][0]["text"] == full + assert "truncated" not in envelope["content"][0] + + +@pytest.mark.asyncio +async def test_server_supplied_truncation_fields_are_stripped() -> None: + # Requirement: ``truncated`` / ``spill_path`` on a content block are + # Conductor-local metadata — a server returning extension fields of + # those names must not have them forwarded as trusted markers (a forged + # ``spill_path`` would leak result values into ``mcp_completed`` events + # and break the frontend's str type for the field). This holds even with + # spilling disabled, so the two can never be confused. + from mcp.types import TextContent + + config = ToolOutputConfig(enabled=False) + manager = _make_manager(tool_output=config) + block = TextContent.model_construct( + type="text", + text="x", + truncated=True, + spill_path={"private_result": "value"}, + ) + manager.sessions["server"].call_tool.return_value = _make_result(content=[block]) + + envelope = await manager.call_tool_structured("server", "my_tool", {}) + + [dumped] = envelope["content"] + assert dumped["type"] == "text" + assert dumped["text"] == "x" + assert "truncated" not in dumped + assert "spill_path" not in dumped + + +@pytest.mark.asyncio +async def test_structured_is_never_truncated(tmp_path: Path) -> None: + # Requirement: the per-result text budget applies to text blocks only; + # the structured payload passes through untouched regardless of its size. + config = ToolOutputConfig(enabled=True, max_chars=1000, spill_to_file=False) + manager = _make_manager(tool_output=config) + big_structured = {"data": "y" * 5000} + manager.sessions["server"].call_tool.return_value = _make_result( + content=[_text_block("x" * 2500)], + structured=big_structured, + ) + + envelope = await manager.call_tool_structured("server", "my_tool", {}) + + assert envelope["content"][0]["truncated"] is True + assert len(envelope["content"][0]["text"]) == 1000 + assert envelope["structured"] == big_structured + + +@pytest.mark.asyncio +async def test_no_log_record_contains_argument_or_exception_values( + caplog: pytest.LogCaptureFixture, +) -> None: + # Requirement (logging contract): the new method must not emit any log + # record containing argument values, result values, or exception text, at + # any level — neither on the success path nor on the failure path. + manager = _make_manager() + session = manager.sessions["server"] + session.call_tool.side_effect = ValueError("very specific leak text") + + with ( + caplog.at_level("DEBUG"), + pytest.raises(RuntimeError, match="MCP tool call failed"), + ): + await manager.call_tool_structured("server", "my_tool", {"secret_arg": "shh"}) + + assert "shh" not in caplog.text + assert "very specific leak text" not in caplog.text + assert "secret_arg" not in caplog.text diff --git a/tests/test_web/test_server.py b/tests/test_web/test_server.py index 5e19595c..45551c88 100644 --- a/tests/test_web/test_server.py +++ b/tests/test_web/test_server.py @@ -11,6 +11,7 @@ from __future__ import annotations import asyncio +import json import logging import re import time @@ -1847,3 +1848,268 @@ def test_uses_shared_value_repr_helper(self) -> None: big_value = "x" * 2000 _, _, _, completed = WebDashboard._synth_agent_or_script("big", agent, big_value) assert completed["value_repr"] == render_set_value_repr(big_value) + + +class TestSyntheticReplayMcpStep: + """Coverage for ``WebDashboard._synth_agent_or_script`` mcp branch. + + The synthetic replay path emits ``mcp_started``/``mcp_completed`` when + restoring an mcp step's envelope from a checkpoint on resume. The payload + must match the live engine emitter byte-for-byte — including the + ``result_bytes`` measurement, which is the shared size contract. + """ + + def _mcp_agent(self) -> object: + """Build a minimal AgentDef-like duck typed object for an mcp step.""" + from types import SimpleNamespace + + return SimpleNamespace( + type="mcp", + server="filesystem", + tool="read_file", + arguments={"path": "/tmp/x"}, + ) + + def _expected_result_bytes(self, content: object, structured: object) -> int: + """Independent re-derivation of the envelope byte size. + + Deliberately restates the measurement formula instead of importing the + production helper, so the test fails if the helper's contract drifts. + """ + import json + + return len( + json.dumps( + {"content": content, "structured": structured}, + ensure_ascii=False, + separators=(",", ":"), + ).encode("utf-8") + ) + + def test_envelope_synthesises_mcp_events(self) -> None: + # Requirement: the mcp branch emits mcp_started/mcp_completed with the + # live payload shape (server/tool from the agent def, argument_keys + # sorted, elapsed 0.0 like the set branch). + content = [{"type": "text", "text": "hello", "truncated": False}] + envelope = {"content": content, "structured": None, "is_error": False} + started_type, started, completed_type, completed = WebDashboard._synth_agent_or_script( + "fetch", self._mcp_agent(), envelope + ) + assert started_type == "mcp_started" + assert completed_type == "mcp_completed" + assert started["server"] == "filesystem" + assert started["tool"] == "read_file" + assert started["argument_keys"] == ["path"] + assert started["synthetic"] is True + assert completed["is_error"] is False + assert completed["elapsed"] == 0.0 + assert completed["result_bytes"] == self._expected_result_bytes(content, None) + + def test_result_bytes_match_live_measurement_for_multibyte_text(self) -> None: + # Requirement: result_bytes is byte-identical between live and + # synthetic events — multibyte text must count UTF-8 bytes, not chars. + content = [{"type": "text", "text": "héllo wörld — 中文文本", "truncated": False}] + envelope = {"content": content, "structured": None, "is_error": False} + _, _, _, completed = WebDashboard._synth_agent_or_script( + "fetch", self._mcp_agent(), envelope + ) + expected = self._expected_result_bytes(content, None) + assert completed["result_bytes"] == expected + assert expected > len("héllo wörld — 中文文本") # bytes, not characters + + def test_result_bytes_match_live_measurement_with_structured_payload(self) -> None: + # Requirement: a non-empty structured mapping participates in the size + # measurement exactly as the live emitter measures it. + content = [{"type": "text", "text": "ok", "truncated": False}] + structured = {"answer": "中文字符串", "score": 42} + envelope = {"content": content, "structured": structured, "is_error": False} + _, _, _, completed = WebDashboard._synth_agent_or_script( + "fetch", self._mcp_agent(), envelope + ) + assert completed["result_bytes"] == self._expected_result_bytes(content, structured) + + def test_is_error_restored_but_stored_truncation_markers_suppressed(self) -> None: + # Requirement: is_error is restored from the saved envelope, but + # stored truncated/spill_path markers are NEVER republished on + # synthetic replay — a checkpoint written before ingestion stripping + # existed can carry server-supplied markers, and replaying them would + # present server-controlled data as Conductor-generated metadata. + content = [ + {"type": "text", "text": "big", "truncated": True, "spill_path": "/tmp/spill.txt"} + ] + envelope = {"content": content, "structured": None, "is_error": True} + _, _, _, completed = WebDashboard._synth_agent_or_script( + "fetch", self._mcp_agent(), envelope + ) + assert completed["is_error"] is True + assert completed["truncated"] is False + assert completed["spill_path"] is None + + def test_forged_spill_path_in_stored_envelope_is_dropped(self) -> None: + # Requirement: only Conductor's own truncation markers are replayed — + # a stored envelope carrying a non-string ``spill_path`` (e.g. forged + # by a server before ingestion stripping existed) must not reach the + # event, whose frontend contract types the field as a string. + content = [{"type": "text", "text": "x", "spill_path": {"private_result": "value"}}] + envelope = {"content": content, "structured": None, "is_error": False} + _, _, _, completed = WebDashboard._synth_agent_or_script( + "fetch", self._mcp_agent(), envelope + ) + assert completed["truncated"] is False + assert completed["spill_path"] is None + + +class TestSyntheticReplayMcpGroups: + """Coverage for group synthesis of ``type: mcp`` members (PR review). + + Live group events (``parallel_completed`` / ``for_each_completed``) carry + counts only, never member outputs — but the aggregate ``outputs`` field + the synthetic replay builds from the restored context used to include + saved MCP envelopes (content + structured values), publishing on resume + what live execution deliberately excludes. MCP members must be stripped + from the aggregate and replayed as metadata-only events instead. + """ + + def _mcp_agent(self, name: str = "fetch") -> object: + from types import SimpleNamespace + + return SimpleNamespace( + name=name, + type="mcp", + server="filesystem", + tool="read_file", + arguments={"path": "/tmp/x"}, + ) + + def _envelope(self, answer: object) -> dict[str, object]: + return { + "content": [{"type": "text", "text": f"result-{answer}", "truncated": False}], + "structured": {"answer": answer}, + "is_error": False, + } + + def test_parallel_group_strips_mcp_member_envelopes(self) -> None: + # Requirement: a mixed parallel group replays its mcp member as + # metadata-only mcp_* events (tagged with group_name) plus the + # LLM-less parallel_agent_completed, the aggregate outputs keep only + # the non-mcp member, and no result value appears in any event. + from types import SimpleNamespace + + agent_defs = { + "fetch": self._mcp_agent(), + "summarize": SimpleNamespace(name="summarize", type="agent"), + } + pg = SimpleNamespace(name="grp", agents=["fetch", "summarize"]) + output = { + "outputs": { + "fetch": self._envelope("SECRET_VALUE"), + "summarize": {"text": "notes"}, + }, + "errors": {}, + } + + events = WebDashboard._synth_parallel("grp", pg, output, agent_defs) + + types = [t for t, _ in events] + assert types[0] == "parallel_started" + assert types[-1] == "parallel_completed" + assert "mcp_started" in types and "mcp_completed" in types + completed = dict(events)["parallel_completed"] + assert "fetch" not in completed["outputs"]["outputs"] + assert completed["outputs"]["outputs"]["summarize"] == {"text": "notes"} + mcp_completed = next(data for t, data in events if t == "mcp_completed") + assert mcp_completed["group_name"] == "grp" + assert mcp_completed["server"] == "filesystem" + assert mcp_completed["result_bytes"] > 0 + assert mcp_completed["synthetic"] is True + member_completed = next( + data + for t, data in events + if t == "parallel_agent_completed" and data["agent_name"] == "fetch" + ) + assert member_completed["agent_type"] == "mcp" + assert "output" not in member_completed + assert "SECRET_VALUE" not in json.dumps(events) + + def test_for_each_mcp_group_replays_items_metadata_only(self) -> None: + # Requirement: an mcp for-each group replays each item as the live + # event sequence (item_started -> mcp pair -> item_completed with no + # output), strips the envelopes from the aggregate, and keeps the + # authoritative item count. + from types import SimpleNamespace + + fg = SimpleNamespace(name="loop", agent=self._mcp_agent("worker")) + output = { + "outputs": {"k1": self._envelope(1), "k2": self._envelope(2)}, + "errors": {}, + "count": 2, + } + + events = WebDashboard._synth_for_each("loop", fg, output) + + types = [t for t, _ in events] + assert types[0] == "for_each_started" + assert types[-1] == "for_each_completed" + item_starts = [data for t, data in events if t == "for_each_item_started"] + assert {d["item_key"] for d in item_starts} == {"k1", "k2"} + mcp_pairs = [data for t, data in events if t == "mcp_completed"] + assert {d["item_key"] for d in mcp_pairs} == {"k1", "k2"} + assert all(d["group_name"] == "loop" for d in mcp_pairs) + item_completions = [data for t, data in events if t == "for_each_item_completed"] + assert all("output" not in d for d in item_completions) + completed = dict(events)["for_each_completed"] + assert completed["outputs"]["outputs"] == {} + assert completed["item_count"] == 2 + assert "result-1" not in json.dumps(events) + + def test_for_each_non_mcp_group_keeps_aggregate_outputs(self) -> None: + # Requirement: non-mcp groups replay unchanged — the stripping is + # scoped to the step type whose live events enforce the no-values + # policy. + from types import SimpleNamespace + + fg = SimpleNamespace(name="loop", agent=SimpleNamespace(name="worker", type="agent")) + output = {"outputs": [{"a": 1}], "errors": {}, "count": 1} + + events = WebDashboard._synth_for_each("loop", fg, output) + + types = [t for t, _ in events] + assert types == ["for_each_started", "for_each_completed"] + completed = dict(events)["for_each_completed"] + assert completed["outputs"]["outputs"] == [{"a": 1}] + assert completed["item_count"] == 1 + + def test_group_replay_suppresses_stored_truncation_markers(self) -> None: + # Requirement: stored truncated/spill_path markers are never + # republished on the group synthetic replay paths either — both + # converge on _synth_mcp_pair, and a checkpoint written before + # ingestion stripping existed can carry server-supplied markers. + from types import SimpleNamespace + + marked_envelope = { + "content": [ + { + "type": "text", + "text": "big", + "truncated": True, + "spill_path": "/tmp/server-chosen.txt", + } + ], + "structured": None, + "is_error": False, + } + agent_defs = {"fetch": self._mcp_agent()} + pg = SimpleNamespace(name="grp", agents=["fetch"]) + parallel_events = WebDashboard._synth_parallel( + "grp", pg, {"outputs": {"fetch": marked_envelope}, "errors": {}}, agent_defs + ) + fg = SimpleNamespace(name="loop", agent=self._mcp_agent("worker")) + for_each_events = WebDashboard._synth_for_each( + "loop", fg, {"outputs": {"k1": marked_envelope}, "errors": {}, "count": 1} + ) + + for events in (parallel_events, for_each_events): + for data in (d for t, d in events if t == "mcp_completed"): + assert data["truncated"] is False + assert data["spill_path"] is None + assert "/tmp/server-chosen.txt" not in json.dumps(events)